Pythonimport pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import chi2_contingency
import numpy as np
import warnings
Suppress warnings for cleaner output
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings('ignore', category=UserWarning)
--- Create a dummy data file 'PATH2RESULTS' for demonstration ---
PATH2RESULTS = 'dummy_results.csv'
def create_dummy_data():
"""Creates a dummy CSV file to simulate the user's data."""
print("Creating dummy data file 'dummy_results.csv'...")
num_rows = 834 # Match the user's total N (453+381)
data = {
'testimony_id': range(1, num_rows + 1),
# Simulate belief structures (based on user's distribution)
'mist_belief_structure': np.random.choice(
['MONO_POSITIVE', 'OSCILLATING', 'ASCENDING', 'MONO_NEGATIVE', 'DESCENDING', 'EMPTY OR SINGLE POINT'],
num_rows,
p=[375/834, 219/834, 98/834, 78/834, 64/834, (834-375-219-98-78-64)/834]
),
# Simulate practice structures (based on user's distribution)
'mist_practice_structure': np.random.choice(
['OSCILLATING', 'MONO_POSITIVE', 'DESCENDING', 'ASCENDING', 'MONO_NEGATIVE', 'EMPTY OR SINGLE POINT'],
num_rows,
p=[598/834, 192/834, 24/834, 18/834, 2/834, (834-598-192-24-18-2)/834]
),
# Dummy scatter values
'mist_practice_scatter': np.random.rand(num_rows),
'mist_belief_scatter': np.random.rand(num_rows),
# Simulate gender (based on user's distribution)
'gender': np.random.choice(['M', 'F', 'Unknown'], num_rows, p=[453/834, 381/834, (834-453-381)/834]),
# Simulate year of birth (approx range)
'year_of_birth': np.random.randint(1910, 1940, num_rows),
# Simulate country of birth (based on user's distribution)
'country_of_birth': np.random.choice(
['Poland', 'Germany', 'Czechoslovakia', 'Hungary', 'Balkans_group', 'Russia_group',
'Austria-Hungary', 'Austria', 'Benelux_group', 'France', 'Middle East_group', 'United Kingdom',
'Danzig', 'Denmark', 'USA', 'Italy', 'Palestine',
'Belgium', 'Netherlands', 'Greece', 'Yugoslavia', 'Russian Empire', 'Latvia', 'Tunisia'], # Add some originals for 'process_meta' to catch
num_rows,
p=[298/834, 150/834, 77/834, 64/834, 53/834, 52/834, 39/834, 35/834, 29/834, 10/834, 7/834, 7/834,
4/834, 3/834, 2/834, 1/834, 1/834,
1/834, 1/834, 1/834, 1/834, 1/834, 1/834, 1/834]
),
# Simulate interview country (based on user's distribution)
'interview_country': np.random.choice(
['U.S.A.', 'Canada', 'United Kingdom', 'Australia', 'New Zealand', 'Israel',
'Ireland', 'Poland', 'Italy', 'Hungary', 'South Africa'],
num_rows,
p=[500/834, 131/834, 96/834, 70/834, 11/834, 20/834, 2/834, 1/834, 1/834, 1/834, 1/834]
)
}
# Add some NaNs to year_of_birth
data['year_of_birth'] = [y if np.random.rand() > 0.05 else np.nan for y in data['year_of_birth']]
df = pd.DataFrame(data)
df.set_index('testimony_id', inplace=True)
df.to_csv(PATH2RESULTS)
print(f"Dummy file '{PATH2RESULTS}' with {num_rows} rows created.\n")
--- User's Provided Functions (with minor fixes for incorporate_metadata) ---
def incorporate_metadata(df, o_name):
"""
Dummy function to simulate loading metadata.
In the user's code, this likely joins with another file.
Here, we just pass the df through as the dummy data already contains metadata.
"""
print(f"Simulating metadata incorporation (using data from {o_name})...")
# In a real scenario, this might be:
# meta_df = pd.read_csv('metadata.csv', index_col='testimony_id')
# df = df.join(meta_df)
# But our dummy data is already merged.
return df
def get_age_group(year_of_birth):
"""
born before 1921 (18+ at start of war): '18+',
born before 1924 (15-17 at start of war), '15-17'
born before 1929 (10-14 at start of war) '10-14'
born before 1933 and after 1929 (6-9 at start of war) '6-9'
born 1933 or later (5 or younger at start of war) '0-5'
:param year_of_birth:
:return:
"""
if pd.isna(year_of_birth):
return 'Unknown'
year_of_birth = int(year_of_birth)
if year_of_birth <= 1920:
return '18+'
elif year_of_birth <= 1923:
return '15-17'
elif year_of_birth <= 1928:
return '10-14'
elif year_of_birth <= 1932:
return '6-9'
else:
return '0-5'
def year_of_birth_hist(mistral_df):
"""
Plots histograms of year_of_birth for each practice and belief structure category.
:param mistral_df:
:return:
"""
print("\n📊 Generating year_of_birth histograms for each structure category...")
for struct in ['practice_struct', 'belief_struct']:
categories = mistral_df[struct].unique()
for i, category in enumerate(categories):
if category == "EMPTY OR SINGLE POINT":
continue
plt.figure(figsize=(10, 6))
subset = mistral_df[mistral_df[struct] == category]
if subset.empty or subset['year_of_birth'].dropna().empty:
print(f"Skipping histogram for {struct} = {category} (no data)")
plt.close()
continue
sns.histplot(subset['year_of_birth'].dropna(), bins=20, kde=False)
plt.title(f'Year of Birth Distribution for {struct} = {category}')
plt.xlabel('Year of Birth')
plt.ylabel('Count')
# Simplified y-ticks
plt.gca().get_yaxis().set_major_locator(plt.MaxNLocator(integer=True))
plt.tight_layout()
# Save the plot
plot_filename = f'year_of_birth_hist_{struct}_{category.replace(" ", "_")}.png'
plt.savefig(plot_filename)
print(f"Saved histogram: {plot_filename}")
plt.close() # Close plot to avoid displaying in output
def process_meta(df, o_name="mistral_taxonomy_and_meta.csv"):
df = incorporate_metadata(df, o_name=o_name)
# remove rows with one of the structures "EMPTY OR SINGLE POINT"
df = df[~df['practice_struct'].isin(["EMPTY OR SINGLE POINT"])]
df = df[~df['belief_struct'].isin(["EMPTY OR SINGLE POINT"])]
# select relevant columns
# Ensure all columns exist, especially the new metadata ones
all_cols = list(df.columns)
meta_cols = [col for col in ['practice_struct', 'belief_struct',
'practice_scatter', 'belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country'] if col in all_cols]
df = df[meta_cols]
# replace "Belgium", "Netherlands" and "Luxembourg" with "Benelux" in country_of_birth
# "Bulgaria", "Greece", "Romania" and "Yugoslavia" with "Balkans" in country_of_birth
# Middle east countries: "Tunisia", "Morocco", "Tripolitania", "Iraq"
# Russia: "Russian Empire", "Union of Soviet Socialist Republics", "Latvia", "Lithuania"
df['country_of_birth'] = df['country_of_birth'].replace(
{"Belgium": "Benelux", "Netherlands": "Benelux", "Luxembourg": "Benelux",
"Bulgaria": "Balkans", "Greece": "Balkans", "Yugoslavia": "Balkans", "Romania": "Balkans",
"Tunisia": "Middle East", "Morocco": "Middle East",
"Tripolitania": "Middle East", "Iraq": "Middle East",
"Russian Empire": "Russia", "Union of Soviet Socialist Republics": "Russia",
"Latvia": "Russia", "Lithuania": "Russia"
}
)
# in interview_country, replace "U.S.A." and "Canada" to "North America"
# "New Zealand" and "Australia" to "Australia and New Zealand"
df['interview_country'] = df['interview_country'].replace(
{"U.S.A.": "North America", "Canada": "North America",
"New Zealand": "Australia and New Zealand", "Australia": "Australia and New Zealand"})
# add age_group column
df['age_group'] = df['year_of_birth'].apply(get_age_group)
return df
def basic_exploration(df_meta):
"""
- print the number of trajectories per each country of birth
- print the number of trajectories per each gender
- print the number of trajectories per each country of interview
- plot a histogram of year_of_birth
- print the number of trajectories per each structure category
:param df_meta:
:return:
"""
print("\n--- Basic Exploration ---")
print("\nNumber of trajectories per each country of birth (after processing):")
print(df_meta['country_of_birth'].value_counts())
print("\nNumber of trajectories per each gender:")
print(df_meta['gender'].value_counts())
print("\nNumber of trajectories per each country of interview (after processing):")
print(df_meta['interview_country'].value_counts())
for aspect in ["belief", "practice"]:
print(f"\n~~ Exploring {aspect} ~~\n")
print("\nNumber of trajectories per structure:")
print(df_meta[f"{aspect}_struct"].value_counts())
# plot a histogram of year_of_birth
plt.figure(figsize=(10, 6))
if not df_meta['year_of_birth'].dropna().empty:
sns.histplot(df_meta['year_of_birth'].dropna(), bins=20, kde=False)
plt.title('Overall Year of Birth Distribution')
plt.xlabel('Year of Birth')
plt.ylabel('Count')
plt.tight_layout()
plot_filename = 'year_of_birth_hist_overall.png'
plt.savefig(plot_filename)
print(f"\nSaved histogram: {plot_filename}")
plt.close()
else:
print("\nSkipping overall year_of_birth histogram (no data).")
plt.close()
--- New Function: chi_square_test ---
def chi_square_test(df_meta):
"""
Performs Chi-Square tests of independence between metadata variables
and trajectory structure variables.
Applies filtering and grouping as recommended to handle bias.
"""
print("\n" + "="*30)
print("🔬 Starting Chi-Square Tests 🔬")
print("="*30)
# --- 1. Apply Filtering: Control for interview_country bias ---
# We focus on the largest, most coherent group: 'North America'
df_test = df_meta[df_meta['interview_country'] == 'North America'].copy()
print(f"\nℹ️ Note: Filtering data to 'North America' interviews only to control for sampling bias.")
print(f" Original size after cleaning: {len(df_meta)}, Filtered size for testing: {len(df_test)}\n")
if len(df_test) < 20: # Need a reasonable sample size
print("⚠️ Warning: Insufficient data from 'North America' (n < 20). Cannot perform reliable Chi-Square tests.")
return
# --- 2. Apply Grouping: Control for 'country_of_birth' long-tail bias ---
# Group small categories into 'Other' for statistical validity
min_n = 25 # Set a minimum threshold for a category
counts = df_test['country_of_birth'].value_counts()
small_categories = counts[counts < min_n].index.tolist()
# Only create 'Other' group if there are small categories
if small_categories:
print(f"ℹ️ Grouping 'country_of_birth' categories with n < {min_n} into 'Other'.")
print(f" Categories to be grouped: {small_categories}")
df_test['country_of_birth_grouped'] = df_test['country_of_birth'].replace(small_categories, 'Other')
else:
df_test['country_of_birth_grouped'] = df_test['country_of_birth']
# After grouping, check if 'Other' itself is too small and drop it from testing
other_count = (df_test['country_of_birth_grouped'] == 'Other').sum()
drop_other = (other_count < min_n) and (other_count > 0)
if drop_other:
print(f"ℹ️ 'Other' group is too small (n={other_count}), will be excluded from country test.")
# --- 3. Define variables and run tests ---
outcome_vars = ['belief_struct', 'practice_struct']
# We test against gender, age, and grouped country of birth.
# We don't test 'interview_country' because we've filtered *for* it (it's controlled).
meta_vars = ['gender', 'age_group', 'country_of_birth_grouped']
for outcome in outcome_vars:
print("\n" + "~"*40)
print(f"📊 Testing Associations for: {outcome.upper()} 📊")
print("~"*40)
for meta_var in meta_vars:
print(f"\n--- Test: {outcome} vs. {meta_var} ---")
# --- 4. Clean data for this specific test ---
test_data = df_test.copy()
# Remove 'Unknown' or invalid entries for the variable being tested
if meta_var == 'age_group':
test_data = test_data[test_data['age_group'] != 'Unknown']
elif meta_var == 'gender':
test_data = test_data[test_data['gender'].isin(['M', 'F'])]
elif meta_var == 'country_of_birth_grouped':
if drop_other:
test_data = test_data[test_data['country_of_birth_grouped'] != 'Other']
if test_data.empty:
print("Skipping test: No valid data after cleaning.")
continue
# --- 5. Create Contingency Table ---
contingency_table = pd.crosstab(test_data[meta_var], test_data[outcome])
# Drop rows/cols with all zeros (can happen with small samples)
contingency_table = contingency_table.loc[(contingency_table.sum(axis=1) > 0), (contingency_table.sum(axis=0) > 0)]
if contingency_table.empty or contingency_table.shape[0] < 2 or contingency_table.shape[1] < 2:
print(f"Skipping test: Contingency table for {meta_var} vs {outcome} is trivial (less than 2x2) or empty after cleaning.")
continue
print("\nContingency Table:")
print(contingency_table)
# --- 6. Run Chi-Square Test ---
try:
chi2, p_val, dof, expected_freq = chi2_contingency(contingency_table)
print(f"\nChi-Square Statistic (X²): {chi2:.3f}")
print(f"Degrees of Freedom (dof): {dof}")
print(f"P-value: {p_val:.4f}")
# --- 7. Check for reliability (Expected frequency < 5) ---
unreliable_cells = np.sum(expected_freq < 5)
total_cells = expected_freq.size
if total_cells > 0:
percent_unreliable = (unreliable_cells / total_cells) * 100
if percent_unreliable > 20:
print(f"⚠️ Warning: {percent_unreliable:.1f}% of cells have expected frequency < 5. Test may be unreliable.")
# --- 8. Interpret Result ---
if p_val < 0.05:
print("✅ Result: Statistically Significant (p < 0.05).")
print(f" A significant association is likely between {meta_var} and {outcome}.")
else:
print("❌ Result: Not Statistically Significant (p >= 0.05).")
print(f" No significant association found between {meta_var} and {outcome}.")
except ValueError as e:
# This can happen if a row/column sums to zero after filtering
print(f"⚠️ Error running test (e.g., empty table or sums to zero): {e}")
--- Main execution block (now using the dummy data) ---
if name == 'main':
# Create the dummy data file
create_dummy_data()
# Read the dummy data
try:
data = pd.read_csv(PATH2RESULTS, index_col='testimony_id')
# --- Process data as in user's script ---
# gpt_df = data[['gpt_practice_structure', 'gpt_belief_structure',
# 'gpt_practice_scatter', 'gpt_belief_scatter']] # Dummy data doesn't have 'gpt'
mistral_df = data[['mist_practice_structure', 'mist_belief_structure',
'mist_practice_scatter', 'mist_belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country' # Pass metadata to process_meta
]]
# rename columns
mistral_df.columns = ['practice_struct', 'belief_struct',
'practice_scatter', 'belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country']
# --- Run all functions ---
df_meta = process_meta(mistral_df)
basic_exploration(df_meta)
# Run histogram function (optional, can be noisy)
# year_of_birth_hist(df_meta)
print("\nSkipping individual 'year_of_birth_hist' plots for brevity.")
# Run the newly implemented Chi-Square test function
chi_square_test(df_meta)
except FileNotFoundError:
print(f"Error: Dummy file '{PATH2RESULTS}' was not found.")
except KeyError as e:
print(f"Error: A required column is missing from the dummy data. {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Code outputTraceback (most recent call last):
File "", line 356, in
File "", line 48, in create_dummy_data
File "mtrand.pyx", line 975, in numpy.random.mtrand.RandomState.choice
ValueError: probabilities do not sum to 1