File size: 6,211 Bytes
c3fc7dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""Read correlation data from Velocity's data_comparisons table.

Replaces parse_excel.py when data is available in Velocity.
Produces the same network_data dict that build_network.py expects.
"""

import pandas as pd

# Default connection params — override via env or function args
DEFAULT_HOST = "dev-aurora-cluster-backend.cluster-cluoomw6649g.eu-central-1.rds.amazonaws.com"
DEFAULT_DB = "decoderdb"
DEFAULT_USER = "readonly_user"
DEFAULT_PORT = 5432


def get_connection(host=None, db=None, user=None, password=None, port=None):
    """Create a psycopg2 connection to Velocity's decoderdb."""
    import psycopg2
    return psycopg2.connect(
        host=host or DEFAULT_HOST,
        dbname=db or DEFAULT_DB,
        user=user or DEFAULT_USER,
        password=password,
        port=port or DEFAULT_PORT,
        sslmode="require",
    )


def get_correlation_matrix(conn, study_id, module_id, group_id=None):
    """
    Read correlation matrix from data_comparisons.

    Args:
        conn: psycopg2 connection
        study_id: Velocity study_id (for finding Total group if group_id not given)
        module_id: Which module's correlations to read
        group_id: Specific group (default: Total group)

    Returns:
        network_data dict compatible with build_network.generate_network_html()
    """
    cur = conn.cursor()

    # Find Total group if not specified
    if group_id is None:
        cur.execute(
            "SELECT group_id FROM briefing_groups WHERE study_id = %s AND type = 'total'",
            (study_id,),
        )
        row = cur.fetchone()
        if not row:
            raise ValueError(f"No Total group found for study {study_id}")
        group_id = row[0]

    # Get correlations with item labels
    cur.execute("""
        SELECT a1.label AS attr1, a2.label AS attr2,
               dc.statistic_value::float AS r
        FROM data_comparisons dc
        JOIN _variable_assets va1 ON va1.variable_id = dc.variable_id_1 AND va1.asset_role = 'item'
        JOIN briefing_assets a1 ON a1.asset_id = va1.asset_id
        JOIN _variable_assets va2 ON va2.variable_id = dc.variable_id_2 AND va2.asset_role = 'item'
        JOIN briefing_assets a2 ON a2.asset_id = va2.asset_id
        WHERE dc.module_id = %s AND dc.group_id_1 = %s
        AND dc.statistic = 'correlation'
    """, (module_id, group_id))

    rows = cur.fetchall()
    if not rows:
        raise ValueError(f"No correlations found for module {module_id}, group {group_id}")

    # Build symmetric correlation matrix
    attrs = sorted(set(r[0] for r in rows) | set(r[1] for r in rows))
    attr_idx = {a: i for i, a in enumerate(attrs)}
    n = len(attrs)
    matrix = pd.DataFrame(0.0, index=attrs, columns=attrs)

    for attr1, attr2, r in rows:
        matrix.loc[attr1, attr2] = r
        matrix.loc[attr2, attr1] = r  # symmetric

    # Fill diagonal with 1.0
    for a in attrs:
        matrix.loc[a, a] = 1.0

    # Get territory classification from aggregations
    cur.execute("""
        SELECT DISTINCT a.label AS territory, ba.label AS item
        FROM briefing_aggregations a
        JOIN briefing_files f ON f.file_id = a.file_id
        JOIN _aggregation_assets aa ON aa.aggregation_id = a.aggregation_id
        JOIN briefing_assets ba ON ba.asset_id = aa.asset_id
        WHERE f.study_id = %s
        ORDER BY a.label, ba.label
    """, (study_id,))

    agg_rows = cur.fetchall()
    rewards_territories = {
        "Adventure", "Autonomy", "Discipline", "Security", "Enjoyment", "Excitement",
    }
    item_to_territory = {}
    for territory, item in agg_rows:
        if territory in rewards_territories:
            item_to_territory[item] = territory

    nonrewards_attrs = set()
    for a in attrs:
        if a not in item_to_territory:
            nonrewards_attrs.add(a)

    # Get category indices from data_summaries (Total group, mean statistic)
    # Category index = the attribute's mean PA across all brands
    cur.execute("""
        SELECT a_item.label AS attribute,
               AVG(ds.summary_value::float * 100) AS cat_index
        FROM data_summaries ds
        JOIN data_variables dv ON dv.variable_id = ds.variable_id
        JOIN briefing_groups g ON g.group_id = ds.group_id
        JOIN _variable_assets va_item ON va_item.variable_id = ds.variable_id AND va_item.asset_role = 'item'
        JOIN briefing_assets a_item ON a_item.asset_id = va_item.asset_id
        WHERE g.study_id = %s AND g.type = 'total'
        AND ds.statistic = 'mean' AND dv.type = 'PA'
        AND ds.module_id = %s
        GROUP BY a_item.label
    """, (study_id, module_id))

    cat_idx_rows = cur.fetchall()
    cat_idx_map = {r[0]: round(r[1], 1) for r in cat_idx_rows}

    category_indices = [cat_idx_map.get(a, 0) for a in attrs]

    cur.close()

    attr_to_cat_idx = dict(zip(attrs, category_indices))

    return {
        "attribute_names": attrs,
        "attribute_codes": attrs,  # same as names when reading from Velocity
        "category_indices": category_indices,
        "attr_to_cat_idx": attr_to_cat_idx,
        "nonrewards_attrs": nonrewards_attrs,
        "driver_names": attrs,
        "corr_df": matrix,
    }


if __name__ == "__main__":
    """Quick test: print correlation matrix stats for study 497."""
    import os
    password = os.environ.get("DB_PASSWORD")
    if not password:
        print("Set DB_PASSWORD environment variable")
        exit(1)

    conn = get_connection(password=password)
    data = get_correlation_matrix(conn, study_id=497, module_id=2641)
    conn.close()

    print(f"Attributes: {len(data['attribute_names'])}")
    print(f"Rewards: {len(data['attribute_names']) - len(data['nonrewards_attrs'])}")
    print(f"Nonrewards: {len(data['nonrewards_attrs'])}")
    print(f"Correlation matrix: {data['corr_df'].shape}")
    print(f"\nTop 5 correlations:")
    corr = data["corr_df"]
    # Get upper triangle pairs
    pairs = []
    for i in range(len(corr)):
        for j in range(i + 1, len(corr)):
            pairs.append((corr.index[i], corr.columns[j], corr.iloc[i, j]))
    pairs.sort(key=lambda x: abs(x[2]), reverse=True)
    for a1, a2, r in pairs[:5]:
        print(f"  {a1} × {a2}: r={r:.3f}")