hemsby commited on
Commit
0dd91bb
·
1 Parent(s): 9e039a4

refactor: split monolith into config, parse_excel, build_network, app

Browse files

- config.py: REWARDS_FACTORS + color palette constants
- parse_excel.py: detection functions + extract_network_data()
- build_network.py: generate_network_html() + HTML template
- app.py: thin Streamlit UI only (~180 lines, was ~750)

Files changed (4) hide show
  1. app.py +43 -566
  2. build_network.py +395 -0
  3. config.py +28 -0
  4. parse_excel.py +195 -0
app.py CHANGED
@@ -1,9 +1,16 @@
 
 
1
  import streamlit as st
2
  import pandas as pd
3
- import numpy as np
4
- import textwrap
5
- import json
6
- import io
 
 
 
 
 
7
 
8
  # =============================================================================
9
  # PAGE CONFIG
@@ -11,557 +18,28 @@ import io
11
  st.set_page_config(
12
  page_title="DECODE Correlation Network Generator",
13
  page_icon="🔗",
14
- layout="wide"
15
  )
16
 
17
- # =============================================================================
18
- # HELPER FUNCTIONS
19
- # =============================================================================
20
-
21
- # Complete REWARDS_FACTORS list - if NOT in this list -> Nonrewards
22
- REWARDS_FACTORS = [
23
- # Core 6 (German)
24
- 'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung',
25
- # Core 6 (English)
26
- 'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement',
27
- # Compound versions (English)
28
- 'Adventure & Thrill', 'Autonomy & Dominance', 'Balance & Security',
29
- 'Discipline & Control', 'Enjoyment & Sensuality', 'Excitement & Playfulness',
30
- # Extended (MX/other)
31
- 'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom'
32
- ]
33
-
34
- def detect_data_start_row(df):
35
- """Find DATA_START_ROW by detecting the 2nd text block in column B."""
36
- in_block = False
37
- block_start = None
38
- blocks = []
39
-
40
- for row_idx in range(df.shape[0]):
41
- val = df.iloc[row_idx, 1]
42
- has_text = pd.notna(val) and isinstance(val, str) and len(str(val).strip()) > 0
43
-
44
- if has_text and not in_block:
45
- in_block = True
46
- block_start = row_idx + 1
47
- elif not has_text and in_block:
48
- in_block = False
49
- blocks.append((block_start, row_idx))
50
- block_start = None
51
-
52
- if in_block:
53
- blocks.append((block_start, df.shape[0]))
54
-
55
- if len(blocks) >= 2:
56
- return blocks[1][0], blocks
57
- elif blocks:
58
- return blocks[0][0], blocks
59
- return None, []
60
-
61
- def detect_cutoff_value(df):
62
- """Find CORR_THRESHOLD by searching for 'Cut-off used in columns' in column B."""
63
- for row_idx in range(df.shape[0]):
64
- val = df.iloc[row_idx, 1]
65
- if pd.notna(val) and isinstance(val, str) and 'cut-off used in columns' in val.lower():
66
- for col_idx in range(df.shape[1]):
67
- cell_val = df.iloc[row_idx, col_idx]
68
- if pd.notna(cell_val) and isinstance(cell_val, (int, float)):
69
- return round(float(cell_val), 2)
70
- return None
71
-
72
- def detect_correlation_column_start(df):
73
- """Find CORR_COL_START by detecting first large column block (>50 cols) in row 5."""
74
- in_block = False
75
- block_start = None
76
- col_blocks = []
77
-
78
- for col_idx in range(df.shape[1]):
79
- val = df.iloc[4, col_idx]
80
- has_data = pd.notna(val) and str(val).strip()
81
- if has_data and not in_block:
82
- in_block = True
83
- block_start = col_idx
84
- elif not has_data and in_block:
85
- in_block = False
86
- col_blocks.append((block_start, col_idx - 1))
87
- block_start = None
88
- if in_block:
89
- col_blocks.append((block_start, df.shape[1] - 1))
90
-
91
- # Find first large block (>50 columns)
92
- for start, end in col_blocks:
93
- if end - start + 1 > 50:
94
- return start
95
- return None
96
-
97
- def detect_nonrewards_patterns(df, data_start_idx):
98
- """Detect Nonrewards patterns in attribute codes (NOT in REWARDS_FACTORS)."""
99
- rewards_count = 0
100
- nonrewards_count = 0
101
-
102
- for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
103
- code = df.iloc[row_idx, 1]
104
- if pd.notna(code) and isinstance(code, str):
105
- if '_PA_' in code:
106
- parts = code.split('_')
107
- if len(parts) >= 3:
108
- factor = parts[2]
109
- if factor in REWARDS_FACTORS:
110
- rewards_count += 1
111
- else:
112
- nonrewards_count += 1
113
-
114
- return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count}
115
-
116
- def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_nodes,
117
- client_name, country_name, brand_name, category_name):
118
- """Generate the HTML network visualization."""
119
-
120
- data_start_idx = data_start_row - 1
121
-
122
- # Get driver codes from row 5
123
- driver_codes = []
124
- for col_idx in range(corr_col_start, df.shape[1]):
125
- driver_code = df.iloc[4, col_idx]
126
- if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip():
127
- driver_codes.append(str(driver_code))
128
- elif pd.isna(driver_code) or driver_code == '':
129
- break
130
-
131
- # Get attributes from rows
132
- attribute_names = []
133
- attribute_codes = []
134
- category_indices = []
135
- nonrewards_attrs = set()
136
-
137
- for row_idx in range(data_start_idx, df.shape[0]):
138
- attr_code = df.iloc[row_idx, 1]
139
- attr_name = df.iloc[row_idx, 2]
140
- cat_idx = df.iloc[row_idx, 3]
141
-
142
- if pd.notna(attr_name) and attr_name != '':
143
- code_str = str(attr_code) if pd.notna(attr_code) else ''
144
- attribute_codes.append(code_str)
145
- attribute_names.append(str(attr_name))
146
-
147
- try:
148
- cat_val = float(cat_idx) if pd.notna(cat_idx) else 0
149
- except (ValueError, TypeError):
150
- cat_val = 0
151
- category_indices.append(cat_val)
152
-
153
- # NEW LOGIC: If factor NOT in REWARDS_FACTORS -> Nonrewards
154
- if '_PA_' in code_str:
155
- parts = code_str.split('_')
156
- if len(parts) >= 3:
157
- factor = parts[2]
158
- if factor not in REWARDS_FACTORS:
159
- nonrewards_attrs.add(str(attr_name))
160
- else:
161
- break
162
-
163
- # Map codes to names
164
- code_to_name = dict(zip(attribute_codes, attribute_names))
165
- driver_names = [code_to_name.get(code, code) for code in driver_codes]
166
- attr_to_cat_idx = dict(zip(attribute_names, category_indices))
167
-
168
- # Build correlation matrix
169
- corr_data = []
170
- for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)):
171
- row_data = []
172
- for col_idx in range(corr_col_start, corr_col_start + len(driver_codes)):
173
- val = df.iloc[row_idx, col_idx]
174
- try:
175
- row_data.append(float(val) if pd.notna(val) else 0)
176
- except (ValueError, TypeError):
177
- row_data.append(0)
178
- corr_data.append(row_data)
179
-
180
- corr_df = pd.DataFrame(corr_data, index=attribute_names, columns=driver_names)
181
-
182
- # Calculate statistics
183
- all_positive_corrs = []
184
- for col in corr_df.columns:
185
- for val in corr_df[col]:
186
- if val >= threshold:
187
- all_positive_corrs.append(val)
188
-
189
- if all_positive_corrs:
190
- avg_corr = np.mean(all_positive_corrs)
191
- max_corr = np.max(all_positive_corrs)
192
- min_corr = threshold
193
- else:
194
- avg_corr = max_corr = min_corr = threshold
195
-
196
- # Helper functions
197
- wrapper = textwrap.TextWrapper(width=15)
198
-
199
- def wrap_label(driver):
200
- if len(driver.split()) > 2:
201
- return '\n'.join(wrapper.wrap(text=driver))
202
- return driver
203
-
204
- # Color palette — outline-based nodes
205
- REWARD_COLOR = '#E03E3E' # warm red
206
- NONREWARD_COLOR = '#2B7AB2' # steel blue
207
- REWARD_BORDER = '#C02020'
208
- NONREWARD_BORDER = '#1A5C8A'
209
- REWARD_BG = '#FDEAEA' # very light red fill
210
- NONREWARD_BG = '#E8F1F8' # very light blue fill
211
- DRIVER_BG = '#2B2B2B' # dark background for selected driver
212
- DRIVER_BORDER = '#000000'
213
- DRIVER_FONT = '#FFFFFF'
214
-
215
- def get_node_colors(name, is_driver=False):
216
- if is_driver:
217
- is_reward = name not in nonrewards_attrs
218
- border = REWARD_BORDER if is_reward else NONREWARD_BORDER
219
- return {
220
- 'background': DRIVER_BG,
221
- 'border': border,
222
- 'highlight': {'background': '#444444', 'border': border},
223
- 'hover': {'background': '#444444', 'border': border}
224
- }
225
- if name in nonrewards_attrs:
226
- return {
227
- 'background': NONREWARD_BG,
228
- 'border': NONREWARD_BORDER,
229
- 'highlight': {'background': '#D0E4F0', 'border': NONREWARD_BORDER},
230
- 'hover': {'background': '#D0E4F0', 'border': NONREWARD_BORDER}
231
- }
232
- return {
233
- 'background': REWARD_BG,
234
- 'border': REWARD_BORDER,
235
- 'highlight': {'background': '#F8D0D0', 'border': REWARD_BORDER},
236
- 'hover': {'background': '#F8D0D0', 'border': REWARD_BORDER}
237
- }
238
-
239
- def get_font_color(name, is_driver=False):
240
- if is_driver:
241
- return DRIVER_FONT
242
- return REWARD_BORDER if name not in nonrewards_attrs else NONREWARD_BORDER
243
-
244
- def get_edge_color(name):
245
- return REWARD_COLOR if name not in nonrewards_attrs else NONREWARD_COLOR
246
-
247
- def scale_edge(corr_val):
248
- if max_corr == min_corr:
249
- return {'width': 3.0, 'opacity': 0.7}
250
- norm = (corr_val - min_corr) / (max_corr - min_corr)
251
- return {'width': round(1 + norm * 7, 2), 'opacity': round(0.3 + norm * 0.7, 2)}
252
-
253
- def get_nodes_edges(selected):
254
- if selected not in corr_df.columns:
255
- return [], []
256
-
257
- nodes, edges = [], []
258
-
259
- cat_idx = attr_to_cat_idx.get(selected, 100)
260
- nodes.append({
261
- 'id': selected,
262
- 'label': wrap_label(selected) + '\n(' + str(int(cat_idx)) + ')',
263
- 'level': 0, 'value': int(cat_idx), 'title': selected + ' — Category Index: ' + str(int(cat_idx)),
264
- 'color': get_node_colors(selected, is_driver=True),
265
- 'font': {'color': DRIVER_FONT, 'size': 16, 'bold': True},
266
- 'shape': 'box',
267
- 'borderWidth': 3,
268
- 'borderWidthSelected': 4,
269
- })
270
-
271
- l1_nodes = []
272
- col_data = corr_df[selected]
273
- corrs = [(attr, float(val)) for attr, val in col_data.items()
274
- if attr != selected and float(val) >= threshold]
275
- corrs.sort(key=lambda x: x[1], reverse=True)
276
-
277
- for attr, val in corrs[:max_l1_nodes]:
278
- l1_nodes.append(attr)
279
- cat = attr_to_cat_idx.get(attr, 100)
280
- nodes.append({
281
- 'id': attr, 'label': wrap_label(attr) + '\n(' + str(int(cat)) + ')',
282
- 'level': 1, 'value': int(cat),
283
- 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
284
- 'color': get_node_colors(attr),
285
- 'font': {'color': get_font_color(attr), 'size': 14},
286
- 'borderWidth': 2,
287
- })
288
- ep = scale_edge(val)
289
- edges.append({
290
- 'from': selected, 'to': attr, 'value': float(val),
291
- 'width': ep['width'],
292
- 'color': {'color': get_edge_color(selected), 'opacity': ep['opacity'], 'highlight': get_edge_color(selected)},
293
- 'title': f'{selected} ↔ {attr}: {val:.1f}'
294
- })
295
-
296
- l2_added = set()
297
- for l1 in l1_nodes:
298
- if l1 in corr_df.columns:
299
- col_data = corr_df[l1]
300
- l2_corrs = [(attr, float(val)) for attr, val in col_data.items()
301
- if attr != selected and attr not in l1_nodes and float(val) >= threshold]
302
- l2_corrs.sort(key=lambda x: x[1], reverse=True)
303
-
304
- for attr, val in l2_corrs[:max_l1_nodes]:
305
- if attr not in l2_added:
306
- cat = attr_to_cat_idx.get(attr, 100)
307
- nodes.append({
308
- 'id': attr, 'label': wrap_label(attr) + '\n(' + str(int(cat)) + ')',
309
- 'level': 2, 'value': int(cat),
310
- 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
311
- 'color': get_node_colors(attr),
312
- 'font': {'color': get_font_color(attr), 'size': 13},
313
- 'borderWidth': 2,
314
- })
315
- l2_added.add(attr)
316
- ep = scale_edge(val)
317
- edges.append({
318
- 'from': l1, 'to': attr, 'value': float(val),
319
- 'width': ep['width'],
320
- 'color': {'color': get_edge_color(l1), 'opacity': ep['opacity'], 'highlight': get_edge_color(l1)},
321
- 'title': f'{l1} ↔ {attr}: {val:.1f}'
322
- })
323
-
324
- return nodes, edges
325
-
326
- # Generate all networks
327
- all_nodes, all_edges = [], []
328
- available_drivers = sorted(driver_names, key=lambda x: x.lower())
329
-
330
- for driver in available_drivers:
331
- n, e = get_nodes_edges(driver)
332
- all_nodes.append(n)
333
- all_edges.append(e)
334
-
335
- chart_title = f"DECODE_{client_name}_{country_name}_{brand_name}"
336
-
337
- # Build driver options HTML
338
- driver_options = ""
339
- for i, nodes_list in enumerate(all_nodes):
340
- if nodes_list:
341
- driver_options += f'<option value="{i}">{nodes_list[0]["id"]}</option>\n'
342
-
343
- # Count rewards vs nonrewards in drivers
344
- reward_drivers = sum(1 for d in available_drivers if d not in nonrewards_attrs)
345
- nonreward_drivers = len(available_drivers) - reward_drivers
346
-
347
- # HTML template
348
- html_template = """<!DOCTYPE html>
349
- <html lang="en">
350
- <head>
351
- <meta charset="utf-8">
352
- <title>""" + chart_title + """ — Association Network</title>
353
- <link type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" />
354
- <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
355
- <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
356
- <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
357
- <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
358
- <style>
359
- * { box-sizing: border-box; margin: 0; padding: 0; }
360
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; }
361
-
362
- /* Header */
363
- .header { background: #fff; border-bottom: 1px solid #e0e0e0; padding: 16px 24px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
364
- .header-left h1 { font-size: 18px; font-weight: 600; color: #1a1a1a; }
365
- .header-left .subtitle { font-size: 13px; color: #888; margin-top: 2px; }
366
- .header-right { display: flex; align-items: center; gap: 16px; }
367
-
368
- /* Toolbar */
369
- .toolbar { background: #fff; border-bottom: 1px solid #e0e0e0; padding: 10px 24px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
370
- .toolbar label { font-size: 13px; font-weight: 500; color: #555; }
371
- .select2-container { min-width: 320px; }
372
- .select2-container .select2-selection--single { height: 36px; border-radius: 6px; border-color: #ccc; }
373
- .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 34px; font-size: 14px; padding-left: 12px; }
374
- .select2-container--default .select2-selection--single .select2-selection__arrow { height: 34px; }
375
- .select2-results__option { font-size: 14px; }
376
- .stat { font-size: 13px; color: #888; }
377
- .stat strong { color: #333; }
378
-
379
- /* Legend (inline, compact) */
380
- .legend-bar { display: flex; align-items: center; gap: 16px; margin-left: auto; }
381
- .legend-item { display: flex; align-items: center; gap: 5px; font-size: 12px; color: #666; }
382
- .legend-dot { width: 12px; height: 12px; border-radius: 3px; border: 2px solid; }
383
- .legend-dot.reward { border-color: #C02020; background: #FDEAEA; }
384
- .legend-dot.nonreward { border-color: #1A5C8A; background: #E8F1F8; }
385
- .legend-dot.driver { border-color: #000; background: #2B2B2B; }
386
-
387
- /* Network canvas */
388
- #mynetwork { width: 100%; height: calc(100vh - 130px); background: #fff; }
389
-
390
- /* Tabs */
391
- .tabs { position: absolute; bottom: 16px; left: 24px; z-index: 10; display: flex; gap: 4px; }
392
- .tab-btn { padding: 6px 14px; font-size: 12px; font-weight: 500; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; color: #555; transition: all 0.15s; }
393
- .tab-btn:hover { background: #f0f0f0; }
394
- .tab-btn.active { background: #333; color: #fff; border-color: #333; }
395
-
396
- /* Details panel (slide-up) */
397
- .details-panel { position: absolute; bottom: 0; left: 0; right: 0; z-index: 20; background: #fff; border-top: 1px solid #e0e0e0; box-shadow: 0 -4px 20px rgba(0,0,0,0.08); transform: translateY(100%); transition: transform 0.25s ease; max-height: 45vh; overflow-y: auto; }
398
- .details-panel.open { transform: translateY(0); }
399
- .details-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; border-bottom: 1px solid #eee; position: sticky; top: 0; background: #fff; }
400
- .details-header h3 { font-size: 14px; font-weight: 600; }
401
- .details-close { background: none; border: none; font-size: 18px; cursor: pointer; color: #888; padding: 4px 8px; border-radius: 4px; }
402
- .details-close:hover { background: #f0f0f0; }
403
- .details-body { padding: 16px 24px; }
404
- .details-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }
405
- .detail-card { padding: 12px; border: 1px solid #eee; border-radius: 8px; background: #fafafa; }
406
- .detail-card h4 { font-size: 12px; font-weight: 600; color: #888; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }
407
- .detail-card p { font-size: 13px; line-height: 1.5; color: #444; }
408
- .detail-card .val { font-size: 20px; font-weight: 600; color: #1a1a1a; }
409
-
410
- /* Canvas wrapper (for relative positioning of tabs) */
411
- .canvas-wrap { position: relative; flex: 1; }
412
- </style>
413
- <script>
414
- var nodes = """ + json.dumps(all_nodes) + """;
415
- var edges = """ + json.dumps(all_edges) + """;
416
- var network = null;
417
-
418
- function destroy() { if (network !== null) { network.destroy(); network = null; } }
419
-
420
- function draw(id) {
421
- destroy();
422
- var data = { nodes: nodes[id], edges: edges[id] };
423
- var options = {
424
- nodes: {
425
- shape: 'box',
426
- scaling: { min: 20, max: 80, label: { enabled: true, min: 11, max: 20 } },
427
- font: { size: 14, face: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif', multi: 'md' },
428
- margin: { top: 8, bottom: 8, left: 12, right: 12 },
429
- shadow: { enabled: true, color: 'rgba(0,0,0,0.08)', size: 6, x: 0, y: 2 },
430
- shapeProperties: { borderRadius: 6 }
431
- },
432
- edges: {
433
- smooth: { type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 },
434
- shadow: false,
435
- hoverWidth: 1.5
436
- },
437
- physics: {
438
- enabled: true,
439
- solver: 'hierarchicalRepulsion',
440
- hierarchicalRepulsion: { nodeDistance: 280, centralGravity: 0.0, springLength: 280, springConstant: 0.01, damping: 0.09, avoidOverlap: 1 },
441
- stabilization: { enabled: true, iterations: 1000 }
442
- },
443
- interaction: { zoomView: true, dragView: true, hover: true, tooltipDelay: 200 },
444
- layout: { hierarchical: false }
445
- };
446
- network = new vis.Network(document.getElementById('mynetwork'), data, options);
447
- document.getElementById('nodeCount').textContent = data.nodes.length;
448
- document.getElementById('edgeCount').textContent = data.edges.length;
449
- }
450
-
451
- function toggleDetails() {
452
- var panel = document.getElementById('detailsPanel');
453
- var btn = document.getElementById('detailsBtn');
454
- panel.classList.toggle('open');
455
- btn.classList.toggle('active');
456
- }
457
-
458
- $(document).ready(function() {
459
- $('#driver_select').select2({ placeholder: 'Search for an attribute...', allowClear: false });
460
- $('#driver_select').on('change', function() { draw($(this).val()); });
461
- draw(0);
462
- });
463
- </script>
464
- </head>
465
- <body style="display:flex; flex-direction:column; height:100vh; overflow:hidden;">
466
-
467
- <div class="header">
468
- <div class="header-left">
469
- <h1>""" + chart_title + """</h1>
470
- <div class="subtitle">Association Network</div>
471
- </div>
472
- <div class="header-right">
473
- <div class="legend-bar">
474
- <div class="legend-item"><div class="legend-dot reward"></div> Emotional</div>
475
- <div class="legend-item"><div class="legend-dot nonreward"></div> Functional</div>
476
- <div class="legend-item"><div class="legend-dot driver"></div> Selected</div>
477
- </div>
478
- </div>
479
- </div>
480
-
481
- <div class="toolbar">
482
- <label>Attribute:</label>
483
- <select id="driver_select">
484
- """ + driver_options + """
485
- </select>
486
- <span class="stat">Nodes: <strong id="nodeCount">0</strong></span>
487
- <span class="stat">Edges: <strong id="edgeCount">0</strong></span>
488
- </div>
489
-
490
- <div class="canvas-wrap">
491
- <div id="mynetwork"></div>
492
- <div class="tabs">
493
- <button class="tab-btn" id="detailsBtn" onclick="toggleDetails()">Details</button>
494
- </div>
495
- <div class="details-panel" id="detailsPanel">
496
- <div class="details-header">
497
- <h3>Technical Details</h3>
498
- <button class="details-close" onclick="toggleDetails()">&times;</button>
499
- </div>
500
- <div class="details-body">
501
- <div class="details-grid">
502
- <div class="detail-card">
503
- <h4>Threshold</h4>
504
- <div class="val">""" + str(threshold) + """</div>
505
- <p>Only associations above this deviation value are shown as connections.</p>
506
- </div>
507
- <div class="detail-card">
508
- <h4>Attributes</h4>
509
- <div class="val">""" + str(len(attribute_names)) + """</div>
510
- <p>""" + str(reward_drivers) + """ emotional (rewards) and """ + str(nonreward_drivers) + """ functional (nonrewards) attributes.</p>
511
- </div>
512
- <div class="detail-card">
513
- <h4>Connections</h4>
514
- <div class="val">""" + str(len(all_positive_corrs)) + """</div>
515
- <p>Total attribute pairs above threshold. Avg: """ + f"{avg_corr:.1f}" + """, Max: """ + f"{max_corr:.1f}" + """</p>
516
- </div>
517
- <div class="detail-card">
518
- <h4>How to Read</h4>
519
- <p>Each node is a brand association. Lines connect associations that co-occur above average.
520
- Thicker lines = stronger co-occurrence. Node size reflects Category Index (importance).
521
- Hover over nodes and lines for details.</p>
522
- </div>
523
- </div>
524
- </div>
525
- </div>
526
- </div>
527
-
528
- </body>
529
- </html>"""
530
-
531
- stats = {
532
- 'drivers': len(available_drivers),
533
- 'attributes': len(attribute_names),
534
- 'rewards': len(attribute_names) - len(nonrewards_attrs),
535
- 'nonrewards': len(nonrewards_attrs),
536
- 'positive_correlations': len(all_positive_corrs)
537
- }
538
-
539
- filename = f"{chart_title}_{category_name}_Correlation_Network_strength_DEVIATION.html"
540
-
541
- return html_template, stats, filename
542
-
543
- # =============================================================================
544
- # STREAMLIT UI
545
- # =============================================================================
546
-
547
  st.title("🔗 DECODE Correlation Network Generator")
