feat: add Velocity data source for correlation networks
Browse filesvelocity_source.py reads correlation matrix directly from Velocity's
data_comparisons table, replacing the Excel upload path. Produces the
same network_data dict that build_network.py expects.
Tested with BGO Showcase (study 497, module 2641): 68 attributes,
36 rewards, 32 nonrewards, 68×68 correlation matrix, 1012 connections.
Territory classification and category indices also read from Velocity
(briefing_aggregations + data_summaries).
- velocity_source.py +172 -0
velocity_source.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read correlation data from Velocity's data_comparisons table.
|
| 2 |
+
|
| 3 |
+
Replaces parse_excel.py when data is available in Velocity.
|
| 4 |
+
Produces the same network_data dict that build_network.py expects.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
# Default connection params — override via env or function args
|
| 10 |
+
DEFAULT_HOST = "dev-aurora-cluster-backend.cluster-cluoomw6649g.eu-central-1.rds.amazonaws.com"
|
| 11 |
+
DEFAULT_DB = "decoderdb"
|
| 12 |
+
DEFAULT_USER = "readonly_user"
|
| 13 |
+
DEFAULT_PORT = 5432
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_connection(host=None, db=None, user=None, password=None, port=None):
|
| 17 |
+
"""Create a psycopg2 connection to Velocity's decoderdb."""
|
| 18 |
+
import psycopg2
|
| 19 |
+
return psycopg2.connect(
|
| 20 |
+
host=host or DEFAULT_HOST,
|
| 21 |
+
dbname=db or DEFAULT_DB,
|
| 22 |
+
user=user or DEFAULT_USER,
|
| 23 |
+
password=password,
|
| 24 |
+
port=port or DEFAULT_PORT,
|
| 25 |
+
sslmode="require",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_correlation_matrix(conn, study_id, module_id, group_id=None):
|
| 30 |
+
"""
|
| 31 |
+
Read correlation matrix from data_comparisons.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
conn: psycopg2 connection
|
| 35 |
+
study_id: Velocity study_id (for finding Total group if group_id not given)
|
| 36 |
+
module_id: Which module's correlations to read
|
| 37 |
+
group_id: Specific group (default: Total group)
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
network_data dict compatible with build_network.generate_network_html()
|
| 41 |
+
"""
|
| 42 |
+
cur = conn.cursor()
|
| 43 |
+
|
| 44 |
+
# Find Total group if not specified
|
| 45 |
+
if group_id is None:
|
| 46 |
+
cur.execute(
|
| 47 |
+
"SELECT group_id FROM briefing_groups WHERE study_id = %s AND type = 'total'",
|
| 48 |
+
(study_id,),
|
| 49 |
+
)
|
| 50 |
+
row = cur.fetchone()
|
| 51 |
+
if not row:
|
| 52 |
+
raise ValueError(f"No Total group found for study {study_id}")
|
| 53 |
+
group_id = row[0]
|
| 54 |
+
|
| 55 |
+
# Get correlations with item labels
|
| 56 |
+
cur.execute("""
|
| 57 |
+
SELECT a1.label AS attr1, a2.label AS attr2,
|
| 58 |
+
dc.statistic_value::float AS r
|
| 59 |
+
FROM data_comparisons dc
|
| 60 |
+
JOIN _variable_assets va1 ON va1.variable_id = dc.variable_id_1 AND va1.asset_role = 'item'
|
| 61 |
+
JOIN briefing_assets a1 ON a1.asset_id = va1.asset_id
|
| 62 |
+
JOIN _variable_assets va2 ON va2.variable_id = dc.variable_id_2 AND va2.asset_role = 'item'
|
| 63 |
+
JOIN briefing_assets a2 ON a2.asset_id = va2.asset_id
|
| 64 |
+
WHERE dc.module_id = %s AND dc.group_id_1 = %s
|
| 65 |
+
AND dc.statistic = 'correlation'
|
| 66 |
+
""", (module_id, group_id))
|
| 67 |
+
|
| 68 |
+
rows = cur.fetchall()
|
| 69 |
+
if not rows:
|
| 70 |
+
raise ValueError(f"No correlations found for module {module_id}, group {group_id}")
|
| 71 |
+
|
| 72 |
+
# Build symmetric correlation matrix
|
| 73 |
+
attrs = sorted(set(r[0] for r in rows) | set(r[1] for r in rows))
|
| 74 |
+
attr_idx = {a: i for i, a in enumerate(attrs)}
|
| 75 |
+
n = len(attrs)
|
| 76 |
+
matrix = pd.DataFrame(0.0, index=attrs, columns=attrs)
|
| 77 |
+
|
| 78 |
+
for attr1, attr2, r in rows:
|
| 79 |
+
matrix.loc[attr1, attr2] = r
|
| 80 |
+
matrix.loc[attr2, attr1] = r # symmetric
|
| 81 |
+
|
| 82 |
+
# Fill diagonal with 1.0
|
| 83 |
+
for a in attrs:
|
| 84 |
+
matrix.loc[a, a] = 1.0
|
| 85 |
+
|
| 86 |
+
# Get territory classification from aggregations
|
| 87 |
+
cur.execute("""
|
| 88 |
+
SELECT DISTINCT a.label AS territory, ba.label AS item
|
| 89 |
+
FROM briefing_aggregations a
|
| 90 |
+
JOIN briefing_files f ON f.file_id = a.file_id
|
| 91 |
+
JOIN _aggregation_assets aa ON aa.aggregation_id = a.aggregation_id
|
| 92 |
+
JOIN briefing_assets ba ON ba.asset_id = aa.asset_id
|
| 93 |
+
WHERE f.study_id = %s
|
| 94 |
+
ORDER BY a.label, ba.label
|
| 95 |
+
""", (study_id,))
|
| 96 |
+
|
| 97 |
+
agg_rows = cur.fetchall()
|
| 98 |
+
rewards_territories = {
|
| 99 |
+
"Adventure", "Autonomy", "Discipline", "Security", "Enjoyment", "Excitement",
|
| 100 |
+
}
|
| 101 |
+
item_to_territory = {}
|
| 102 |
+
for territory, item in agg_rows:
|
| 103 |
+
if territory in rewards_territories:
|
| 104 |
+
item_to_territory[item] = territory
|
| 105 |
+
|
| 106 |
+
nonrewards_attrs = set()
|
| 107 |
+
for a in attrs:
|
| 108 |
+
if a not in item_to_territory:
|
| 109 |
+
nonrewards_attrs.add(a)
|
| 110 |
+
|
| 111 |
+
# Get category indices from data_summaries (Total group, mean statistic)
|
| 112 |
+
# Category index = the attribute's mean PA across all brands
|
| 113 |
+
cur.execute("""
|
| 114 |
+
SELECT a_item.label AS attribute,
|
| 115 |
+
AVG(ds.summary_value::float * 100) AS cat_index
|
| 116 |
+
FROM data_summaries ds
|
| 117 |
+
JOIN data_variables dv ON dv.variable_id = ds.variable_id
|
| 118 |
+
JOIN briefing_groups g ON g.group_id = ds.group_id
|
| 119 |
+
JOIN _variable_assets va_item ON va_item.variable_id = ds.variable_id AND va_item.asset_role = 'item'
|
| 120 |
+
JOIN briefing_assets a_item ON a_item.asset_id = va_item.asset_id
|
| 121 |
+
WHERE g.study_id = %s AND g.type = 'total'
|
| 122 |
+
AND ds.statistic = 'mean' AND dv.type = 'PA'
|
| 123 |
+
AND ds.module_id = %s
|
| 124 |
+
GROUP BY a_item.label
|
| 125 |
+
""", (study_id, module_id))
|
| 126 |
+
|
| 127 |
+
cat_idx_rows = cur.fetchall()
|
| 128 |
+
cat_idx_map = {r[0]: round(r[1], 1) for r in cat_idx_rows}
|
| 129 |
+
|
| 130 |
+
category_indices = [cat_idx_map.get(a, 0) for a in attrs]
|
| 131 |
+
|
| 132 |
+
cur.close()
|
| 133 |
+
|
| 134 |
+
attr_to_cat_idx = dict(zip(attrs, category_indices))
|
| 135 |
+
|
| 136 |
+
return {
|
| 137 |
+
"attribute_names": attrs,
|
| 138 |
+
"attribute_codes": attrs, # same as names when reading from Velocity
|
| 139 |
+
"category_indices": category_indices,
|
| 140 |
+
"attr_to_cat_idx": attr_to_cat_idx,
|
| 141 |
+
"nonrewards_attrs": nonrewards_attrs,
|
| 142 |
+
"driver_names": attrs,
|
| 143 |
+
"corr_df": matrix,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
"""Quick test: print correlation matrix stats for study 497."""
|
| 149 |
+
import os
|
| 150 |
+
password = os.environ.get("DB_PASSWORD")
|
| 151 |
+
if not password:
|
| 152 |
+
print("Set DB_PASSWORD environment variable")
|
| 153 |
+
exit(1)
|
| 154 |
+
|
| 155 |
+
conn = get_connection(password=password)
|
| 156 |
+
data = get_correlation_matrix(conn, study_id=497, module_id=2641)
|
| 157 |
+
conn.close()
|
| 158 |
+
|
| 159 |
+
print(f"Attributes: {len(data['attribute_names'])}")
|
| 160 |
+
print(f"Rewards: {len(data['attribute_names']) - len(data['nonrewards_attrs'])}")
|
| 161 |
+
print(f"Nonrewards: {len(data['nonrewards_attrs'])}")
|
| 162 |
+
print(f"Correlation matrix: {data['corr_df'].shape}")
|
| 163 |
+
print(f"\nTop 5 correlations:")
|
| 164 |
+
corr = data["corr_df"]
|
| 165 |
+
# Get upper triangle pairs
|
| 166 |
+
pairs = []
|
| 167 |
+
for i in range(len(corr)):
|
| 168 |
+
for j in range(i + 1, len(corr)):
|
| 169 |
+
pairs.append((corr.index[i], corr.columns[j], corr.iloc[i, j]))
|
| 170 |
+
pairs.sort(key=lambda x: abs(x[2]), reverse=True)
|
| 171 |
+
for a1, a2, r in pairs[:5]:
|
| 172 |
+
print(f" {a1} × {a2}: r={r:.3f}")
|