Correlation-network / build_network.py
DecodeMarketing's picture
fix: pick the master file, keep names inside the area, Henkel terms (#8)
7fbdd56 unverified
Raw History Blame Contribute Delete
41.2 kB
"""Generate interactive HTML network visualization from parsed correlation data."""
import html
import json
from pathlib import Path
import numpy as np
from config import COLORS
def _export_js(name):
"""The PowerPoint export's code, inlined into the HTML (one file, no server)."""
js = (Path(__file__).parent / name).read_text(encoding='utf-8')
if '</script' in js.lower():
raise ValueError(f'{name} must not contain "</script"')
return js
def _safe_json(obj):
"""JSON-encode and escape </script> sequences for safe embedding in HTML."""
return json.dumps(obj).replace('</','<\\/')
def generate_network_html(network_data, threshold, max_l1_nodes,
client_name, country_name, brand_name, category_name,
show_category_index=True, fallback_name=''):
"""Build the complete HTML file with vis.js network visualization.
Args:
network_data: Dict from parse_excel.extract_network_data()
threshold: Minimum correlation value to show as a connection
max_l1_nodes: Max number of Level 1 connections per node (default for in-HTML dropdown)
client_name, country_name, brand_name, category_name: Project metadata (all optional)
fallback_name: Fallback name from uploaded filename (used when no project details entered)
Returns:
(html_string, stats_dict, filename)
"""
corr_df = network_data['corr_df']
attribute_names = network_data['attribute_names']
nonrewards_attrs = network_data['nonrewards_attrs']
driver_names = network_data['driver_names']
attr_to_cat_idx = network_data['attr_to_cat_idx']
# Calculate statistics
all_positive_corrs = []
for col in corr_df.columns:
for val in corr_df[col]:
if val >= threshold:
all_positive_corrs.append(val)
if all_positive_corrs:
avg_corr = float(np.mean(all_positive_corrs))
max_corr = float(np.max(all_positive_corrs))
min_corr = float(threshold)
else:
avg_corr = max_corr = min_corr = float(threshold)
# --- Build sparse deviation matrix (only above-threshold pairs) ---
# Directed: the key is "source,target". The source attribute supplies the COLUMN
# and the target supplies the ROW, because the deviation matrix is asymmetric —
# an attribute's associations are read down its own column. Storing only one
# triangle would let the alphabetical sort above decide which of the two values
# is used. See docs/deviation-direction.md.
attr_list = sorted(driver_names, key=lambda x: x.lower())
sparse_corr = {}
for i, source in enumerate(attr_list):
if source not in corr_df.columns:
continue
for j, target in enumerate(attr_list):
if i == j or target not in corr_df.index:
continue
val = float(corr_df.loc[target, source])
if val >= threshold:
sparse_corr[f"{i},{j}"] = round(val, 1)
# Build attribute metadata array (parallel to attr_list)
attr_meta = []
for name in attr_list:
cat_idx = int(attr_to_cat_idx.get(name, 100))
is_reward = name not in nonrewards_attrs
attr_meta.append({
'name': name,
'catIdx': cat_idx,
'isReward': is_reward,
})
# Build driver list with index references for sidebar
driver_list = []
for i, meta in enumerate(attr_meta):
driver_list.append({
'name': meta['name'],
'catIdx': meta['catIdx'],
'isReward': meta['isReward'],
'index': i,
})
# Count rewards vs nonrewards
reward_drivers = sum(1 for m in attr_meta if m['isReward'])
nonreward_drivers = len(attr_meta) - reward_drivers
# Build title from filled-in fields only
detail_parts = [p for p in [client_name, brand_name, country_name, category_name] if p]
if detail_parts:
chart_title = 'DECODE_' + '_'.join(detail_parts)
header_title = ' \u00b7 '.join(detail_parts) # · separator
elif fallback_name:
chart_title = fallback_name
header_title = fallback_name.replace('_', ' ')
else:
chart_title = 'Association_Network'
header_title = ''
# Clamp default max_l1 to dropdown range (2-6)
default_max_l1 = max(2, min(6, max_l1_nodes))
# --- HTML template ---
html_out = _build_html_template(
chart_title=chart_title,
header_title=header_title,
sparse_corr=sparse_corr,
attr_meta=attr_meta,
driver_list=driver_list,
nonrewards_list=sorted(nonrewards_attrs),
threshold=threshold,
min_corr=min_corr,
max_corr=max_corr,
attribute_count=len(attribute_names),
reward_drivers=reward_drivers,
nonreward_drivers=nonreward_drivers,
corr_count=len(all_positive_corrs),
avg_corr=avg_corr,
default_max_l1=default_max_l1,
show_category_index=show_category_index,
project={'client': client_name or '', 'country': country_name or '',
'brand': brand_name or '', 'category': category_name or ''},
)
stats = {
'drivers': len(attr_list),
'attributes': len(attribute_names),
'rewards': len(attribute_names) - len(nonrewards_attrs),
'nonrewards': len(nonrewards_attrs),
'positive_correlations': len(all_positive_corrs),
}
if detail_parts or fallback_name:
filename = f"{chart_title}_Correlation_Network.html"
else:
filename = "Correlation_Network.html"
return html_out, stats, filename
def _build_html_template(*, chart_title, header_title, sparse_corr, attr_meta,
driver_list, nonrewards_list, threshold, min_corr,
max_corr, attribute_count, reward_drivers,
nonreward_drivers, corr_count, avg_corr,
default_max_l1, show_category_index, project=None):
"""Build the standalone HTML string. Separated for readability."""
# Escape all user-supplied strings for safe HTML embedding
h = html.escape
safe_title = h(chart_title)
safe_header = h(header_title)
# JSON data for script block (escape </script> sequences)
corr_json = _safe_json(sparse_corr)
meta_json = _safe_json(attr_meta)
drivers_json = _safe_json(driver_list)
nonrewards_json = _safe_json(nonrewards_list)
project_json = _safe_json(project or {})
title_json = _safe_json(chart_title)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{safe_title} — Association Network</title>
<link type="text/css" href="https://unpkg.com/vis-network@9.1.9/dist/dist/vis-network.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<style>
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; }}
.header {{ background: #fff; border-bottom: 1px solid #e0e0e0; padding: 12px 24px; display: flex; align-items: center; gap: 12px; }}
.header-left {{ flex-shrink: 0; }}
.decode-logo {{ height: 22px; width: auto; }}
.header-center {{ flex: 1; text-align: center; }}
.header-center h1 {{ font-size: 17px; font-weight: 600; color: #1a1a1a; }}
.header-center .subtitle {{ font-size: 12px; color: #888; margin-top: 1px; }}
.legend-bar {{ display: flex; align-items: center; gap: 16px; }}
.legend-item {{ display: flex; align-items: center; gap: 5px; font-size: 12px; color: #666; }}
.legend-dot {{ width: 12px; height: 12px; border-radius: 3px; border: 2px solid; }}
.legend-dot.reward {{ border-color: {COLORS['reward_border']}; background: {COLORS['reward_bg']}; }}
.legend-dot.nonreward {{ border-color: {COLORS['nonreward_border']}; background: {COLORS['nonreward_bg']}; }}
.legend-dot.driver {{ border-color: #000; background: {COLORS['driver_bg']}; }}
.main {{ display: flex; flex: 1; overflow: hidden; }}
/* --- Sidebar --- */
.sidebar {{ width: 280px; min-width: 280px; background: #fff; border-right: 1px solid #e0e0e0; display: flex; flex-direction: column; transition: width 0.2s ease, min-width 0.2s ease; overflow: hidden; }}
.sidebar.collapsed {{ width: 0; min-width: 0; border-right: none; }}
.sidebar-header {{ padding: 12px 14px 8px; border-bottom: 1px solid #eee; flex-shrink: 0; }}
.sidebar-header h2 {{ font-size: 13px; font-weight: 600; color: #555; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }}
.sidebar-search {{ width: 100%; padding: 7px 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 13px; outline: none; }}
.sidebar-search:focus {{ border-color: #999; }}
.control-bar {{ display: flex; gap: 2px; margin-top: 8px; }}
.control-btn {{ flex: 1; padding: 4px 0; font-size: 11px; font-weight: 500; border: 1px solid #ddd; background: #f8f8f8; cursor: pointer; color: #777; transition: all 0.12s; }}
.control-btn:first-child {{ border-radius: 4px 0 0 4px; }}
.control-btn:last-child {{ border-radius: 0 4px 4px 0; }}
.control-btn.active {{ background: #283273; color: #fff; border-color: #283273; }}
.connections-row {{ display: flex; align-items: center; gap: 8px; margin-top: 8px; }}
.connections-label {{ font-size: 11px; font-weight: 500; color: #777; white-space: nowrap; }}
.connections-select {{ flex: 1; padding: 4px 6px; font-size: 11px; border: 1px solid #ddd; border-radius: 4px; background: #f8f8f8; color: #555; cursor: pointer; outline: none; }}
.connections-select:focus {{ border-color: #999; }}
.sidebar-list {{ flex: 1; overflow-y: auto; }}
.attr-row {{ display: flex; align-items: center; padding: 8px 14px; cursor: pointer; border-bottom: 1px solid #f0f0f0; transition: background 0.1s; gap: 8px; }}
.attr-row:hover {{ background: #f5f7fa; }}
.attr-row.selected {{ background: #eef2f7; }}
.attr-dot {{ width: 8px; height: 8px; border-radius: 2px; border: 2px solid; flex-shrink: 0; }}
.attr-dot.reward {{ border-color: {COLORS['reward_border']}; background: {COLORS['reward_bg']}; }}
.attr-dot.nonreward {{ border-color: {COLORS['nonreward_border']}; background: {COLORS['nonreward_bg']}; }}
.attr-name {{ flex: 1; font-size: 13px; font-weight: 600; color: #333; line-height: 1.3; }}
.attr-idx {{ font-size: 12px; font-weight: 700; color: #888; min-width: 28px; text-align: right; flex-shrink: 0; }}
.sidebar-stats {{ padding: 10px 14px; border-top: 1px solid #eee; font-size: 12px; color: #999; flex-shrink: 0; }}
/* --- Collapse toggle --- */
.collapse-btn {{ position: absolute; top: 50%; left: 0; transform: translateY(-50%); z-index: 15; width: 20px; height: 48px; background: #fff; border: 1px solid #ddd; border-left: none; border-radius: 0 6px 6px 0; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #888; transition: all 0.15s; }}
.collapse-btn:hover {{ background: #f0f0f0; color: #333; }}
/* --- Canvas --- */
.canvas-wrap {{ position: relative; flex: 1; }}
#mynetwork {{ width: 100%; height: 100%; background: #fff; }}
.status-bar {{ position: absolute; top: 12px; right: 16px; z-index: 10; display: flex; gap: 8px; align-items: center; }}
.stat {{ font-size: 12px; color: #aaa; background: rgba(255,255,255,0.9); padding: 4px 10px; border-radius: 4px; border: 1px solid #eee; }}
.stat strong {{ color: #555; }}
.tabs {{ position: absolute; bottom: 16px; left: 24px; z-index: 10; display: flex; gap: 4px; }}
.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; }}
.tab-btn:hover {{ background: #f0f0f0; }}
.tab-btn.active {{ background: #283273; color: #fff; border-color: #283273; }}
#pptxDialog {{ position: fixed; inset: 0; background: rgba(20,24,40,.35); display: none; align-items: center; justify-content: center; z-index: 900; }}
#pptxDialog .xp {{ background: #fff; width: 520px; max-width: calc(100vw - 32px); max-height: calc(100vh - 64px); overflow: auto; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,.25); padding: 20px 22px; font-size: 13px; line-height: 1.5; color: #222; }}
#pptxDialog h2 {{ font-size: 15px; margin: 0 0 2px; }}
#pptxDialog .sub {{ color: #666; margin: 0 0 14px; }}
#pptxDialog .row {{ margin: 0 0 12px; }}
#pptxDialog label {{ display: block; font-weight: 600; margin: 10px 0 4px; }}
#pptxDialog input, #pptxDialog select {{ width: 100%; padding: 5px 7px; font: inherit; border: 1px solid #ccc; border-radius: 4px; }}
#pptxDialog .warn {{ color: #8a5a00; background: #fff6e0; padding: 6px 8px; border-radius: 4px; margin-top: 12px; }}
#pptxDialog .status {{ color: #555; margin-top: 12px; min-height: 1.5em; }}
#pptxDialog .btns {{ display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }}
#pptxDialog button {{ padding: 6px 14px; font: inherit; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }}
#pptxDialog button.primary {{ background: #283273; color: #fff; border-color: #283273; }}
#pptxDialog button:disabled {{ opacity: .5; cursor: default; }}
.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; }}
.details-panel.open {{ transform: translateY(0); }}
.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; }}
.details-header h3 {{ font-size: 14px; font-weight: 600; }}
.details-close {{ background: none; border: none; font-size: 18px; cursor: pointer; color: #888; padding: 4px 8px; border-radius: 4px; }}
.details-close:hover {{ background: #f0f0f0; }}
.details-body {{ padding: 16px 24px; }}
.details-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }}
.detail-card {{ padding: 12px; border: 1px solid #eee; border-radius: 8px; background: #fafafa; }}
.detail-card h4 {{ font-size: 12px; font-weight: 600; color: #888; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }}
.detail-card p {{ font-size: 13px; line-height: 1.5; color: #444; }}
.detail-card .val {{ font-size: 20px; font-weight: 600; color: #1a1a1a; }}
/* --- Profile panel (right) --- */
.profile-panel {{ position: absolute; top: 0; right: 0; bottom: 0; width: 320px; background: #fff; border-left: 1px solid #e0e0e0; box-shadow: -4px 0 20px rgba(0,0,0,0.06); transform: translateX(100%); transition: transform 0.25s ease; z-index: 20; display: flex; flex-direction: column; }}
.profile-panel.open {{ transform: translateX(0); }}
.profile-header {{ display: flex; align-items: flex-start; justify-content: space-between; padding: 14px 16px 10px; border-bottom: 1px solid #eee; flex-shrink: 0; }}
.profile-header-info h3 {{ font-size: 15px; font-weight: 600; color: #1a1a1a; line-height: 1.3; }}
.profile-meta {{ display: flex; gap: 8px; margin-top: 4px; align-items: center; }}
.profile-badge {{ font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 3px; }}
.profile-badge.reward {{ background: {COLORS['reward_bg']}; color: {COLORS['reward_border']}; border: 1px solid {COLORS['reward_border']}; }}
.profile-badge.nonreward {{ background: {COLORS['nonreward_bg']}; color: {COLORS['nonreward_border']}; border: 1px solid {COLORS['nonreward_border']}; }}
.profile-cat-idx {{ font-size: 11px; color: #888; }}
.profile-close {{ background: none; border: none; font-size: 18px; cursor: pointer; color: #888; padding: 0 4px; border-radius: 4px; flex-shrink: 0; }}
.profile-close:hover {{ background: #f0f0f0; }}
.profile-subtitle {{ padding: 8px 16px 4px; font-size: 11px; font-weight: 600; color: #999; text-transform: uppercase; letter-spacing: 0.5px; flex-shrink: 0; }}
.profile-bars {{ flex: 1; overflow-y: auto; padding: 4px 16px 16px; }}
.bar-row {{ display: flex; align-items: center; gap: 8px; padding: 5px 0; border-bottom: 1px solid #f5f5f5; }}
.bar-label {{ width: 110px; font-size: 12px; font-weight: 500; color: #444; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
.bar-track {{ flex: 1; height: 16px; background: #f5f5f5; border-radius: 3px; position: relative; overflow: hidden; }}
.bar-fill {{ height: 100%; border-radius: 3px; transition: width 0.3s ease; }}
.bar-fill.reward {{ background: {COLORS['reward_color']}; opacity: 0.7; }}
.bar-fill.nonreward {{ background: {COLORS['nonreward_color']}; opacity: 0.7; }}
.bar-val {{ font-size: 11px; font-weight: 600; color: #888; min-width: 30px; text-align: right; flex-shrink: 0; }}
</style>
<script>
// --- Embedded data ---
var corrMatrix = {corr_json};
var attrMeta = {meta_json};
var driverList = {drivers_json};
var nonrewardsSet = new Set({nonrewards_json});
var THRESHOLD = {threshold};
var MIN_CORR = {min_corr};
var MAX_CORR = {max_corr};
var SHOW_CAT_IDX = {'true' if show_category_index else 'false'};
var PROJECT = {project_json};
var CHART_TITLE = {title_json};
var COLORS = {{
reward_color: '{COLORS["reward_color"]}',
reward_border: '{COLORS["reward_border"]}',
reward_bg: '{COLORS["reward_bg"]}',
nonreward_color: '{COLORS["nonreward_color"]}',
nonreward_border: '{COLORS["nonreward_border"]}',
nonreward_bg: '{COLORS["nonreward_bg"]}',
driver_bg: '{COLORS["driver_bg"]}',
driver_font: '{COLORS["driver_font"]}'
}};
var network = null;
var nodesDS = null;
var edgesDS = null;
var currentSort = 'index';
var currentFilter = 'all';
var selectedIdx = 0;
var origNodes = {{}};
var clickedNode = null;
var FADED = {{
color: {{ background: '#f5f5f5', border: '#e0e0e0',
highlight: {{ background: '#f5f5f5', border: '#e0e0e0' }},
hover: {{ background: '#f5f5f5', border: '#e0e0e0' }} }},
font: {{ color: '#ccc' }},
borderWidth: 1
}};
function esc(s) {{ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }}
// --- Deviation lookup. Directed: i is the source (column), j the target (row). ---
function getCorr(i, j) {{
if (i === j) return 0;
return corrMatrix[i + ',' + j] || 0;
}}
// --- Styling helpers (ported from Python) ---
function wrapLabel(text) {{
var words = text.split(/\\s+/);
if (words.length <= 2) return text;
var lines = [], line = '';
for (var w = 0; w < words.length; w++) {{
if (line.length + words[w].length + 1 > 15 && line.length > 0) {{
lines.push(line);
line = words[w];
}} else {{
line = line ? line + ' ' + words[w] : words[w];
}}
}}
if (line) lines.push(line);
return lines.join('\\n');
}}
function makeLabel(name, catIdx) {{
var label = wrapLabel(name);
if (SHOW_CAT_IDX) label += '\\n(' + catIdx + ')';
return label;
}}
function isReward(name) {{ return !nonrewardsSet.has(name); }}
function getNodeColors(name, isDriver) {{
if (isDriver) {{
var border = isReward(name) ? COLORS.reward_border : COLORS.nonreward_border;
return {{
background: COLORS.driver_bg, border: border,
highlight: {{ background: '#444444', border: border }},
hover: {{ background: '#444444', border: border }}
}};
}}
if (!isReward(name)) {{
return {{
background: COLORS.nonreward_bg, border: COLORS.nonreward_border,
highlight: {{ background: '#D0E4F0', border: COLORS.nonreward_border }},
hover: {{ background: '#D0E4F0', border: COLORS.nonreward_border }}
}};
}}
return {{
background: COLORS.reward_bg, border: COLORS.reward_border,
highlight: {{ background: '#F8D0D0', border: COLORS.reward_border }},
hover: {{ background: '#F8D0D0', border: COLORS.reward_border }}
}};
}}
function getEdgeColor(name) {{
return isReward(name) ? COLORS.reward_color : COLORS.nonreward_color;
}}
function scaleEdge(val) {{
if (MAX_CORR === MIN_CORR) return {{ width: 3.0, opacity: 0.7 }};
var norm = (val - MIN_CORR) / (MAX_CORR - MIN_CORR);
return {{ width: Math.round((1 + norm * 7) * 100) / 100, opacity: Math.round((0.3 + norm * 0.7) * 100) / 100 }};
}}
// --- Build network for a selected attribute ---
function buildNetwork(selectedIdx, maxL1) {{
var selected = attrMeta[selectedIdx].name;
var nodes = [], edges = [];
// Level 0: selected driver
var catIdx = attrMeta[selectedIdx].catIdx;
nodes.push({{
id: selected,
label: makeLabel(selected, catIdx),
level: 0, value: catIdx,
title: selected + ' \\u2014 Category Index: ' + catIdx,
color: getNodeColors(selected, true),
font: {{ color: COLORS.driver_font, size: 18, bold: true }},
shape: 'box', borderWidth: 3, borderWidthSelected: 4
}});
// Level 1: top correlated attributes
var corrs = [];
for (var j = 0; j < attrMeta.length; j++) {{
if (j === selectedIdx) continue;
var val = getCorr(selectedIdx, j);
if (val >= THRESHOLD) corrs.push({{ idx: j, val: val }});
}}
corrs.sort(function(a, b) {{ return b.val - a.val; }});
var l1Names = [];
var l1Set = new Set();
for (var k = 0; k < Math.min(corrs.length, maxL1); k++) {{
var c = corrs[k];
var m = attrMeta[c.idx];
l1Names.push(m.name);
l1Set.add(m.name);
nodes.push({{
id: m.name,
label: makeLabel(m.name, m.catIdx),
level: 1, value: m.catIdx,
title: m.name + ' \\u2014 Category Index: ' + m.catIdx + ', Correlation: ' + c.val.toFixed(1),
color: getNodeColors(m.name, false),
font: {{ color: '#333333', size: 16 }},
borderWidth: 2
}});
var ep = scaleEdge(c.val);
var ec = getEdgeColor(selected);
edges.push({{
from: selected, to: m.name, value: c.val,
width: ep.width,
color: {{ color: ec, opacity: ep.opacity, highlight: ec, hover: ec }},
title: selected + ' \\u2194 ' + m.name + ': ' + c.val.toFixed(1)
}});
}}
// Level 2: secondary correlations from L1 nodes
var l2Added = new Set();
for (var li = 0; li < l1Names.length; li++) {{
var l1Name = l1Names[li];
var l1Idx = null;
for (var q = 0; q < attrMeta.length; q++) {{
if (attrMeta[q].name === l1Name) {{ l1Idx = q; break; }}
}}
if (l1Idx === null) continue;
var l2Corrs = [];
for (var j2 = 0; j2 < attrMeta.length; j2++) {{
if (j2 === selectedIdx || l1Set.has(attrMeta[j2].name)) continue;
var v2 = getCorr(l1Idx, j2);
if (v2 >= THRESHOLD) l2Corrs.push({{ idx: j2, val: v2 }});
}}
l2Corrs.sort(function(a, b) {{ return b.val - a.val; }});
for (var k2 = 0; k2 < Math.min(l2Corrs.length, maxL1); k2++) {{
var c2 = l2Corrs[k2];
var m2 = attrMeta[c2.idx];
if (!l2Added.has(m2.name)) {{
nodes.push({{
id: m2.name,
label: makeLabel(m2.name, m2.catIdx),
level: 2, value: m2.catIdx,
title: m2.name + ' \\u2014 Category Index: ' + m2.catIdx + ', Correlation: ' + c2.val.toFixed(1),
color: getNodeColors(m2.name, false),
font: {{ color: '#333333', size: 15 }},
borderWidth: 2
}});
l2Added.add(m2.name);
}}
var ep2 = scaleEdge(c2.val);
var ec2 = getEdgeColor(l1Name);
edges.push({{
from: l1Name, to: m2.name, value: c2.val,
width: ep2.width,
color: {{ color: ec2, opacity: ep2.opacity, highlight: ec2, hover: ec2 }},
title: l1Name + ' \\u2194 ' + m2.name + ': ' + c2.val.toFixed(1)
}});
}}
}}
return {{ nodes: nodes, edges: edges }};
}}
function applyFocus(nodeId) {{
var connected = network.getConnectedNodes(nodeId);
var connEdges = network.getConnectedEdges(nodeId);
var nUp = [];
nodesDS.forEach(function(n) {{
if (n.id !== nodeId && connected.indexOf(n.id) === -1) {{
nUp.push({{ id: n.id, color: FADED.color, font: FADED.font, borderWidth: FADED.borderWidth }});
}}
}});
nodesDS.update(nUp);
var eUp = [];
edgesDS.forEach(function(e) {{
if (connEdges.indexOf(e.id) === -1) {{
eUp.push({{ id: e.id, hidden: true }});
}}
}});
edgesDS.update(eUp);
}}
function clearFocus() {{
var nUp = [];
nodesDS.forEach(function(n) {{
var o = origNodes[n.id];
if (o) nUp.push({{ id: n.id, color: o.color, font: o.font, borderWidth: o.borderWidth }});
}});
nodesDS.update(nUp);
var eUp = [];
edgesDS.forEach(function(e) {{
eUp.push({{ id: e.id, hidden: false }});
}});
edgesDS.update(eUp);
}}
function destroy() {{ if (network !== null) {{ network.destroy(); network = null; }} }}
function getMaxL1() {{
var sel = document.getElementById('maxL1Select');
return sel ? parseInt(sel.value, 10) : {default_max_l1};
}}
function draw(id) {{
destroy();
selectedIdx = id;
var maxL1 = getMaxL1();
var data = buildNetwork(id, maxL1);
var options = {{
nodes: {{
shape: 'box',
scaling: {{ min: 40, max: 90, label: {{ enabled: true, min: 15, max: 20 }} }},
font: {{ size: 14, face: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif', multi: 'md' }},
margin: {{ top: 8, bottom: 8, left: 12, right: 12 }},
shadow: {{ enabled: true, color: 'rgba(0,0,0,0.08)', size: 6, x: 0, y: 2 }},
shapeProperties: {{ borderRadius: 6 }}
}},
edges: {{
smooth: {{ type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 }},
shadow: false,
hoverWidth: 1.5
}},
physics: {{
enabled: true,
solver: 'hierarchicalRepulsion',
hierarchicalRepulsion: {{ nodeDistance: 280, centralGravity: 0.0, springLength: 280, springConstant: 0.01, damping: 0.09, avoidOverlap: 1 }},
stabilization: {{ enabled: true, iterations: 1000 }}
}},
interaction: {{ zoomView: true, dragView: true, hover: true, tooltipDelay: 200, selectConnectedEdges: true, hoverConnectedEdges: true, hideEdgesOnDrag: false }},
layout: {{ hierarchical: false }}
}};
nodesDS = new vis.DataSet(data.nodes);
edgesDS = new vis.DataSet(data.edges);
var netData = {{ nodes: nodesDS, edges: edgesDS }};
network = new vis.Network(document.getElementById('mynetwork'), netData, options);
document.getElementById('nodeCount').textContent = data.nodes.length;
document.getElementById('edgeCount').textContent = data.edges.length;
origNodes = {{}};
nodesDS.forEach(function(n) {{
origNodes[n.id] = {{ color: n.color, font: n.font, borderWidth: n.borderWidth }};
}});
clickedNode = null;
network.on('hoverNode', function(params) {{
if (clickedNode) return;
applyFocus(params.node);
}});
network.on('blurNode', function() {{
if (clickedNode) return;
clearFocus();
}});
network.on('click', function(params) {{
if (params.nodes.length > 0) {{
clickedNode = params.nodes[0];
clearFocus();
applyFocus(clickedNode);
showProfile(clickedNode);
}} else {{
clickedNode = null;
clearFocus();
closeProfile();
}}
}});
highlightSidebarRow(id);
closeProfile();
}}
function showProfile(nodeId) {{
var panel = document.getElementById('profilePanel');
var node = nodesDS.get(nodeId);
if (!node) return;
var connEdges = network.getConnectedEdges(nodeId);
var bars = [];
connEdges.forEach(function(eid) {{
var e = edgesDS.get(eid);
if (!e) return;
var other = e.from === nodeId ? e.to : e.from;
bars.push({{ name: other, value: e.value }});
}});
bars.sort(function(a, b) {{ return b.value - a.value; }});
var maxVal = bars.length > 0 ? bars[0].value : 1;
var isNR = nonrewardsSet.has(nodeId);
var catIdx = node.value || 0;
document.getElementById('profileName').textContent = nodeId;
var badge = document.getElementById('profileBadge');
badge.textContent = isNR ? 'Functional' : 'Emotional';
badge.className = 'profile-badge ' + (isNR ? 'nonreward' : 'reward');
document.getElementById('profileCatIdx').textContent = 'Category Index: ' + catIdx;
var html = '';
bars.forEach(function(b) {{
var pct = Math.round((b.value / maxVal) * 100);
var cls = nonrewardsSet.has(b.name) ? 'nonreward' : 'reward';
html += '<div class="bar-row">'
+ '<span class="bar-label" title="' + esc(b.name) + '">' + esc(b.name) + '</span>'
+ '<div class="bar-track"><div class="bar-fill ' + cls + '" style="width:' + pct + '%"></div></div>'
+ '<span class="bar-val">' + b.value.toFixed(1) + '</span>'
+ '</div>';
}});
document.getElementById('profileBars').innerHTML = html;
panel.classList.add('open');
}}
function closeProfile() {{
document.getElementById('profilePanel').classList.remove('open');
if (clickedNode) {{
clickedNode = null;
clearFocus();
}}
}}
function saveScreenshot() {{
var canvas = document.getElementById('mynetwork').getElementsByTagName('canvas')[0];
if (!canvas) return;
var link = document.createElement('a');
link.download = '{safe_title}_network.png';
link.href = canvas.toDataURL('image/png');
link.click();
}}
function highlightSidebarRow(id) {{
var rows = document.querySelectorAll('.attr-row');
rows.forEach(function(r) {{ r.classList.remove('selected'); }});
var active = document.querySelector('.attr-row[data-index="' + id + '"]');
if (active) {{
active.classList.add('selected');
active.scrollIntoView({{ block: 'nearest' }});
}}
}}
function renderSidebar() {{
var search = document.getElementById('sidebarSearch').value.toLowerCase();
var sorted = driverList.slice();
if (currentSort === 'index') {{
sorted.sort(function(a, b) {{ return b.catIdx - a.catIdx; }});
}} else {{
sorted.sort(function(a, b) {{ return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }});
}}
var html = '';
var visibleCount = 0;
sorted.forEach(function(d) {{
if (search && d.name.toLowerCase().indexOf(search) === -1) return;
if (currentFilter === 'emotional' && !d.isReward) return;
if (currentFilter === 'functional' && d.isReward) return;
visibleCount++;
var cls = d.isReward ? 'reward' : 'nonreward';
var sel = d.index === selectedIdx ? ' selected' : '';
html += '<div class="attr-row' + sel + '" data-index="' + d.index + '" onclick="draw(' + d.index + ')">'
+ '<div class="attr-dot ' + cls + '"></div>'
+ '<span class="attr-name">' + esc(d.name) + '</span>'
+ '<span class="attr-idx">' + d.catIdx + '</span>'
+ '</div>';
}});
document.getElementById('sidebarList').innerHTML = html;
document.getElementById('sidebarCount').textContent = visibleCount;
}}
function setSort(mode) {{
currentSort = mode;
document.querySelectorAll('[data-sort]').forEach(function(b) {{ b.classList.remove('active'); }});
document.querySelector('[data-sort="' + mode + '"]').classList.add('active');
renderSidebar();
}}
function setFilter(mode) {{
currentFilter = mode;
document.querySelectorAll('.filter-btn').forEach(function(b) {{ b.classList.remove('active'); }});
document.querySelector('.filter-btn[data-filter="' + mode + '"]').classList.add('active');
renderSidebar();
}}
function toggleSidebar() {{
var sb = document.getElementById('sidebar');
var btn = document.getElementById('collapseBtn');
sb.classList.toggle('collapsed');
btn.textContent = sb.classList.contains('collapsed') ? '\\u203A' : '\\u2039';
}}
function toggleDetails() {{
var panel = document.getElementById('detailsPanel');
var btn = document.getElementById('detailsBtn');
panel.classList.toggle('open');
btn.classList.toggle('active');
}}
function onMaxL1Change() {{
draw(selectedIdx);
}}
document.addEventListener('DOMContentLoaded', function() {{
renderSidebar();
var sorted = driverList.slice().sort(function(a, b) {{ return b.catIdx - a.catIdx; }});
if (sorted.length > 0) draw(sorted[0].index);
}});
</script>
</head>
<body style="display:flex; flex-direction:column; height:100vh; overflow:hidden;">
<div class="header">
<div class="header-left">
<svg class="decode-logo" viewBox="0 0 160 21" xmlns="http://www.w3.org/2000/svg"><path d="M0,0.69 L0,19.5 L10.2,19.5 C15.83,19.5 19.72,16.02 19.72,9.81 C19.72,2.8 14.52,0.69 10.2,0.69 L0,0.69 Z M3.78,4.47 L10.2,4.47 C13.14,4.47 15.94,5.59 15.94,10.02 C15.94,13.84 13.51,15.72 10.2,15.72 L3.78,15.72 L3.78,4.47 Z M28.69,0.69 L28.69,19.5 L45.82,19.5 L45.82,15.72 L32.46,15.72 L32.46,11.66 L41.98,11.66 L41.98,7.88 L32.46,7.88 L32.46,4.47 L45.39,4.47 L45.39,0.69 L28.69,0.69 Z M73.57,3.67 C71.57,2.25 68.92,0.11 64.05,0.11 C58.82,0.11 52.72,3.45 52.72,10.1 C52.72,16.63 57.95,20.08 64.27,20.08 C67.18,20.08 71.24,19.1 73.89,17.14 L72.19,13.65 C70.63,14.85 67.65,16.31 64.31,16.31 C58.9,16.31 56.5,13 56.5,10.21 C56.5,7.16 59.22,3.89 63.87,3.89 C67.54,3.89 70.12,5.96 71.35,6.97 L73.57,3.67 Z M92.96,20.08 C100.33,20.08 104.5,15.36 104.5,10.1 C104.5,4.79 100.4,0.11 92.96,0.11 C85.55,0.11 81.41,4.83 81.41,10.1 C81.41,15.36 85.59,20.08 92.96,20.08 Z M92.96,16.31 C88.27,16.31 85.19,13.36 85.19,10.1 C85.19,6.86 88.27,3.89 92.96,3.89 C97.64,3.89 100.73,6.83 100.73,10.1 C100.73,13.36 97.64,16.31 92.96,16.31 Z M113.94,0.69 L113.94,19.5 L124.15,19.5 C129.78,19.5 133.66,16.02 133.66,9.81 C133.66,2.8 128.47,0.69 124.15,0.69 L113.94,0.69 Z M117.72,4.47 L124.15,4.47 C127.09,4.47 129.88,5.59 129.88,10.02 C129.88,13.84 127.45,15.72 124.15,15.72 L117.72,15.72 L117.72,4.47 Z M142.63,0.69 L142.63,19.5 L159.77,19.5 L159.77,15.72 L146.41,15.72 L146.41,11.66 L155.93,11.66 L155.93,7.88 L146.41,7.88 L146.41,4.47 L159.33,4.47 L159.33,0.69 L142.63,0.69 Z" fill="#283273"/></svg>
</div>
<div class="header-center">
<h1>{'Association Network' if not safe_header else safe_header}</h1>
{'<div class="subtitle">Association Network</div>' if safe_header else ''}
</div>
<div class="legend-bar">
<div class="legend-item"><div class="legend-dot reward"></div> Emotional</div>
<div class="legend-item"><div class="legend-dot nonreward"></div> Functional</div>
<div class="legend-item"><div class="legend-dot driver"></div> Selected</div>
</div>
</div>
<div class="main">
<div class="sidebar" id="sidebar">
<div class="sidebar-header">
<h2>Attributes</h2>
<input type="text" class="sidebar-search" id="sidebarSearch" placeholder="Filter..." oninput="renderSidebar()">
<div class="control-bar">
<button class="control-btn active" data-sort="index" onclick="setSort('index')">Index</button>
<button class="control-btn" data-sort="name" onclick="setSort('name')">Name</button>
</div>
<div class="control-bar" style="margin-top:4px">
<button class="control-btn filter-btn active" data-filter="all" onclick="setFilter('all')">All</button>
<button class="control-btn filter-btn" data-filter="emotional" onclick="setFilter('emotional')">Emotional</button>
<button class="control-btn filter-btn" data-filter="functional" onclick="setFilter('functional')">Functional</button>
</div>
<div class="connections-row">
<span class="connections-label">Connections:</span>
<select class="connections-select" id="maxL1Select" onchange="onMaxL1Change()">
<option value="2"{" selected" if default_max_l1 == 2 else ""}>2</option>
<option value="3"{" selected" if default_max_l1 == 3 else ""}>3</option>
<option value="4"{" selected" if default_max_l1 == 4 else ""}>4</option>
<option value="5"{" selected" if default_max_l1 == 5 else ""}>5</option>
<option value="6"{" selected" if default_max_l1 == 6 else ""}>6</option>
</select>
</div>
</div>
<div class="sidebar-list" id="sidebarList"></div>
<div class="sidebar-stats"><span id="sidebarCount">{attribute_count}</span> attributes &middot; {reward_drivers} emotional &middot; {nonreward_drivers} functional</div>
</div>
<div class="canvas-wrap">
<button class="collapse-btn" id="collapseBtn" onclick="toggleSidebar()">&lsaquo;</button>
<div class="status-bar">
<span class="stat">Attributes: <strong id="nodeCount">0</strong></span>
<span class="stat">Connections: <strong id="edgeCount">0</strong></span>
</div>
<div id="mynetwork"></div>
<div class="profile-panel" id="profilePanel">
<div class="profile-header">
<div class="profile-header-info">
<h3 id="profileName"></h3>
<div class="profile-meta">
<span class="profile-badge" id="profileBadge"></span>
<span class="profile-cat-idx" id="profileCatIdx"></span>
</div>
</div>
<button class="profile-close" onclick="closeProfile()">&times;</button>
</div>
<div class="profile-subtitle">Connections in network</div>
<div class="profile-bars" id="profileBars"></div>
</div>
<div class="tabs">
<button class="tab-btn" onclick="saveScreenshot()" title="Save as PNG">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
Save PNG
</button>
<button class="tab-btn" onclick="startPptxExport()" title="One slide per listed attribute, on the DECODE, Henkel or REWE master">PowerPoint</button>
<button class="tab-btn" id="detailsBtn" onclick="toggleDetails()">Details</button>
</div>
<div class="details-panel" id="detailsPanel">
<div class="details-header">
<h3>Technical Details</h3>
<button class="details-close" onclick="toggleDetails()">&times;</button>
</div>
<div class="details-body">
<div class="details-grid">
<div class="detail-card">
<h4>Threshold</h4>
<div class="val">{threshold}</div>
<p>Only associations above this deviation value are shown as connections.</p>
</div>
<div class="detail-card">
<h4>Attributes</h4>
<div class="val">{attribute_count}</div>
<p>{reward_drivers} emotional (rewards) and {nonreward_drivers} functional (nonrewards) attributes.</p>
</div>
<div class="detail-card">
<h4>Connections</h4>
<div class="val">{corr_count}</div>
<p>Total attribute pairs above threshold. Avg: {avg_corr:.1f}, Max: {max_corr:.1f}</p>
</div>
<div class="detail-card">
<h4>How to Read</h4>
<p>Each node is a brand association. Lines connect associations that co-occur above average.
Thicker lines = stronger co-occurrence. Node size reflects Category Index (importance).
Hover over nodes and lines for details.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="file" id="pptxMasterPick" accept=".pptx" style="display:none">
<div id="pptxDialog"></div>
<script>
__PPTX_EXPORT_JS__
</script>
<script>
__PPTX_EXPORT_UI_JS__
</script>
</body>
</html>""".replace('__PPTX_EXPORT_JS__', _export_js('pptx_export.js')).replace('__PPTX_EXPORT_UI_JS__', _export_js('pptx_export_ui.js'))