548
  st.markdown("**Generate interactive HTML network visualizations from correlation matrices (DEVIATION data)**")
549
-
550
  st.markdown("---")
551
 
552
- # Section 1: File Upload
 
 
553
  st.header("1. Upload Excel File")
554
 
555
  uploaded_file = st.file_uploader(
556
  "Choose your correlation Excel file",
557
  type=['xlsx', 'xls'],
558
- help="Upload the Excel file containing your correlation matrix"
559
  )
560
 
561
  worksheet_name = st.text_input(
562
  "Worksheet Name",
563
  value="Results Correls",
564
- help="Name of the worksheet containing the correlation data"
565
  )
566
 
567
  # Initialize session state
@@ -576,7 +54,6 @@ if uploaded_file is not None:
576
  df = pd.read_excel(uploaded_file, sheet_name=worksheet_name, header=None)
577
  st.session_state.df = df
578
 
579
- # Auto-detect parameters
580
  detected_row, blocks = detect_data_start_row(df)
581
  detected_cutoff = detect_cutoff_value(df)
582
  detected_col = detect_correlation_column_start(df)
@@ -587,12 +64,11 @@ if uploaded_file is not None:
587
  'col': detected_col,
588
  'cutoff': detected_cutoff,
589
  'blocks': blocks,
