Here is the implementation for the struct_meta_conf_matrix function.This implementation uses pandas.melt to combine the practice_struct and belief_struct columns, which allows pandas.crosstab to create a single matrix with a hierarchical column index (5 for practice, 5 for belief) as you wanted.It then uses seaborn.heatmap to plot the resulting crosstabulations. For the country-based plots, I've added logic to only show the Top 15 most frequent countries to keep the visualizations readable.Python"""
This script is for exploring the connections between the testimonies metadata
and the taxonomy structures.
For the taxonomy data, we have two versions of results: Mistral and GPT.
Features we include:
- Gender
- Age
- Country of Birth
Taxonomy Structures:
-
Practice: Active, Inactive, Ascending, Descending, Oscillating
-
Belief: Positive, Negative, Ascending, Descending, Oscillating
-
An additional feature we will consider to review is scatter: ranges from 0 to 1.
"""
import pandas as pd
import sys
import seaborn as sns
import matplotlib.pyplot as plt
add path to /home/esther/PycharmProjects/religious-paths/analyzing-paths
sys.path.append('/home/esther/PycharmProjects/religious-paths/analyzing-paths')
from predefined_taxonomy import *
Show all columns
pd.set_option('display.max_columns', None)
PATH2RESULTS = "/home/esther/PycharmProjects/religious-paths/data/results/predefined_taxonomy_mistral_gpt_results.csv"
def struct_meta_conf_matrix(data: pd.DataFrame):
"""
Plots confusion matrices (crosstabs) showing the relationships
between taxonomy structures and metadata.
1. practice and belief structures (10 columns) vs gender
2. practice and belief structures vs country of birth (Top 15)
3. practice and belief structures vs interview country (Top 15)
:param data: DataFrame with columns ['practice_struct', 'belief_struct',
'gender', 'country_of_birth', 'interview_country']
:return: None (displays plots)
"""
print("📊 Generating structure vs. metadata crosstab heatmaps...")
# --- 1. Data Preparation ---
# Melt the dataframe to combine practice and belief structures into a single hierarchy
# This achieves the "10 columns" (5 for practice, 5 for belief) in a single matrix
metadata_cols = ['gender', 'country_of_birth', 'interview_country']
structure_cols = ['practice_struct', 'belief_struct']
# Check that all required columns are present
required_cols = metadata_cols + structure_cols
missing_cols = [col for col in required_cols if col not in data.columns]
if missing_cols:
print(f"Warning: Missing required columns: {missing_cols}. Skipping this function.")
return
df_melted = data.melt(
id_vars=metadata_cols,
value_vars=structure_cols,
var_name='structure_type',
value_name='structure_value'
)
# Define the desired order of structures to make the plot logical
practice_order = ['Active', 'Inactive', 'Ascending', 'Descending', 'Oscillating']
belief_order = ['Positive', 'Negative', 'Ascending', 'Descending', 'Oscillating']
# Create a list of tuples for the MultiIndex column order
column_order = [('practice_struct', p) for p in practice_order] + \
[('belief_struct', b) for b in belief_order]
# --- 2. Plot 1: Gender vs. Structures ---
print(" - Plotting Gender vs. Structures...")
try:
# Create the crosstab
ct_gender = pd.crosstab(
df_melted['gender'],
[df_melted['structure_type'], df_melted['structure_value']]
)
# Reorder and fill missing columns with 0
ct_gender_ordered = ct_gender.reindex(columns=column_order, fill_value=0)
plt.figure(figsize=(18, 7))
sns.heatmap(ct_gender_ordered, annot=True, fmt='d', cmap='viridis', linewidths=.5)
plt.title('Taxonomy Structures vs. Gender', fontsize=16)
plt.xlabel('Taxonomy Structure', fontsize=12)
plt.ylabel('Gender', fontsize=12)
plt.tight_layout()
plt.show()
except Exception as e:
print(f" - Could not plot Gender vs. Structures: {e}")
# --- 3. Plot 2: Country of Birth vs. Structures ---
print(" - Plotting Country of Birth vs. Structures (Top 15)...")
try:
N_COUNTRIES = 15
top_countries_cob = data['country_of_birth'].value_counts().nlargest(N_COUNTRIES).index
df_melted_cob = df_melted[df_melted['country_of_birth'].isin(top_countries_cob)]
if not df_melted_cob.empty:
ct_cob = pd.crosstab(
df_melted_cob['country_of_birth'],
[df_melted_cob['structure_type'], df_melted_cob['structure_value']]
)
# Reorder and fill
ct_cob_ordered = ct_cob.reindex(columns=column_order, fill_value=0)
# Reorder index to show most frequent on top
ct_cob_ordered = ct_cob_ordered.reindex(index=top_countries_cob)
plt.figure(figsize=(20, 10))
sns.heatmap(ct_cob_ordered, annot=True, fmt='d', cmap='viridis', linewidths=.5)
plt.title(f'Taxonomy Structures vs. Country of Birth (Top {N_COUNTRIES})', fontsize=16)
plt.xlabel('Taxonomy Structure', fontsize=12)
plt.ylabel('Country of Birth', fontsize=12)
plt.tight_layout()
plt.show()
else:
print(" - No data to plot for Country of Birth.")
except Exception as e:
print(f" - Could not plot Country of Birth vs. Structures: {e}")
# --- 4. Plot 3: Interview Country vs. Structures ---
print(" - Plotting Interview Country vs. Structures (Top 15)...")
try:
top_countries_ic = data['interview_country'].value_counts().nlargest(N_COUNTRIES).index
df_melted_ic = df_melted[df_melted['interview_country'].isin(top_countries_ic)]
if not df_melted_ic.empty:
ct_ic = pd.crosstab(
df_melted_ic['interview_country'],
[df_melted_ic['structure_type'], df_melted_ic['structure_value']]
)
# Reorder and fill
ct_ic_ordered = ct_ic.reindex(columns=column_order, fill_value=0)
# Reorder index to show most frequent on top
ct_ic_ordered = ct_ic_ordered.reindex(index=top_countries_ic)
plt.figure(figsize=(20, 10))
sns.heatmap(ct_ic_ordered, annot=True, fmt='d', cmap='viridis', linewidths=.5)
plt.title(f'Taxonomy Structures vs. Interview Country (Top {N_COUNTRIES})', fontsize=16)
plt.xlabel('Taxonomy Structure', fontsize=12)
plt.ylabel('Interview Country', fontsize=12)
plt.tight_layout()
plt.show()
else:
print(" - No data to plot for Interview Country.")
except Exception as e:
print(f" - Could not plot Interview Country vs. Structures: {e}")
def scatter_meta_correlation(data: pd.DataFrame):
"""
Explores the correlation between scatter values and numerical metadata features.
:param data:
:return:
"""
pass
if name == 'main':
df = pd.read_csv(PATH2RESULTS, index_col='testimony_id')
gpt_df = df[['gpt_practice_structure', 'gpt_belief_structure',
'gpt_practice_scatter', 'gpt_belief_scatter']]
mistral_df = df[['mist_practice_structure', 'mist_belief_structure',
'mist_practice_scatter', 'mist_belief_scatter']]
mistral_df = incorporate_metadata(mistral_df, o_name="mistral_taxonomy_and_meta.csv")
meta_cols = ['mist_practice_structure', 'mist_belief_structure', # Renamed from your list, one 'mist_practice_structure' was duplicated
'mist_practice_scatter', 'mist_belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country']
# Corrected filter to match the intended columns
# Your original list had a typo: 'mist_practice_structure' was listed twice.
# I'm assuming you meant 'mist_belief_structure' for the second one.
mistral_df = mistral_df[meta_cols]
mistral_df.columns = ['practice_struct', 'belief_struct',
'practice_scatter', 'belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country']
# --- Analysis ---
# Create a copy to avoid SettingWithCopyWarning during data cleaning
analysis_df = mistral_df.copy()
# Data Cleaning: Convert year_of_birth to numeric age
# We need to handle non-numeric values
if 'year_of_birth' in analysis_df.columns:
analysis_df['year_of_birth'] = pd.to_numeric(analysis_df['year_of_birth'], errors='coerce')
# Simple age calculation (assuming current year is ~2024 for analysis)
# A more robust approach might use the interview date if available
analysis_df['age'] = 2024 - analysis_df['year_of_birth']
# Clean categorical data (e.g., strip whitespace, handle 'nan' strings)
for col in ['gender', 'country_of_birth', 'interview_country', 'practice_struct', 'belief_struct']:
if col in analysis_df.columns:
analysis_df[col] = analysis_df[col].astype(str).str.strip().replace('nan', pd.NA)
# Drop rows where key analysis columns are missing
analysis_df = analysis_df.dropna(subset=['practice_struct', 'belief_struct', 'gender',
'country_of_birth', 'interview_country'], how='all')
struct_meta_conf_matrix(analysis_df)
scatter_meta_correlation(analysis_df)
print("Analysis complete.")
Key changes and additions:Imports: Added import seaborn as sns and import matplotlib.pyplot as plt at the top of the script.pd.melt: This is the core logic. It takes the 'practice_struct' and 'belief_struct' columns and "unpivots" them into two new columns: structure_type (which will contain the names 'practice_struct' or 'belief_struct') and structure_value (which will contain the actual structures like 'Active', 'Positive', etc.).pd.crosstab: This function is used to create the contingency table. We set the metadata (e.g., df_melted['gender']) as the index and the two new structure columns ([df_melted['structure_type'], df_melted['structure_value']]) as the columns. This automatically creates the 10-column hierarchical index you wanted.Column Ordering:I created practice_order and belief_order lists based on your script's docstring.I combine these into column_order, which is a list of tuples [('practice_struct', 'Active'), ('practice_struct', 'Inactive'), ..., ('belief_struct', 'Positive'), ...].I use .reindex(columns=column_order, fill_value=0) on the crosstab. This ensures the columns are always in the same logical order (all 5 practice, then all 5 belief) and that any structures not present in the data still appear as a column of zeros.Readability (Top 15): For 'country_of_birth' and 'interview_country', I added logic to find the top 15 most common countries and filter the DataFrame before plotting. Plotting dozens of countries would make the heatmap unreadable. I also reordered the y-axis (the index) to show the most frequent country at the top.if name == 'main' block:I corrected a small typo in your meta_cols list (you had mist_practice_structure twice).I added some basic data cleaning steps (like converting year_of_birth to age and cleaning string columns) to make the plotting functions more robust.Would you like me to implement the scatter_meta_correlation function next?