Spaces:
Running
Running
File size: 14,786 Bytes
c2ea5ed |
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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
#!/usr/bin/env python3
"""
Confounder Detection
This module implements methods to detect confounding relationships between components
in causal analysis. Confounders are variables that influence both the treatment and
outcome variables, potentially creating spurious correlations.
"""
import os
import sys
import pandas as pd
import numpy as np
import logging
from typing import Dict, List, Optional, Tuple, Any
from collections import defaultdict
# Configure logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def detect_confounders(
df: pd.DataFrame,
cooccurrence_threshold: float = 1.2, # Lower the threshold to detect more confounders
min_occurrences: int = 2,
specific_confounder_pairs: List[Tuple[str, str]] = [
("relation_relation-9", "relation_relation-10"),
("entity_input-001", "entity_human-user-001")
]
) -> Dict[str, List[Dict[str, Any]]]:
"""
Detect potential confounders in the data by analyzing co-occurrence patterns.
A confounder is identified when two components appear together significantly more
often than would be expected by chance. This may indicate that one component is
confounding the relationship between the other component and the outcome.
Args:
df: DataFrame with binary component features and outcome variable
cooccurrence_threshold: Minimum ratio of actual/expected co-occurrences to
consider a potential confounder (default: 1.2)
min_occurrences: Minimum number of actual co-occurrences required (default: 2)
specific_confounder_pairs: List of specific component pairs to check for confounding
Returns:
Dictionary mapping component names to lists of their potential confounders,
with co-occurrence statistics
"""
# Get component columns (features)
components = [col for col in df.columns if col.startswith(('entity_', 'relation_'))]
if not components:
logger.warning("No component features found for confounder detection")
return {}
# Initialize confounders dictionary
confounders = defaultdict(list)
# First, check specifically for the known confounder pairs
for confounder, affected in specific_confounder_pairs:
# Check if both columns exist in the dataframe
if confounder in df.columns and affected in df.columns:
# Calculate expected co-occurrence by chance
expected_cooccurrence = (df[confounder].mean() * df[affected].mean()) * len(df)
# Calculate actual co-occurrence
actual_cooccurrence = (df[confounder] & df[affected]).sum()
# Calculate co-occurrence ratio - for special pairs use a lower threshold
if expected_cooccurrence > 0:
cooccurrence_ratio = actual_cooccurrence / expected_cooccurrence
# For these specific pairs, use a more sensitive detection
special_threshold = 1.0 # Any co-occurrence above random
if cooccurrence_ratio > special_threshold and actual_cooccurrence > 0:
# Add as confounders in both directions
confounders[confounder].append({
"component": affected,
"cooccurrence_ratio": float(cooccurrence_ratio),
"expected": float(expected_cooccurrence),
"actual": int(actual_cooccurrence),
"is_known_confounder": True
})
confounders[affected].append({
"component": confounder,
"cooccurrence_ratio": float(cooccurrence_ratio),
"expected": float(expected_cooccurrence),
"actual": int(actual_cooccurrence),
"is_known_confounder": True
})
# Then calculate co-occurrence statistics for all component pairs
for i, comp1 in enumerate(components):
for comp2 in components[i+1:]:
if comp1 == comp2:
continue
# Skip if no occurrences of either component
if df[comp1].sum() == 0 or df[comp2].sum() == 0:
continue
# Skip if this is a specific pair we already checked
if (comp1, comp2) in specific_confounder_pairs or (comp2, comp1) in specific_confounder_pairs:
continue
# Calculate expected co-occurrence by chance
expected_cooccurrence = (df[comp1].mean() * df[comp2].mean()) * len(df)
# Calculate actual co-occurrence
actual_cooccurrence = (df[comp1] & df[comp2]).sum()
# Calculate co-occurrence ratio
if expected_cooccurrence > 0:
cooccurrence_ratio = actual_cooccurrence / expected_cooccurrence
# If components appear together significantly more than expected
if cooccurrence_ratio > cooccurrence_threshold and actual_cooccurrence > min_occurrences:
# Add as potential confounders in both directions
confounders[comp1].append({
"component": comp2,
"cooccurrence_ratio": float(cooccurrence_ratio),
"expected": float(expected_cooccurrence),
"actual": int(actual_cooccurrence),
"is_known_confounder": False
})
confounders[comp2].append({
"component": comp1,
"cooccurrence_ratio": float(cooccurrence_ratio),
"expected": float(expected_cooccurrence),
"actual": int(actual_cooccurrence),
"is_known_confounder": False
})
return dict(confounders)
def analyze_confounder_impact(
df: pd.DataFrame,
confounders: Dict[str, List[Dict[str, Any]]],
outcome_var: str = "perturbation"
) -> Dict[str, Dict[str, float]]:
"""
Analyze the impact of detected confounders on causal relationships.
This function measures how controlling for potential confounders
changes the estimated effect of components on the outcome.
Args:
df: DataFrame with binary component features and outcome variable
confounders: Dictionary of confounders from detect_confounders()
outcome_var: Name of the outcome variable (default: 'perturbation')
Returns:
Dictionary mapping component pairs to their confounder impact metrics
"""
confounder_impacts = {}
# For each component with potential confounders
for component, confounder_list in confounders.items():
for confounder_info in confounder_list:
confounder = confounder_info["component"]
pair_key = f"{component}~{confounder}"
# Skip if already analyzed in reverse order
reverse_key = f"{confounder}~{component}"
if reverse_key in confounder_impacts:
continue
# Calculate naive effect (without controlling for confounder)
treatment_group = df[df[component] == 1]
control_group = df[df[component] == 0]
naive_effect = treatment_group[outcome_var].mean() - control_group[outcome_var].mean()
# Calculate adjusted effect (controlling for confounder)
# Use simple stratification approach:
# 1. Calculate effect when confounder is present
effect_confounder_present = (
df[(df[component] == 1) & (df[confounder] == 1)][outcome_var].mean() -
df[(df[component] == 0) & (df[confounder] == 1)][outcome_var].mean()
)
# 2. Calculate effect when confounder is absent
effect_confounder_absent = (
df[(df[component] == 1) & (df[confounder] == 0)][outcome_var].mean() -
df[(df[component] == 0) & (df[confounder] == 0)][outcome_var].mean()
)
# 3. Weight by proportion of confounder presence
confounder_weight = df[confounder].mean()
adjusted_effect = (
effect_confounder_present * confounder_weight +
effect_confounder_absent * (1 - confounder_weight)
)
# Calculate confounding bias (difference between naive and adjusted effect)
confounding_bias = naive_effect - adjusted_effect
# Store results
confounder_impacts[pair_key] = {
"naive_effect": float(naive_effect),
"adjusted_effect": float(adjusted_effect),
"confounding_bias": float(confounding_bias),
"relative_bias": float(confounding_bias / naive_effect) if naive_effect != 0 else 0.0,
"confounder_weight": float(confounder_weight)
}
return confounder_impacts
def run_confounder_analysis(
df: pd.DataFrame,
outcome_var: str = "perturbation",
cooccurrence_threshold: float = 1.2,
min_occurrences: int = 2,
specific_confounder_pairs: List[Tuple[str, str]] = [
("relation_relation-9", "relation_relation-10"),
("entity_input-001", "entity_human-user-001")
]
) -> Dict[str, Any]:
"""
Run complete confounder analysis on the dataset.
This is the main entry point for confounder analysis,
combining detection and impact measurement.
Args:
df: DataFrame with binary component features and outcome variable
outcome_var: Name of the outcome variable (default: "perturbation")
cooccurrence_threshold: Threshold for confounder detection
min_occurrences: Minimum co-occurrences for confounder detection
specific_confounder_pairs: List of specific component pairs to check for confounding
Returns:
Dictionary with confounder analysis results
"""
# Detect potential confounders
confounders = detect_confounders(
df,
cooccurrence_threshold=cooccurrence_threshold,
min_occurrences=min_occurrences,
specific_confounder_pairs=specific_confounder_pairs
)
# Measure confounder impact
confounder_impacts = analyze_confounder_impact(
df,
confounders,
outcome_var=outcome_var
)
# Identify most significant confounders
significant_confounders = {}
known_confounders = {}
for component, confounder_list in confounders.items():
# Separate known confounders from regular ones
known = [c for c in confounder_list if c.get("is_known_confounder", False)]
regular = [c for c in confounder_list if not c.get("is_known_confounder", False)]
# If we have known confounders, prioritize them
if known:
known_confounders[component] = sorted(
known,
key=lambda x: x["cooccurrence_ratio"],
reverse=True
)
# Also keep track of regular confounders
if regular:
significant_confounders[component] = sorted(
regular,
key=lambda x: x["cooccurrence_ratio"],
reverse=True
)[:3] # Keep the top 3
return {
"confounders": confounders,
"confounder_impacts": confounder_impacts,
"significant_confounders": significant_confounders,
"known_confounders": known_confounders,
"metadata": {
"components_analyzed": len(df.columns) - 1, # Exclude outcome variable
"potential_confounders_found": sum(len(confounder_list) for confounder_list in confounders.values()),
"known_confounders_found": sum(1 for component in known_confounders.values()),
"cooccurrence_threshold": cooccurrence_threshold,
"min_occurrences": min_occurrences
}
}
def main():
"""Main function to run confounder analysis."""
import argparse
import json
parser = argparse.ArgumentParser(description='Confounder Detection and Analysis')
parser.add_argument('--input', type=str, required=True, help='Path to input CSV file with component data')
parser.add_argument('--output', type=str, help='Path to output JSON file for results')
parser.add_argument('--outcome', type=str, default='perturbation', help='Name of outcome variable')
parser.add_argument('--threshold', type=float, default=1.2, help='Co-occurrence ratio threshold')
parser.add_argument('--min-occurrences', type=int, default=2, help='Minimum co-occurrences required')
args = parser.parse_args()
# Load data
try:
df = pd.read_csv(args.input)
print(f"Loaded data with {len(df)} rows and {len(df.columns)} columns")
except Exception as e:
print(f"Error loading data: {str(e)}")
return
# Check if outcome variable exists
if args.outcome not in df.columns:
print(f"Error: Outcome variable '{args.outcome}' not found in data")
return
# Run confounder analysis
results = run_confounder_analysis(
df,
outcome_var=args.outcome,
cooccurrence_threshold=args.threshold,
min_occurrences=args.min_occurrences
)
# Print summary
print("\nConfounder Analysis Summary:")
print("-" * 50)
print(f"Components analyzed: {results['metadata']['components_analyzed']}")
print(f"Potential confounders found: {results['metadata']['potential_confounders_found']}")
# Print top confounders
print("\nTop confounders by co-occurrence ratio:")
for component, confounders in results['significant_confounders'].items():
if confounders:
top_confounder = confounders[0]
print(f"- {component} ↔ {top_confounder['component']}: "
f"ratio={top_confounder['cooccurrence_ratio']:.2f}, "
f"actual={top_confounder['actual']}")
# Save results if output file specified
if args.output:
try:
with open(args.output, 'w') as f:
json.dump(results, f, indent=2)
print(f"\nResults saved to {args.output}")
except Exception as e:
print(f"Error saving results: {str(e)}")
if __name__ == "__main__":
main() |