Correlation-network / velocity_source.py
hemsby's picture
feat: add Velocity data source for correlation networks
c3fc7dd
Raw History Blame Contribute Delete
6.21 kB
"""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}")