from scipy.stats import pearsonr import numpy as np import warnings def analyze_fc_patterns(latents, demographics): results = {} # Suppress the ConstantInputWarning with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=RuntimeWarning) for demo_name, demo_values in demographics.items(): # Check if the demographic is categorical or continuous if demo_name not in ['sex', 'gender']: # For continuous variables correlations = [] p_values = [] for latent_dim in range(latents.shape[1]): # Check for constant values that would cause correlation issues if np.all(latents[:, latent_dim] == latents[0, latent_dim]) or np.all(demo_values == demo_values[0]): # If either array is constant, correlation is undefined r, p = np.nan, np.nan else: try: # Convert to numpy array if not already demo_array = np.array(demo_values, dtype=float) # Calculate correlation r, p = pearsonr(latents[:, latent_dim], demo_array) except (ValueError, TypeError) as e: print(f"Error calculating correlation for {demo_name}, dimension {latent_dim}: {e}") r, p = np.nan, np.nan correlations.append(r) p_values.append(p) results[demo_name] = {'correlations': correlations, 'p_values': p_values} return results