590
- 'patterns': patterns
591
  }
592
 
593
  st.success(f"✅ File loaded: {df.shape[0]} rows × {df.shape[1]} columns")
594
 
595
- # Show detected values
596
  with st.expander("📊 Auto-detected Values", expanded=True):
597
  col1, col2 = st.columns(2)
598
  with col1:
@@ -621,7 +97,9 @@ if uploaded_file is not None:
621
 
622
  st.markdown("---")
623
 
624
- # Section 2: Parameters
 
 
625
  st.header("2. Data Parameters")
626
  st.caption("Adjust auto-detected values if needed")
627
 
@@ -632,16 +110,15 @@ with col1:
632
  "Data Start Row",
633
  min_value=1,
634
  value=st.session_state.detected_values.get('row', 97) or 97,
635
- help="Excel row number where data starts (1-based)"
636
  )
637
-
638
  threshold = st.number_input(
639
  "Correlation Threshold",
640
  min_value=0.0,
641
  value=float(st.session_state.detected_values.get('cutoff', 6.0) or 6.0),
642
  step=0.1,
643
  format="%.2f",
644
- help="Higher = fewer connections, Lower = more connections"
645
  )
646
 
647
  with col2:
@@ -649,20 +126,21 @@ with col2:
649
  "Correlation Column Start",
650
  min_value=0,
651
  value=st.session_state.detected_values.get('col', 32) or 32,
652
- help="Column index where correlation data starts (0-based)"
653
  )
654
-
655
  max_l1_nodes = st.number_input(
656
  "Max L1 Connections",
657
  min_value=1,
658
  max_value=20,
659
  value=5,
660
- help="Maximum number of Level 1 connections per node"
661
  )
662
 
663
  st.markdown("---")
664
 
665
- # Section 3: Project Details
 
 
666
  st.header("3. Project Details")
667
  st.caption("Used for output filename")
668
 
@@ -678,16 +156,17 @@ with col2:
678
 
679
  st.markdown("---")
680
 
681
- # Section 4: Generate
 
 
682
  st.header("4. Generate Network")
683
 
684
- # Validation
685
  can_generate = (
686
- st.session_state.df is not None and
687
- client_name.strip() and
688
- country_name.strip() and
689
- brand_name.strip() and
690
- category_name.strip()
691
  )
692
 
693
  if not can_generate:
@@ -702,42 +181,40 @@ if not can_generate:
702
  missing.append("Brand Name")
703
  if not category_name.strip():
704
  missing.append("Category")
705
-
706
  st.warning(f"⚠️ Please complete: {', '.join(missing)}")
707
 
708
  if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="primary"):
709
  with st.spinner("Generating network..."):
710
  try:
 
 
 
 
711
  html_content, stats, filename = generate_network_html(
712
- st.session_state.df,
713
- data_start_row,
714
- corr_col_start,
715
  threshold,
716
  max_l1_nodes,
717
  client_name.strip(),
718
  country_name.strip(),
719
  brand_name.strip(),
720
- category_name.strip()
721
  )
722
 
723
  st.success("✅ Network generated successfully!")
724
 
725
- # Show stats
726
  col1, col2, col3, col4 = st.columns(4)
727
  col1.metric("Drivers", stats['drivers'])
728
  col2.metric("Rewards (red)", stats['rewards'])
729
  col3.metric("Nonrewards (blue)", stats['nonrewards'])
730
  col4.metric("Correlations", stats['positive_correlations'])
731
 
732
- # Download button
733
  st.download_button(
734
  label="📥 Download HTML File",
735
  data=html_content,
736
  file_name=filename,
737
  mime="text/html",
738
- type="primary"
739
  )
740
-
741
  st.caption(f"Filename: `{filename}`")
742
 
743
  except Exception as e:
 
1
+ """Streamlit UI for the DECODE Correlation Network Generator."""
2
+
3
  import streamlit as st
4
  import pandas as pd
5
+
6
+ from parse_excel import (
7
+ detect_data_start_row,
8
+ detect_cutoff_value,
9
+ detect_correlation_column_start,
10
+ detect_nonrewards_patterns,
11
+ extract_network_data,
12
+ )
13
+ from build_network import generate_network_html
14
 
15
  # =============================================================================
16
  # PAGE CONFIG
 
18
  st.set_page_config(
19
  page_title="DECODE Correlation Network Generator",
20
  page_icon="🔗",
21
+ layout="wide",
22
  )
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  st.title("🔗 DECODE Correlation Network Generator")
25
  st.markdown("**Generate interactive HTML network visualizations from correlation matrices (DEVIATION data)**")
 
26
  st.markdown("---")
27
 
28
+ # =============================================================================
29
+ # 1. FILE UPLOAD
30
+ # =============================================================================
31
  st.header("1. Upload Excel File")
32
 
33
  uploaded_file = st.file_uploader(
34
  "Choose your correlation Excel file",
35
  type=['xlsx', 'xls'],
36
+ help="Upload the Excel file containing your correlation matrix",
37
  )
38
 
39
  worksheet_name = st.text_input(
40
  "Worksheet Name",
41
  value="Results Correls",
42
+ help="Name of the worksheet containing the correlation data",
43
  )
44
 
45
  # Initialize session state
 
54
  df = pd.read_excel(uploaded_file, sheet_name=worksheet_name, header=None)
55
  st.session_state.df = df
56
 
 
57
  detected_row, blocks = detect_data_start_row(df)
58
  detected_cutoff = detect_cutoff_value(df)
59
  detected_col = detect_correlation_column_start(df)
 
64
  'col': detected_col,
65
  'cutoff': detected_cutoff,
66
  'blocks': blocks,
67
+ 'patterns': patterns,
68
  }
69
 
70
  st.success(f"✅ File loaded: {df.shape[0]} rows × {df.shape[1]} columns")
71
 
 
72
  with st.expander("📊 Auto-detected Values", expanded=True):
73
  col1, col2 = st.columns(2)
74
  with col1:
 
97
 
98
  st.markdown("---")
99
 
100
+ # =============================================================================
101
+ # 2. PARAMETERS
102
+ # =============================================================================
103
  st.header("2. Data Parameters")
104
  st.caption("Adjust auto-detected values if needed")
105
 
 
110
  "Data Start Row",
111
  min_value=1,
112
  value=st.session_state.detected_values.get('row', 97) or 97,
113
+ help="Excel row number where data starts (1-based)",
114
  )
 
115
  threshold = st.number_input(
116
  "Correlation Threshold",
117
  min_value=0.0,
118
  value=float(st.session_state.detected_values.get('cutoff', 6.0) or 6.0),
119
  step=0.1,
120
  format="%.2f",
121
+ help="Higher = fewer connections, Lower = more connections",
122
  )
123
 
124
  with col2:
 
126
  "Correlation Column Start",
127
  min_value=0,
128
  value=st.session_state.detected_values.get('col', 32) or 32,
129
+ help="Column index where correlation data starts (0-based)",
130
  )
 
131
  max_l1_nodes = st.number_input(
132
  "Max L1 Connections",
133
  min_value=1,
134
  max_value=20,
135
  value=5,
136
+ help="Maximum number of Level 1 connections per node",
137
  )
138
 
139
  st.markdown("---")
140
 
141
+ # =============================================================================
142
+ # 3. PROJECT DETAILS
143
+ # =============================================================================
144
  st.header("3. Project Details")
145
  st.caption("Used for output filename")
146
 
 
156
 
157
  st.markdown("---")
158
 
159
+ # =============================================================================
160
+ # 4. GENERATE
161
+ # =============================================================================
162
  st.header("4. Generate Network")
163
 
 
164
  can_generate = (
165
+ st.session_state.df is not None
166
+ and client_name.strip()
167
+ and country_name.strip()
168
+ and brand_name.strip()
169
+ and category_name.strip()
170
  )
171
 
172
  if not can_generate:
 
181
  missing.append("Brand Name")
182
  if not category_name.strip():
183
  missing.append("Category")
 
184
  st.warning(f"⚠️ Please complete: {', '.join(missing)}")
185
 
186
  if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="primary"):
187
  with st.spinner("Generating network..."):
188
  try:
189
+ network_data = extract_network_data(
190
+ st.session_state.df, data_start_row, corr_col_start
191
+ )
192
+
193
  html_content, stats, filename = generate_network_html(
194
+ network_data,
 
 
195
  threshold,
196
  max_l1_nodes,
197
  client_name.strip(),
198
  country_name.strip(),
199
  brand_name.strip(),
200
+ category_name.strip(),
201
  )
202
 
203
  st.success("✅ Network generated successfully!")
204
 
 
205
  col1, col2, col3, col4 = st.columns(4)
206
  col1.metric("Drivers", stats['drivers'])
207
  col2.metric("Rewards (red)", stats['rewards'])
208
  col3.metric("Nonrewards (blue)", stats['nonrewards'])
209
  col4.metric("Correlations", stats['positive_correlations'])
210
 
 
211
  st.download_button(
212
  label="📥 Download HTML File",
213
  data=html_content,
214
  file_name=filename,
215
  mime="text/html",
216
+ type="primary",
217
  )
 
218
  st.caption(f"Filename: `{filename}`")
219
 
220
  except Exception as e:
build_network.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate interactive HTML network visualization from parsed correlation data."""
2
+
3
+ import json
4
+ import textwrap
5
+ import numpy as np
6
+ from config import COLORS
7
+
8
+
9
+ def generate_network_html(network_data, threshold, max_l1_nodes,
10
+ client_name, country_name, brand_name, category_name):
11
+ """Build the complete HTML file with vis.js network visualization.
12
+
13
+ Args:
14
+ network_data: Dict from parse_excel.extract_network_data()
15
+ threshold: Minimum correlation value to show as a connection
16
+ max_l1_nodes: Max number of Level 1 connections per node
17
+ client_name, country_name, brand_name, category_name: Project metadata
18
+
19
+ Returns:
20
+ (html_string, stats_dict, filename)
21
+ """
22
+ corr_df = network_data['corr_df']
23
+ attribute_names = network_data['attribute_names']
24
+ nonrewards_attrs = network_data['nonrewards_attrs']
25
+ driver_names = network_data['driver_names']
26
+ attr_to_cat_idx = network_data['attr_to_cat_idx']
27
+
28
+ # Calculate statistics
29
+ all_positive_corrs = []
30
+ for col in corr_df.columns:
31
+ for val in corr_df[col]:
32
+ if val >= threshold:
33
+ all_positive_corrs.append(val)
34
+
35
+ if all_positive_corrs:
36
+ avg_corr = np.mean(all_positive_corrs)
37
+ max_corr = np.max(all_positive_corrs)
38
+ min_corr = threshold
39
+ else:
40
+ avg_corr = max_corr = min_corr = threshold
41
+
42
+ # --- Styling helpers ---
43
+
44
+ wrapper = textwrap.TextWrapper(width=15)
45
+
46
+ def wrap_label(text):
47
+ if len(text.split()) > 2:
48
+ return '\n'.join(wrapper.wrap(text=text))
49
+ return text
50
+
51
+ def is_reward(name):
52
+ return name not in nonrewards_attrs
53
+
54
+ def get_node_colors(name, is_driver=False):
55
+ c = COLORS
56
+ if is_driver:
57
+ border = c['reward_border'] if is_reward(name) else c['nonreward_border']
58
+ return {
59
+ 'background': c['driver_bg'], 'border': border,
60
+ 'highlight': {'background': '#444444', 'border': border},
61
+ 'hover': {'background': '#444444', 'border': border},
62
+ }
63
+ if not is_reward(name):
64
+ return {
65
+ 'background': c['nonreward_bg'], 'border': c['nonreward_border'],
66
+ 'highlight': {'background': '#D0E4F0', 'border': c['nonreward_border']},
67
+ 'hover': {'background': '#D0E4F0', 'border': c['nonreward_border']},
68
+ }
69
+ return {
70
+ 'background': c['reward_bg'], 'border': c['reward_border'],
71
+ 'highlight': {'background': '#F8D0D0', 'border': c['reward_border']},
72
+ 'hover': {'background': '#F8D0D0', 'border': c['reward_border']},
73
+ }
74
+
75
+ def get_font_color(name, is_driver=False):
76
+ if is_driver:
77
+ return COLORS['driver_font']
78
+ return COLORS['reward_border'] if is_reward(name) else COLORS['nonreward_border']
79
+
80
+ def get_edge_color(name):
81
+ return COLORS['reward_color'] if is_reward(name) else COLORS['nonreward_color']
82
+
83
+ def scale_edge(corr_val):
84
+ if max_corr == min_corr:
85
+ return {'width': 3.0, 'opacity': 0.7}
86
+ norm = (corr_val - min_corr) / (max_corr - min_corr)
87
+ return {'width': round(1 + norm * 7, 2), 'opacity': round(0.3 + norm * 0.7, 2)}
88
+
89
+ # --- Build node/edge data for each driver ---
90
+
91
+ def get_nodes_edges(selected):
92
+ if selected not in corr_df.columns:
93
+ return [], []
94
+
95
+ nodes, edges = [], []
96
+
97
+ # Level 0: selected driver
98
+ cat_idx = attr_to_cat_idx.get(selected, 100)
99
+ nodes.append({
100
+ 'id': selected,
101
+ 'label': wrap_label(selected) + '\n(' + str(int(cat_idx)) + ')',
102
+ 'level': 0, 'value': int(cat_idx),
103
+ 'title': selected + ' — Category Index: ' + str(int(cat_idx)),
104
+ 'color': get_node_colors(selected, is_driver=True),
105
+ 'font': {'color': COLORS['driver_font'], 'size': 16, 'bold': True},
106
+ 'shape': 'box', 'borderWidth': 3, 'borderWidthSelected': 4,
107
+ })
108
+
109
+ # Level 1: top correlated attributes
110
+ l1_nodes = []
111
+ col_data = corr_df[selected]
112
+ corrs = [(attr, float(val)) for attr, val in col_data.items()
113
+ if attr != selected and float(val) >= threshold]
114
+ corrs.sort(key=lambda x: x[1], reverse=True)
115
+
116
+ for attr, val in corrs[:max_l1_nodes]:
117
+ l1_nodes.append(attr)
118
+ cat = attr_to_cat_idx.get(attr, 100)
119
+ nodes.append({
120
+ 'id': attr, 'label': wrap_label(attr) + '\n(' + str(int(cat)) + ')',
121
+ 'level': 1, 'value': int(cat),
122
+ 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
123
+ 'color': get_node_colors(attr),
124
+ 'font': {'color': get_font_color(attr), 'size': 14},
125
+ 'borderWidth': 2,
126
+ })
127
+ ep = scale_edge(val)
128
+ edges.append({
129
+ 'from': selected, 'to': attr, 'value': float(val),
130
+ 'width': ep['width'],
131
+ 'color': {'color': get_edge_color(selected), 'opacity': ep['opacity'],
132
+ 'highlight': get_edge_color(selected)},
133
+ 'title': f'{selected} \u2194 {attr}: {val:.1f}',
134
+ })
135
+
136
+ # Level 2: secondary correlations from L1 nodes
137
+ l2_added = set()
138
+ for l1 in l1_nodes:
139
+ if l1 in corr_df.columns:
140
+ col_data = corr_df[l1]
141
+ l2_corrs = [(attr, float(val)) for attr, val in col_data.items()
142
+ if attr != selected and attr not in l1_nodes and float(val) >= threshold]
143
+ l2_corrs.sort(key=lambda x: x[1], reverse=True)
144
+
145
+ for attr, val in l2_corrs[:max_l1_nodes]:
146
+ if attr not in l2_added:
147
+ cat = attr_to_cat_idx.get(attr, 100)
148
+ nodes.append({
149
+ 'id': attr, 'label': wrap_label(attr) + '\n(' + str(int(cat)) + ')',
150
+ 'level': 2, 'value': int(cat),
151
+ 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
152
+ 'color': get_node_colors(attr),
153
+ 'font': {'color': get_font_color(attr), 'size': 13},
154
+ 'borderWidth': 2,
155
+ })
156
+ l2_added.add(attr)
157
+ ep = scale_edge(val)
158
+ edges.append({
159
+ 'from': l1, 'to': attr, 'value': float(val),
160
+ 'width': ep['width'],
161
+ 'color': {'color': get_edge_color(l1), 'opacity': ep['opacity'],
162
+ 'highlight': get_edge_color(l1)},
163
+ 'title': f'{l1} \u2194 {attr}: {val:.1f}',
164
+ })
165
+
166
+ return nodes, edges
167
+
168
+ # Generate networks for all drivers
169
+ all_nodes, all_edges = [], []
170
+ available_drivers = sorted(driver_names, key=lambda x: x.lower())
171
+
172
+ for driver in available_drivers:
173
+ n, e = get_nodes_edges(driver)
174
+ all_nodes.append(n)
175
+ all_edges.append(e)
176
+
177
+ chart_title = f"DECODE_{client_name}_{country_name}_{brand_name}"
178
+
179
+ # Build driver options HTML
180
+ driver_options = ""
181
+ for i, nodes_list in enumerate(all_nodes):
182
+ if nodes_list:
183
+ driver_options += f'<option value="{i}">{nodes_list[0]["id"]}</option>\n'
184
+
185
+ # Count rewards vs nonrewards in drivers
186
+ reward_drivers = sum(1 for d in available_drivers if is_reward(d))
187
+ nonreward_drivers = len(available_drivers) - reward_drivers
188
+
189
+ # --- HTML template ---
190
+ html = _build_html_template(
191
+ chart_title=chart_title,
192
+ all_nodes=all_nodes,
193
+ all_edges=all_edges,
194
+ driver_options=driver_options,
195
+ threshold=threshold,
196
+ attribute_count=len(attribute_names),
197
+ reward_drivers=reward_drivers,
198
+ nonreward_drivers=nonreward_drivers,
199
+ corr_count=len(all_positive_corrs),
200
+ avg_corr=avg_corr,
201
+ max_corr=max_corr,
202
+ )
203
+
204
+ stats = {
205
+ 'drivers': len(available_drivers),
206
+ 'attributes': len(attribute_names),
207
+ 'rewards': len(attribute_names) - len(nonrewards_attrs),
208
+ 'nonrewards': len(nonrewards_attrs),
209
+ 'positive_correlations': len(all_positive_corrs),
210
+ }
211
+
212
+ filename = f"{chart_title}_{category_name}_Correlation_Network_strength_DEVIATION.html"
213
+
214
+ return html, stats, filename
215
+
216
+
217
+ def _build_html_template(*, chart_title, all_nodes, all_edges, driver_options,
218
+ threshold, attribute_count, reward_drivers, nonreward_drivers,
219
+ corr_count, avg_corr, max_corr):
220
+ """Build the standalone HTML string. Separated for readability."""
221
+
222
+ return f"""<!DOCTYPE html>
223
+ <html lang="en">
224
+ <head>
225
+ <meta charset="utf-8">
226
+ <title>{chart_title} — Association Network</title>
227
+ <link type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" />
228
+ <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
229
+ <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
230
+ <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
231
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
232
+ <style>
233
+ * {{ box-sizing: border-box; margin: 0; padding: 0; }}
234
+ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; }}
235
+
236
+ .header {{ background: #fff; border-bottom: 1px solid #e0e0e0; padding: 16px 24px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }}
237
+ .header-left h1 {{ font-size: 18px; font-weight: 600; color: #1a1a1a; }}
238
+ .header-left .subtitle {{ font-size: 13px; color: #888; margin-top: 2px; }}
239
+
240
+ .toolbar {{ background: #fff; border-bottom: 1px solid #e0e0e0; padding: 10px 24px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }}
241
+ .toolbar label {{ font-size: 13px; font-weight: 500; color: #555; }}
242
+ .select2-container {{ min-width: 320px; }}
243
+ .select2-container .select2-selection--single {{ height: 36px; border-radius: 6px; border-color: #ccc; }}
244
+ .select2-container--default .select2-selection--single .select2-selection__rendered {{ line-height: 34px; font-size: 14px; padding-left: 12px; }}
245
+ .select2-container--default .select2-selection--single .select2-selection__arrow {{ height: 34px; }}
246
+ .select2-results__option {{ font-size: 14px; }}
247
+ .stat {{ font-size: 13px; color: #888; }}
248
+ .stat strong {{ color: #333; }}
249
+
250
+ .legend-bar {{ display: flex; align-items: center; gap: 16px; margin-left: auto; }}
251
+ .legend-item {{ display: flex; align-items: center; gap: 5px; font-size: 12px; color: #666; }}
252
+ .legend-dot {{ width: 12px; height: 12px; border-radius: 3px; border: 2px solid; }}
253
+ .legend-dot.reward {{ border-color: {COLORS['reward_border']}; background: {COLORS['reward_bg']}; }}
254
+ .legend-dot.nonreward {{ border-color: {COLORS['nonreward_border']}; background: {COLORS['nonreward_bg']}; }}
255
+ .legend-dot.driver {{ border-color: #000; background: {COLORS['driver_bg']}; }}
256
+
257
+ #mynetwork {{ width: 100%; height: calc(100vh - 130px); background: #fff; }}
258
+
259
+ .tabs {{ position: absolute; bottom: 16px; left: 24px; z-index: 10; display: flex; gap: 4px; }}
260
+ .tab-btn {{ padding: 6px 14px; font-size: 12px; font-weight: 500; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; color: #555; transition: all 0.15s; }}
261
+ .tab-btn:hover {{ background: #f0f0f0; }}
262
+ .tab-btn.active {{ background: #333; color: #fff; border-color: #333; }}
263
+
264
+ .details-panel {{ position: absolute; bottom: 0; left: 0; right: 0; z-index: 20; background: #fff; border-top: 1px solid #e0e0e0; box-shadow: 0 -4px 20px rgba(0,0,0,0.08); transform: translateY(100%); transition: transform 0.25s ease; max-height: 45vh; overflow-y: auto; }}
265
+ .details-panel.open {{ transform: translateY(0); }}
266
+ .details-header {{ display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; border-bottom: 1px solid #eee; position: sticky; top: 0; background: #fff; }}
267
+ .details-header h3 {{ font-size: 14px; font-weight: 600; }}
268
+ .details-close {{ background: none; border: none; font-size: 18px; cursor: pointer; color: #888; padding: 4px 8px; border-radius: 4px; }}
269
+ .details-close:hover {{ background: #f0f0f0; }}
270
+ .details-body {{ padding: 16px 24px; }}
271
+ .details-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }}
272
+ .detail-card {{ padding: 12px; border: 1px solid #eee; border-radius: 8px; background: #fafafa; }}
273
+ .detail-card h4 {{ font-size: 12px; font-weight: 600; color: #888; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }}
274
+ .detail-card p {{ font-size: 13px; line-height: 1.5; color: #444; }}
275
+ .detail-card .val {{ font-size: 20px; font-weight: 600; color: #1a1a1a; }}
276
+
277
+ .canvas-wrap {{ position: relative; flex: 1; }}
278
+ </style>
279
+ <script>
280
+ var nodes = {json.dumps(all_nodes)};
281
+ var edges = {json.dumps(all_edges)};
282
+ var network = null;
283
+
284
+ function destroy() {{ if (network !== null) {{ network.destroy(); network = null; }} }}
285
+
286
+ function draw(id) {{
287
+ destroy();
288
+ var data = {{ nodes: nodes[id], edges: edges[id] }};
289
+ var options = {{
290
+ nodes: {{
291
+ shape: 'box',
292
+ scaling: {{ min: 20, max: 80, label: {{ enabled: true, min: 11, max: 20 }} }},
293
+ font: {{ size: 14, face: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif', multi: 'md' }},
294
+ margin: {{ top: 8, bottom: 8, left: 12, right: 12 }},
295
+ shadow: {{ enabled: true, color: 'rgba(0,0,0,0.08)', size: 6, x: 0, y: 2 }},
296
+ shapeProperties: {{ borderRadius: 6 }}
297
+ }},
298
+ edges: {{
299
+ smooth: {{ type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 }},
300
+ shadow: false,
301
+ hoverWidth: 1.5
302
+ }},
303
+ physics: {{
304
+ enabled: true,
305
+ solver: 'hierarchicalRepulsion',
306
+ hierarchicalRepulsion: {{ nodeDistance: 280, centralGravity: 0.0, springLength: 280, springConstant: 0.01, damping: 0.09, avoidOverlap: 1 }},
307
+ stabilization: {{ enabled: true, iterations: 1000 }}
308
+ }},
309
+ interaction: {{ zoomView: true, dragView: true, hover: true, tooltipDelay: 200 }},
310
+ layout: {{ hierarchical: false }}
311
+ }};
312
+ network = new vis.Network(document.getElementById('mynetwork'), data, options);
313
+ document.getElementById('nodeCount').textContent = data.nodes.length;
314
+ document.getElementById('edgeCount').textContent = data.edges.length;
315
+ }}
316
+
317
+ function toggleDetails() {{
318
+ var panel = document.getElementById('detailsPanel');
319
+ var btn = document.getElementById('detailsBtn');
320
+ panel.classList.toggle('open');
321
+ btn.classList.toggle('active');
322
+ }}
323
+
324
+ $(document).ready(function() {{
325
+ $('#driver_select').select2({{ placeholder: 'Search for an attribute...', allowClear: false }});
326
+ $('#driver_select').on('change', function() {{ draw($(this).val()); }});
327
+ draw(0);
328
+ }});
329
+ </script>
330
+ </head>
331
+ <body style="display:flex; flex-direction:column; height:100vh; overflow:hidden;">
332
+
333
+ <div class="header">
334
+ <div class="header-left">
335
+ <h1>{chart_title}</h1>
336
+ <div class="subtitle">Association Network</div>
337
+ </div>
338
+ <div class="header-right">
339
+ <div class="legend-bar">
340
+ <div class="legend-item"><div class="legend-dot reward"></div> Emotional</div>
341
+ <div class="legend-item"><div class="legend-dot nonreward"></div> Functional</div>
342
+ <div class="legend-item"><div class="legend-dot driver"></div> Selected</div>
343
+ </div>
344
+ </div>
345
+ </div>
346
+
347
+ <div class="toolbar">
348
+ <label>Attribute:</label>
349
+ <select id="driver_select">
350
+ {driver_options}
351
+ </select>
352
+ <span class="stat">Attributes: <strong id="nodeCount">0</strong></span>
353
+ <span class="stat">Connections: <strong id="edgeCount">0</strong></span>
354
+ </div>
355
+
356
+ <div class="canvas-wrap">
357
+ <div id="mynetwork"></div>
358
+ <div class="tabs">
359
+ <button class="tab-btn" id="detailsBtn" onclick="toggleDetails()">Details</button>
360
+ </div>
361
+ <div class="details-panel" id="detailsPanel">
362
+ <div class="details-header">
363
+ <h3>Technical Details</h3>
364
+ <button class="details-close" onclick="toggleDetails()">&times;</button>
365
+ </div>
366
+ <div class="details-body">
367
+ <div class="details-grid">
368
+ <div class="detail-card">
369
+ <h4>Threshold</h4>
370
+ <div class="val">{threshold}</div>
371
+ <p>Only associations above this deviation value are shown as connections.</p>
372
+ </div>
373
+ <div class="detail-card">
374
+ <h4>Attributes</h4>
375
+ <div class="val">{attribute_count}</div>
376
+ <p>{reward_drivers} emotional (rewards) and {nonreward_drivers} functional (nonrewards) attributes.</p>
377
+ </div>
378
+ <div class="detail-card">
379
+ <h4>Connections</h4>
380
+ <div class="val">{corr_count}</div>
381
+ <p>Total attribute pairs above threshold. Avg: {avg_corr:.1f}, Max: {max_corr:.1f}</p>
382
+ </div>
383
+ <div class="detail-card">
384
+ <h4>How to Read</h4>
385
+ <p>Each node is a brand association. Lines connect associations that co-occur above average.
386
+ Thicker lines = stronger co-occurrence. Node size reflects Category Index (importance).
387
+ Hover over nodes and lines for details.</p>
388
+ </div>
389
+ </div>
390
+ </div>
391
+ </div>
392
+ </div>
393
+
394
+ </body>
395
+ </html>"""
config.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constants for the correlation network generator."""
2
+
3
+ # Territory names used to classify attributes as Rewards vs Nonrewards.
4
+ # If the territory part of a variable code is NOT in this list → Nonreward.
5
+ REWARDS_FACTORS = [
6
+ # Core 6 (German)
7
+ 'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung',
8
+ # Core 6 (English)
9
+ 'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement',
10
+ # Compound versions (English)
11
+ 'Adventure & Thrill', 'Autonomy & Dominance', 'Balance & Security',
12
+ 'Discipline & Control', 'Enjoyment & Sensuality', 'Excitement & Playfulness',
13
+ # Extended (MX/other)
14
+ 'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom',
15
+ ]
16
+
17
+ # Node color palette — outline-based styling
18
+ COLORS = {
19
+ 'reward_color': '#E03E3E', # warm red (edges)
20
+ 'reward_border': '#C02020', # darker red (node border)
21
+ 'reward_bg': '#FDEAEA', # very light red (node fill)
22
+ 'nonreward_color': '#2B7AB2', # steel blue (edges)
23
+ 'nonreward_border': '#1A5C8A', # darker blue (node border)
24
+ 'nonreward_bg': '#E8F1F8', # very light blue (node fill)
25
+ 'driver_bg': '#2B2B2B', # dark (selected driver fill)
26
+ 'driver_border': '#000000',
27
+ 'driver_font': '#FFFFFF',
28
+ }
parse_excel.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Excel correlation file parsing and auto-detection."""
2
+
3
+ import pandas as pd
4
+ from config import REWARDS_FACTORS
5
+
6
+
7
+ def detect_data_start_row(df):
8
+ """Find DATA_START_ROW by detecting the 2nd text block in column B.
9
+
10
+ The Excel files have two data blocks: means (block 1) and deviations (block 2).
11
+ We want block 2 (deviations) since those show what's distinctive.
12
+
13
+ Returns:
14
+ (row_number, blocks) where row_number is 1-based and blocks is a list
15
+ of (start, end) tuples for each text block found.
16
+ """
17
+ in_block = False
18
+ block_start = None
19
+ blocks = []
20
+
21
+ for row_idx in range(df.shape[0]):
22
+ val = df.iloc[row_idx, 1]
23
+ has_text = pd.notna(val) and isinstance(val, str) and len(str(val).strip()) > 0
24
+
25
+ if has_text and not in_block:
26
+ in_block = True
27
+ block_start = row_idx + 1
28
+ elif not has_text and in_block:
29
+ in_block = False
30
+ blocks.append((block_start, row_idx))
31
+ block_start = None
32
+
33
+ if in_block:
34
+ blocks.append((block_start, df.shape[0]))
35
+
36
+ if len(blocks) >= 2:
37
+ return blocks[1][0], blocks
38
+ elif blocks:
39
+ return blocks[0][0], blocks
40
+ return None, []
41
+
42
+
43
+ def detect_cutoff_value(df):
44
+ """Find CORR_THRESHOLD by searching for 'Cut-off used in columns' in column B.
45
+
46
+ Note: This detection fails on all known real files — they don't contain this text.
47
+ Falls back to the default (6.0) in the UI.
48
+ """
49
+ for row_idx in range(df.shape[0]):
50
+ val = df.iloc[row_idx, 1]
51
+ if pd.notna(val) and isinstance(val, str) and 'cut-off used in columns' in val.lower():
52
+ for col_idx in range(df.shape[1]):
53
+ cell_val = df.iloc[row_idx, col_idx]
54
+ if pd.notna(cell_val) and isinstance(cell_val, (int, float)):
55
+ return round(float(cell_val), 2)
56
+ return None
57
+
58
+
59
+ def detect_correlation_column_start(df):
60
+ """Find CORR_COL_START by detecting first large column block (>50 cols) in row 5.
61
+
62
+ Row 5 (0-indexed row 4) contains the column headers for the correlation matrix.
63
+ The first block of >50 consecutive non-empty cells is the "mean across all brands"
64
+ correlation matrix.
65
+ """
66
+ in_block = False
67
+ block_start = None
68
+ col_blocks = []
69
+
70
+ for col_idx in range(df.shape[1]):
71
+ val = df.iloc[4, col_idx]
72
+ has_data = pd.notna(val) and str(val).strip()
73
+ if has_data and not in_block:
74
+ in_block = True
75
+ block_start = col_idx
76
+ elif not has_data and in_block:
77
+ in_block = False
78
+ col_blocks.append((block_start, col_idx - 1))
79
+ block_start = None
80
+ if in_block:
81
+ col_blocks.append((block_start, df.shape[1] - 1))
82
+
83
+ for start, end in col_blocks:
84
+ if end - start + 1 > 50:
85
+ return start
86
+ return None
87
+
88
+
89
+ def detect_nonrewards_patterns(df, data_start_idx):
90
+ """Count Rewards vs Nonrewards attributes starting from data_start_idx.
91
+
92
+ Classification is based on whether the territory part of the variable code
93
+ (3rd segment of PREFIX_PA_Territory_Attribute) appears in REWARDS_FACTORS.
94
+ """
95
+ rewards_count = 0
96
+ nonrewards_count = 0
97
+
98
+ for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
99
+ code = df.iloc[row_idx, 1]
100
+ if pd.notna(code) and isinstance(code, str):
101
+ if '_PA_' in code:
102
+ parts = code.split('_')
103
+ if len(parts) >= 3:
104
+ factor = parts[2]
105
+ if factor in REWARDS_FACTORS:
106
+ rewards_count += 1
107
+ else:
108
+ nonrewards_count += 1
109
+
110
+ return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count}
111
+
112
+
113
+ def extract_network_data(df, data_start_row, corr_col_start):
114
+ """Extract attributes, codes, category indices, and correlation matrix from the Excel data.
115
+
116
+ Args:
117
+ df: Raw DataFrame (no header, 0-indexed)
118
+ data_start_row: 1-based row number where deviation data starts
119
+ corr_col_start: 0-based column index where correlation matrix starts
120
+
121
+ Returns:
122
+ dict with keys: attribute_names, attribute_codes, category_indices,
123
+ nonrewards_attrs, driver_names, corr_df
124
+ """
125
+ data_start_idx = data_start_row - 1
126
+
127
+ # Get driver codes from row 5 (0-indexed row 4)
128
+ driver_codes = []
129
+ for col_idx in range(corr_col_start, df.shape[1]):
130
+ driver_code = df.iloc[4, col_idx]
131
+ if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip():
132
+ driver_codes.append(str(driver_code))
133
+ elif pd.isna(driver_code) or driver_code == '':
134
+ break
135
+
136
+ # Get attributes from rows
137
+ attribute_names = []
138
+ attribute_codes = []
139
+ category_indices = []
140
+ nonrewards_attrs = set()
141
+
142
+ for row_idx in range(data_start_idx, df.shape[0]):
143
+ attr_code = df.iloc[row_idx, 1]
144
+ attr_name = df.iloc[row_idx, 2]
145
+ cat_idx = df.iloc[row_idx, 3]
146
+
147
+ if pd.notna(attr_name) and attr_name != '':
148
+ code_str = str(attr_code) if pd.notna(attr_code) else ''
149
+ attribute_codes.append(code_str)
150
+ attribute_names.append(str(attr_name))
151
+
152
+ try:
153
+ cat_val = float(cat_idx) if pd.notna(cat_idx) else 0
154
+ except (ValueError, TypeError):
155
+ cat_val = 0
156
+ category_indices.append(cat_val)
157
+
158
+ # Classify: if territory NOT in REWARDS_FACTORS → Nonreward
159
+ if '_PA_' in code_str:
160
+ parts = code_str.split('_')
161
+ if len(parts) >= 3:
162
+ factor = parts[2]
163
+ if factor not in REWARDS_FACTORS:
164
+ nonrewards_attrs.add(str(attr_name))
165
+ else:
166
+ break
167
+
168
+ # Map codes to display names
169
+ code_to_name = dict(zip(attribute_codes, attribute_names))
170
+ driver_names = [code_to_name.get(code, code) for code in driver_codes]
171
+
172
+ # Build correlation matrix
173
+ import numpy as np
174
+ corr_data = []
175
+ for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)):
176
+ row_data = []
177
+ for col_idx in range(corr_col_start, corr_col_start + len(driver_codes)):
178
+ val = df.iloc[row_idx, col_idx]
179
+ try:
180
+ row_data.append(float(val) if pd.notna(val) else 0)
181
+ except (ValueError, TypeError):
182
+ row_data.append(0)
183
+ corr_data.append(row_data)
184
+
185
+ corr_df = pd.DataFrame(corr_data, index=attribute_names, columns=driver_names)
186
+
187
+ return {
188
+ 'attribute_names': attribute_names,
189
+ 'attribute_codes': attribute_codes,
190
+ 'category_indices': category_indices,
191
+ 'nonrewards_attrs': nonrewards_attrs,
192
+ 'driver_names': driver_names,
193
+ 'corr_df': corr_df,
194
+ 'attr_to_cat_idx': dict(zip(attribute_names, category_indices)),
195
+ }