Builder-Neekhil commited on
Commit
703ee9e
·
verified ·
1 Parent(s): 8001279

Upload phase2_marriage_duration.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. phase2_marriage_duration.py +623 -0
phase2_marriage_duration.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Phase 2: Marriage Duration Longitudinal Model
3
+ ==============================================
4
+ Dataset: vedastro-org/15000-Famous-People-Marriage-Divorce-Info
5
+ 15,807 famous people → 18,148 marriage records
6
+
7
+ Goal: Extract marriage duration statistics, build survival model,
8
+ and create longevity prior features (base rates) that can
9
+ augment the main relationship predictor.
10
+ """
11
+
12
+ import os
13
+ import json
14
+ import warnings
15
+ import numpy as np
16
+ import pandas as pd
17
+ import matplotlib
18
+ matplotlib.use('Agg')
19
+ import matplotlib.pyplot as plt
20
+ import seaborn as sns
21
+ from datasets import load_dataset
22
+ from datetime import datetime
23
+ import re
24
+ import joblib
25
+
26
+ warnings.filterwarnings('ignore')
27
+ np.random.seed(42)
28
+
29
+ OUTPUT_DIR = "/app/phase2_output"
30
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
31
+ os.makedirs(f"{OUTPUT_DIR}/figures", exist_ok=True)
32
+
33
+ # ============================================================
34
+ # 1. LOAD AND PARSE VEDASTRO DATASET
35
+ # ============================================================
36
+ print("=" * 70)
37
+ print("PHASE 2: MARRIAGE DURATION LONGITUDINAL MODEL")
38
+ print("=" * 70)
39
+
40
+ print("\nStep 1: Loading Vedastro marriage records...")
41
+ ds = load_dataset("vedastro-org/15000-Famous-People-Marriage-Divorce-Info", split="train")
42
+ print(f" Raw records: {len(ds)}")
43
+
44
+ # Parse the JSON info field
45
+ records = []
46
+ parse_errors = 0
47
+
48
+ for row in ds:
49
+ try:
50
+ info = json.loads(row['Info'])
51
+ person_key = row['PartitionKey']
52
+
53
+ # Extract birth year from key (format: Name+Year)
54
+ birth_year_match = re.search(r'(\d{4})$', person_key)
55
+ birth_year = int(birth_year_match.group(1)) if birth_year_match else None
56
+
57
+ marriages = info.get('marriages', [])
58
+ if not marriages:
59
+ continue
60
+
61
+ for m_idx, m in enumerate(marriages):
62
+ record = {
63
+ 'person': person_key,
64
+ 'birth_year': birth_year,
65
+ 'marriage_idx': m_idx,
66
+ 'marriage_type': m.get('type', ''),
67
+ 'spouse': m.get('spouse', ''),
68
+ 'marriage_date_raw': m.get('marriageDate', ''),
69
+ 'divorce_date_raw': m.get('divorceDate', ''),
70
+ 'outcome': m.get('outcome', ''),
71
+ 'data_credibility': m.get('dataCredibility', ''),
72
+ }
73
+ records.append(record)
74
+ except (json.JSONDecodeError, KeyError, TypeError) as e:
75
+ parse_errors += 1
76
+
77
+ df = pd.DataFrame(records)
78
+ print(f" Parsed marriage records: {len(df)}")
79
+ print(f" Parse errors: {parse_errors}")
80
+
81
+ # ============================================================
82
+ # 2. DATA AUDIT
83
+ # ============================================================
84
+ print("\n" + "=" * 70)
85
+ print("Step 2: Data Audit")
86
+ print("=" * 70)
87
+
88
+ print(f"\nOutcome distribution:")
89
+ print(df['outcome'].value_counts())
90
+
91
+ print(f"\nMarriage type distribution:")
92
+ print(df['marriage_type'].value_counts())
93
+
94
+ print(f"\nData credibility:")
95
+ print(df['data_credibility'].value_counts())
96
+
97
+ print(f"\nDivorce date values (sample):")
98
+ print(df['divorce_date_raw'].value_counts().head(20))
99
+
100
+ # ============================================================
101
+ # 3. PARSE DATES & COMPUTE DURATION
102
+ # ============================================================
103
+ print("\n" + "=" * 70)
104
+ print("Step 3: Parsing Dates & Computing Marriage Duration")
105
+ print("=" * 70)
106
+
107
+ def parse_date(date_str):
108
+ """Parse various date formats to year (float)."""
109
+ if not date_str or pd.isna(date_str):
110
+ return None
111
+ date_str = str(date_str).strip()
112
+
113
+ # Skip non-date values
114
+ skip_vals = ['Not Applicable', 'N/A', 'None', '', 'Unknown', 'not applicable',
115
+ 'Present', 'present', 'Current', 'current', 'Still Married',
116
+ 'still married', 'Ongoing']
117
+ if date_str in skip_vals:
118
+ return None
119
+
120
+ # Try various formats
121
+ # "1990" → year only
122
+ if re.match(r'^\d{4}$', date_str):
123
+ return int(date_str)
124
+
125
+ # "31/08/1921" or "08/31/1921" → DD/MM/YYYY or MM/DD/YYYY
126
+ match = re.match(r'^(\d{1,2})/(\d{1,2})/(\d{4})$', date_str)
127
+ if match:
128
+ return int(match.group(3))
129
+
130
+ # "August 1990" or "Aug 1990"
131
+ match = re.match(r'^[A-Za-z]+\s+(\d{4})$', date_str)
132
+ if match:
133
+ return int(match.group(1))
134
+
135
+ # "1990-01-01" ISO format
136
+ match = re.match(r'^(\d{4})-\d{2}-\d{2}', date_str)
137
+ if match:
138
+ return int(match.group(1))
139
+
140
+ # Just try to find a 4-digit year anywhere
141
+ match = re.search(r'(\d{4})', date_str)
142
+ if match:
143
+ year = int(match.group(1))
144
+ if 1800 <= year <= 2030:
145
+ return year
146
+
147
+ return None
148
+
149
+ df['marriage_year'] = df['marriage_date_raw'].apply(parse_date)
150
+ df['divorce_year'] = df['divorce_date_raw'].apply(parse_date)
151
+
152
+ # Determine if divorced
153
+ df['is_divorced'] = False
154
+ # Explicit divorce date
155
+ df.loc[df['divorce_year'].notna(), 'is_divorced'] = True
156
+ # Outcome-based
157
+ divorce_outcomes = ['Dissolution', 'dissolution', 'Tragedy']
158
+ df.loc[df['outcome'].isin(divorce_outcomes), 'is_divorced'] = True
159
+
160
+ # Compute duration
161
+ # For divorced: divorce_year - marriage_year
162
+ # For not divorced: use 2024 as censoring date (or death year if available)
163
+ CENSOR_YEAR = 2024
164
+
165
+ df['duration_years'] = np.nan
166
+ # Divorced with both dates
167
+ mask_divorced = df['is_divorced'] & df['marriage_year'].notna() & df['divorce_year'].notna()
168
+ df.loc[mask_divorced, 'duration_years'] = df.loc[mask_divorced, 'divorce_year'] - df.loc[mask_divorced, 'marriage_year']
169
+
170
+ # Not divorced (censored)
171
+ mask_censored = ~df['is_divorced'] & df['marriage_year'].notna()
172
+ df.loc[mask_censored, 'duration_years'] = CENSOR_YEAR - df.loc[mask_censored, 'marriage_year']
173
+
174
+ # Remove impossible durations
175
+ df.loc[df['duration_years'] < 0, 'duration_years'] = np.nan
176
+ df.loc[df['duration_years'] > 100, 'duration_years'] = np.nan
177
+
178
+ print(f"\nDate parsing results:")
179
+ print(f" Records with marriage year: {df['marriage_year'].notna().sum()}")
180
+ print(f" Records with divorce year: {df['divorce_year'].notna().sum()}")
181
+ print(f" Is divorced (total): {df['is_divorced'].sum()}")
182
+ print(f" Records with valid duration: {df['duration_years'].notna().sum()}")
183
+
184
+ # Filter to high-credibility records with valid data
185
+ df_valid = df[df['duration_years'].notna() & (df['duration_years'] >= 0)].copy()
186
+ print(f"\nValid records for analysis: {len(df_valid)}")
187
+
188
+ print(f"\nDuration statistics (years):")
189
+ print(df_valid['duration_years'].describe())
190
+
191
+ print(f"\nDuration by outcome:")
192
+ for outcome in df_valid['outcome'].unique():
193
+ subset = df_valid[df_valid['outcome'] == outcome]
194
+ if len(subset) > 10:
195
+ print(f" {outcome}: n={len(subset)}, mean={subset['duration_years'].mean():.1f}, "
196
+ f"median={subset['duration_years'].median():.1f}, std={subset['duration_years'].std():.1f}")
197
+
198
+ print(f"\nDuration by marriage type:")
199
+ for mtype in df_valid['marriage_type'].unique():
200
+ subset = df_valid[df_valid['marriage_type'] == mtype]
201
+ if len(subset) > 10:
202
+ print(f" {mtype}: n={len(subset)}, mean={subset['duration_years'].mean():.1f}, "
203
+ f"median={subset['duration_years'].median():.1f}, divorced={subset['is_divorced'].mean():.1%}")
204
+
205
+ # ============================================================
206
+ # 4. FEATURE ENGINEERING FOR SURVIVAL MODEL
207
+ # ============================================================
208
+ print("\n" + "=" * 70)
209
+ print("Step 4: Feature Engineering for Survival Model")
210
+ print("=" * 70)
211
+
212
+ # Marriage era
213
+ df_valid['marriage_era'] = pd.cut(
214
+ df_valid['marriage_year'],
215
+ bins=[0, 1900, 1950, 1970, 1990, 2000, 2010, 2030],
216
+ labels=['pre_1900', '1900_1950', '1950_1970', '1970_1990', '1990_2000', '2000_2010', '2010_plus']
217
+ )
218
+
219
+ # Marriage type encoding
220
+ df_valid['is_love_marriage'] = (df_valid['marriage_type'] == 'Love').astype(int)
221
+ df_valid['is_arranged_marriage'] = (df_valid['marriage_type'] == 'Arranged').astype(int)
222
+
223
+ # Age at marriage (if birth year available)
224
+ df_valid['age_at_marriage'] = np.nan
225
+ mask = df_valid['birth_year'].notna() & df_valid['marriage_year'].notna()
226
+ df_valid.loc[mask, 'age_at_marriage'] = df_valid.loc[mask, 'marriage_year'] - df_valid.loc[mask, 'birth_year']
227
+ # Filter out unreasonable ages
228
+ df_valid.loc[(df_valid['age_at_marriage'] < 14) | (df_valid['age_at_marriage'] > 80), 'age_at_marriage'] = np.nan
229
+
230
+ # Marriage number (first, second, etc.)
231
+ df_valid['marriage_number'] = df_valid['marriage_idx'] + 1
232
+ df_valid['is_first_marriage'] = (df_valid['marriage_idx'] == 0).astype(int)
233
+
234
+ # Outcome encoding
235
+ outcome_map = {
236
+ 'Happiness': 0, 'happiness': 0,
237
+ 'Dissolution': 1, 'dissolution': 1,
238
+ 'Struggle': 2, 'struggle': 2,
239
+ 'Tragedy': 3, 'tragedy': 3,
240
+ }
241
+ df_valid['outcome_code'] = df_valid['outcome'].map(outcome_map).fillna(-1).astype(int)
242
+
243
+ print(f"\nAge at marriage statistics:")
244
+ print(df_valid['age_at_marriage'].describe())
245
+
246
+ print(f"\nMarriage era distribution:")
247
+ print(df_valid['marriage_era'].value_counts())
248
+
249
+ print(f"\nFirst marriage vs subsequent:")
250
+ print(f" First: n={df_valid['is_first_marriage'].sum()}, "
251
+ f"divorce_rate={df_valid[df_valid['is_first_marriage']==1]['is_divorced'].mean():.1%}")
252
+ print(f" Subsequent: n={(~df_valid['is_first_marriage'].astype(bool)).sum()}, "
253
+ f"divorce_rate={df_valid[df_valid['is_first_marriage']==0]['is_divorced'].mean():.1%}")
254
+
255
+ # ============================================================
256
+ # 5. SURVIVAL ANALYSIS — KAPLAN-MEIER + COX PH
257
+ # ============================================================
258
+ print("\n" + "=" * 70)
259
+ print("Step 5: Survival Analysis")
260
+ print("=" * 70)
261
+
262
+ # Install lifelines for survival analysis
263
+ import subprocess
264
+ subprocess.run(['pip', 'install', 'lifelines', '-q'], capture_output=True)
265
+ from lifelines import KaplanMeierFitter, CoxPHFitter
266
+ from lifelines.statistics import logrank_test
267
+
268
+ # Prepare survival data
269
+ surv_df = df_valid[['duration_years', 'is_divorced', 'is_love_marriage', 'is_arranged_marriage',
270
+ 'age_at_marriage', 'marriage_number', 'is_first_marriage', 'marriage_year']].dropna(subset=['duration_years'])
271
+
272
+ # Convert is_divorced to int for lifelines
273
+ surv_df['event'] = surv_df['is_divorced'].astype(int)
274
+
275
+ print(f"\nSurvival dataset: {len(surv_df)} records")
276
+ print(f" Events (divorces): {surv_df['event'].sum()}")
277
+ print(f" Censored (ongoing): {(surv_df['event'] == 0).sum()}")
278
+
279
+ # --- Kaplan-Meier ---
280
+ kmf = KaplanMeierFitter()
281
+
282
+ # Overall survival
283
+ kmf.fit(surv_df['duration_years'], event_observed=surv_df['event'])
284
+ print(f"\nOverall Marriage Survival Estimates:")
285
+ for t in [5, 10, 15, 20, 25, 30, 40, 50]:
286
+ if t <= kmf.survival_function_.index.max():
287
+ surv = kmf.predict(t)
288
+ print(f" {t:3d} years: {surv:.1%} still married")
289
+
290
+ median_survival = kmf.median_survival_time_
291
+ print(f" Median survival: {median_survival:.1f} years")
292
+
293
+ # Plot overall KM curve
294
+ fig, ax = plt.subplots(figsize=(10, 7))
295
+ kmf.plot_survival_function(ax=ax, label='All Marriages', ci_show=True)
296
+ ax.set_xlabel('Years Since Marriage', fontsize=12)
297
+ ax.set_ylabel('Probability Still Married', fontsize=12)
298
+ ax.set_title('Marriage Survival Curve (Kaplan-Meier)\n15,000+ Famous People', fontsize=14)
299
+ ax.set_xlim(0, 60)
300
+ ax.grid(True, alpha=0.3)
301
+ plt.tight_layout()
302
+ plt.savefig(f"{OUTPUT_DIR}/figures/km_overall.png", dpi=150, bbox_inches='tight')
303
+ plt.close()
304
+
305
+ # --- KM by Marriage Type ---
306
+ fig, ax = plt.subplots(figsize=(10, 7))
307
+
308
+ for mtype, label, color in [('Love', 'Love Marriage', '#e74c3c'),
309
+ ('Arranged', 'Arranged Marriage', '#3498db')]:
310
+ mask = df_valid['marriage_type'] == mtype
311
+ subset = df_valid[mask & df_valid['duration_years'].notna()].copy()
312
+ if len(subset) > 50:
313
+ kmf_sub = KaplanMeierFitter()
314
+ kmf_sub.fit(subset['duration_years'], event_observed=subset['is_divorced'].astype(int))
315
+ kmf_sub.plot_survival_function(ax=ax, label=f'{label} (n={len(subset)})', ci_show=True, color=color)
316
+
317
+ ax.set_xlabel('Years Since Marriage', fontsize=12)
318
+ ax.set_ylabel('Probability Still Married', fontsize=12)
319
+ ax.set_title('Marriage Survival by Type: Love vs Arranged', fontsize=14)
320
+ ax.set_xlim(0, 60)
321
+ ax.legend(fontsize=11)
322
+ ax.grid(True, alpha=0.3)
323
+ plt.tight_layout()
324
+ plt.savefig(f"{OUTPUT_DIR}/figures/km_by_type.png", dpi=150, bbox_inches='tight')
325
+ plt.close()
326
+
327
+ # Log-rank test: Love vs Arranged
328
+ love_mask = df_valid['marriage_type'] == 'Love'
329
+ arranged_mask = df_valid['marriage_type'] == 'Arranged'
330
+ love_data = df_valid[love_mask & df_valid['duration_years'].notna()]
331
+ arranged_data = df_valid[arranged_mask & df_valid['duration_years'].notna()]
332
+
333
+ if len(love_data) > 50 and len(arranged_data) > 50:
334
+ lr_result = logrank_test(
335
+ love_data['duration_years'], arranged_data['duration_years'],
336
+ event_observed_A=love_data['is_divorced'].astype(int),
337
+ event_observed_B=arranged_data['is_divorced'].astype(int)
338
+ )
339
+ print(f"\nLog-rank test (Love vs Arranged):")
340
+ print(f" Test statistic: {lr_result.test_statistic:.4f}")
341
+ print(f" p-value: {lr_result.p_value:.6f}")
342
+ print(f" Significant: {'YES' if lr_result.p_value < 0.05 else 'NO'}")
343
+
344
+ # --- KM by Marriage Era ---
345
+ fig, ax = plt.subplots(figsize=(10, 7))
346
+ colors_era = plt.cm.viridis(np.linspace(0.2, 0.9, len(df_valid['marriage_era'].dropna().unique())))
347
+
348
+ for era, color in zip(sorted(df_valid['marriage_era'].dropna().unique()), colors_era):
349
+ subset = df_valid[(df_valid['marriage_era'] == era) & df_valid['duration_years'].notna()]
350
+ if len(subset) > 30:
351
+ kmf_era = KaplanMeierFitter()
352
+ kmf_era.fit(subset['duration_years'], event_observed=subset['is_divorced'].astype(int))
353
+ kmf_era.plot_survival_function(ax=ax, label=f'{era} (n={len(subset)})', ci_show=False, color=color)
354
+
355
+ ax.set_xlabel('Years Since Marriage', fontsize=12)
356
+ ax.set_ylabel('Probability Still Married', fontsize=12)
357
+ ax.set_title('Marriage Survival by Era', fontsize=14)
358
+ ax.set_xlim(0, 60)
359
+ ax.legend(fontsize=9)
360
+ ax.grid(True, alpha=0.3)
361
+ plt.tight_layout()
362
+ plt.savefig(f"{OUTPUT_DIR}/figures/km_by_era.png", dpi=150, bbox_inches='tight')
363
+ plt.close()
364
+
365
+ # --- KM by First vs Subsequent Marriage ---
366
+ fig, ax = plt.subplots(figsize=(10, 7))
367
+ for is_first, label, color in [(1, 'First Marriage', '#2ecc71'), (0, 'Subsequent Marriage', '#e67e22')]:
368
+ subset = df_valid[(df_valid['is_first_marriage'] == is_first) & df_valid['duration_years'].notna()]
369
+ if len(subset) > 50:
370
+ kmf_m = KaplanMeierFitter()
371
+ kmf_m.fit(subset['duration_years'], event_observed=subset['is_divorced'].astype(int))
372
+ kmf_m.plot_survival_function(ax=ax, label=f'{label} (n={len(subset)})', ci_show=True, color=color)
373
+
374
+ ax.set_xlabel('Years Since Marriage', fontsize=12)
375
+ ax.set_ylabel('Probability Still Married', fontsize=12)
376
+ ax.set_title('Marriage Survival: First vs Subsequent Marriage', fontsize=14)
377
+ ax.set_xlim(0, 60)
378
+ ax.legend(fontsize=11)
379
+ ax.grid(True, alpha=0.3)
380
+ plt.tight_layout()
381
+ plt.savefig(f"{OUTPUT_DIR}/figures/km_by_marriage_number.png", dpi=150, bbox_inches='tight')
382
+ plt.close()
383
+
384
+ # --- Cox Proportional Hazards ---
385
+ print("\n" + "-" * 50)
386
+ print("Cox Proportional Hazards Model")
387
+ print("-" * 50)
388
+
389
+ cox_df = surv_df.dropna(subset=['age_at_marriage']).copy()
390
+ cox_df = cox_df[['duration_years', 'event', 'is_love_marriage', 'age_at_marriage',
391
+ 'marriage_number', 'is_first_marriage']].dropna()
392
+
393
+ if len(cox_df) > 100:
394
+ cph = CoxPHFitter()
395
+ cph.fit(cox_df, duration_col='duration_years', event_col='event')
396
+
397
+ print("\nCox PH Model Summary:")
398
+ cph.print_summary()
399
+
400
+ # Extract hazard ratios
401
+ print("\nHazard Ratios (exp(coef)):")
402
+ for var in cph.summary.index:
403
+ hr = cph.summary.loc[var, 'exp(coef)']
404
+ p = cph.summary.loc[var, 'p']
405
+ sig = '***' if p < 0.001 else '**' if p < 0.01 else '*' if p < 0.05 else ''
406
+ print(f" {var:25s} HR={hr:.4f} p={p:.4f} {sig}")
407
+
408
+ # Save Cox model
409
+ cox_summary = cph.summary.to_dict()
410
+
411
+ # Plot hazard ratios
412
+ fig, ax = plt.subplots(figsize=(8, 5))
413
+ cph.plot(ax=ax)
414
+ ax.set_title('Cox PH — Hazard Ratios for Divorce', fontsize=14)
415
+ plt.tight_layout()
416
+ plt.savefig(f"{OUTPUT_DIR}/figures/cox_hazard_ratios.png", dpi=150, bbox_inches='tight')
417
+ plt.close()
418
+ else:
419
+ print(f" Insufficient data for Cox PH: {len(cox_df)} records")
420
+ cox_summary = {}
421
+
422
+ # ============================================================
423
+ # 6. DURATION DISTRIBUTION ANALYSIS
424
+ # ============================================================
425
+ print("\n" + "=" * 70)
426
+ print("Step 6: Duration Distribution Analysis")
427
+ print("=" * 70)
428
+
429
+ # Duration distribution for divorced couples only
430
+ divorced_durations = df_valid[df_valid['is_divorced']]['duration_years'].dropna()
431
+ print(f"\nDivorced couples duration statistics:")
432
+ print(f" Count: {len(divorced_durations)}")
433
+ print(f" Mean: {divorced_durations.mean():.1f} years")
434
+ print(f" Median: {divorced_durations.median():.1f} years")
435
+ print(f" Std: {divorced_durations.std():.1f} years")
436
+ print(f" Mode: {divorced_durations.mode().values[0]:.0f} years")
437
+
438
+ # Most dangerous periods
439
+ print(f"\nDivorce Timing (when do marriages end?):")
440
+ for period, label in [(range(0, 3), '0-2 years (honeymoon crisis)'),
441
+ (range(3, 8), '3-7 years (seven year itch)'),
442
+ (range(8, 15), '8-14 years (mid-life)'),
443
+ (range(15, 25), '15-24 years (empty nest)'),
444
+ (range(25, 100), '25+ years (late divorce)')]:
445
+ count = divorced_durations[divorced_durations.isin(period)].count()
446
+ pct = count / len(divorced_durations) * 100
447
+ print(f" {label}: {count} ({pct:.1f}%)")
448
+
449
+ # Plot divorce duration histogram
450
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6))
451
+
452
+ axes[0].hist(divorced_durations[divorced_durations <= 60], bins=60, color='#e74c3c', alpha=0.7, edgecolor='white')
453
+ axes[0].set_xlabel('Marriage Duration (years)', fontsize=12)
454
+ axes[0].set_ylabel('Count', fontsize=12)
455
+ axes[0].set_title('Distribution of Divorce Timing', fontsize=14)
456
+ axes[0].axvline(x=divorced_durations.median(), color='black', linestyle='--',
457
+ label=f'Median: {divorced_durations.median():.0f} years')
458
+ axes[0].axvline(x=7, color='#f39c12', linestyle='--', alpha=0.7, label='7-year itch')
459
+ axes[0].legend()
460
+
461
+ # Cumulative divorce risk
462
+ axes[1].hist(divorced_durations[divorced_durations <= 60], bins=60, color='#e74c3c',
463
+ alpha=0.7, cumulative=True, density=True, edgecolor='white')
464
+ axes[1].set_xlabel('Marriage Duration (years)', fontsize=12)
465
+ axes[1].set_ylabel('Cumulative Proportion of Divorces', fontsize=12)
466
+ axes[1].set_title('Cumulative Divorce Risk', fontsize=14)
467
+ axes[1].axhline(y=0.5, color='grey', linestyle='--', alpha=0.5, label='50% of divorces')
468
+ axes[1].legend()
469
+
470
+ plt.tight_layout()
471
+ plt.savefig(f"{OUTPUT_DIR}/figures/divorce_timing.png", dpi=150, bbox_inches='tight')
472
+ plt.close()
473
+
474
+ # ============================================================
475
+ # 7. BUILD LONGEVITY PRIOR TABLE
476
+ # ============================================================
477
+ print("\n" + "=" * 70)
478
+ print("Step 7: Building Longevity Prior Table")
479
+ print("=" * 70)
480
+
481
+ # Create base rate priors that can be used as features
482
+ priors = {}
483
+
484
+ # Overall prior
485
+ priors['overall'] = {
486
+ 'divorce_rate': float(df_valid['is_divorced'].mean()),
487
+ 'mean_duration_if_divorced': float(divorced_durations.mean()),
488
+ 'median_duration_if_divorced': float(divorced_durations.median()),
489
+ 'n': int(len(df_valid))
490
+ }
491
+
492
+ # By marriage type
493
+ for mtype in ['Love', 'Arranged']:
494
+ subset = df_valid[df_valid['marriage_type'] == mtype]
495
+ if len(subset) > 20:
496
+ divorced_sub = subset[subset['is_divorced']]['duration_years'].dropna()
497
+ priors[f'type_{mtype.lower()}'] = {
498
+ 'divorce_rate': float(subset['is_divorced'].mean()),
499
+ 'mean_duration_if_divorced': float(divorced_sub.mean()) if len(divorced_sub) > 0 else None,
500
+ 'median_duration_if_divorced': float(divorced_sub.median()) if len(divorced_sub) > 0 else None,
501
+ 'n': int(len(subset))
502
+ }
503
+
504
+ # By era
505
+ for era in df_valid['marriage_era'].dropna().unique():
506
+ subset = df_valid[df_valid['marriage_era'] == era]
507
+ if len(subset) > 20:
508
+ divorced_sub = subset[subset['is_divorced']]['duration_years'].dropna()
509
+ priors[f'era_{era}'] = {
510
+ 'divorce_rate': float(subset['is_divorced'].mean()),
511
+ 'mean_duration_if_divorced': float(divorced_sub.mean()) if len(divorced_sub) > 0 else None,
512
+ 'n': int(len(subset))
513
+ }
514
+
515
+ # By marriage number
516
+ for num in [1, 2, 3]:
517
+ subset = df_valid[df_valid['marriage_number'] == num]
518
+ if len(subset) > 20:
519
+ divorced_sub = subset[subset['is_divorced']]['duration_years'].dropna()
520
+ ordinal = {1: 'first', 2: 'second', 3: 'third'}[num]
521
+ priors[f'marriage_{ordinal}'] = {
522
+ 'divorce_rate': float(subset['is_divorced'].mean()),
523
+ 'mean_duration_if_divorced': float(divorced_sub.mean()) if len(divorced_sub) > 0 else None,
524
+ 'n': int(len(subset))
525
+ }
526
+
527
+ # By age at marriage (buckets)
528
+ for low, high, label in [(14, 22, 'young'), (22, 30, 'prime'), (30, 40, 'mature'), (40, 80, 'late')]:
529
+ subset = df_valid[(df_valid['age_at_marriage'] >= low) & (df_valid['age_at_marriage'] < high)]
530
+ if len(subset) > 20:
531
+ divorced_sub = subset[subset['is_divorced']]['duration_years'].dropna()
532
+ priors[f'age_at_marriage_{label}'] = {
533
+ 'divorce_rate': float(subset['is_divorced'].mean()),
534
+ 'mean_duration_if_divorced': float(divorced_sub.mean()) if len(divorced_sub) > 0 else None,
535
+ 'age_range': f'{low}-{high}',
536
+ 'n': int(len(subset))
537
+ }
538
+
539
+ print("\nLongevity Prior Table:")
540
+ for key, val in priors.items():
541
+ print(f" {key:35s} divorce_rate={val['divorce_rate']:.1%} n={val['n']}")
542
+
543
+ # Save priors
544
+ with open(f"{OUTPUT_DIR}/longevity_priors.json", "w") as f:
545
+ json.dump(priors, f, indent=2)
546
+
547
+ # ============================================================
548
+ # 8. CREATE SURVIVAL RISK SCORING FUNCTION
549
+ # ============================================================
550
+ print("\n" + "=" * 70)
551
+ print("Step 8: Creating Survival Risk Scoring Function")
552
+ print("=" * 70)
553
+
554
+ # Save the survival model components
555
+ survival_recipe = {
556
+ 'priors': priors,
557
+ 'km_overall_median_survival': float(median_survival) if not pd.isna(median_survival) else None,
558
+ 'cox_summary': {k: {kk: float(vv) if isinstance(vv, (np.floating, float)) else vv
559
+ for kk, vv in v.items()}
560
+ for k, v in cox_summary.items()} if cox_summary else {},
561
+ 'divorce_timing': {
562
+ 'honeymoon_crisis_0_2yr': float(divorced_durations[divorced_durations < 3].count() / len(divorced_durations)),
563
+ 'seven_year_itch_3_7yr': float(divorced_durations[(divorced_durations >= 3) & (divorced_durations < 8)].count() / len(divorced_durations)),
564
+ 'midlife_8_14yr': float(divorced_durations[(divorced_durations >= 8) & (divorced_durations < 15)].count() / len(divorced_durations)),
565
+ 'empty_nest_15_24yr': float(divorced_durations[(divorced_durations >= 15) & (divorced_durations < 25)].count() / len(divorced_durations)),
566
+ 'late_divorce_25yr_plus': float(divorced_durations[divorced_durations >= 25].count() / len(divorced_durations)),
567
+ },
568
+ 'key_findings': {
569
+ 'love_vs_arranged_divorce_rate': {
570
+ 'love': float(love_data['is_divorced'].mean()) if len(love_data) > 0 else None,
571
+ 'arranged': float(arranged_data['is_divorced'].mean()) if len(arranged_data) > 0 else None,
572
+ },
573
+ 'first_vs_subsequent_divorce_rate': {
574
+ 'first': float(df_valid[df_valid['is_first_marriage']==1]['is_divorced'].mean()),
575
+ 'subsequent': float(df_valid[df_valid['is_first_marriage']==0]['is_divorced'].mean()),
576
+ },
577
+ },
578
+ 'dataset_stats': {
579
+ 'total_records': int(len(df_valid)),
580
+ 'total_divorces': int(df_valid['is_divorced'].sum()),
581
+ 'total_people': int(df_valid['person'].nunique()),
582
+ }
583
+ }
584
+
585
+ with open(f"{OUTPUT_DIR}/survival_recipe.json", "w") as f:
586
+ json.dump(survival_recipe, f, indent=2, default=str)
587
+
588
+ # Save processed dataframe for integration
589
+ df_valid.to_csv(f"{OUTPUT_DIR}/processed_marriages.csv", index=False)
590
+
591
+ print("\nPhase 2 Complete!")
592
+ print(f" Output directory: {OUTPUT_DIR}")
593
+ print(f" Longevity priors: longevity_priors.json")
594
+ print(f" Survival recipe: survival_recipe.json")
595
+ print(f" Processed data: processed_marriages.csv")
596
+ print(f" Figures: {OUTPUT_DIR}/figures/")
597
+
598
+ # ============================================================
599
+ # FINAL SUMMARY
600
+ # ============================================================
601
+ print("\n" + "=" * 70)
602
+ print("PHASE 2 FINAL SUMMARY")
603
+ print("=" * 70)
604
+ print(f"""
605
+ Dataset: vedastro-org/15000-Famous-People-Marriage-Divorce-Info
606
+ - {len(df_valid)} valid marriage records
607
+ - {df_valid['person'].nunique()} unique people
608
+ - {df_valid['is_divorced'].sum()} divorces ({df_valid['is_divorced'].mean():.1%} divorce rate)
609
+
610
+ Key Findings:
611
+ 1. Median marriage survival: {median_survival:.0f}+ years
612
+ 2. Most divorces happen within the first {divorced_durations.median():.0f} years
613
+ 3. Love marriages: {love_data['is_divorced'].mean():.1%} divorce rate
614
+ 4. Arranged marriages: {arranged_data['is_divorced'].mean():.1%} divorce rate
615
+ 5. First marriages: {df_valid[df_valid['is_first_marriage']==1]['is_divorced'].mean():.1%} divorce rate
616
+ 6. Subsequent marriages: {df_valid[df_valid['is_first_marriage']==0]['is_divorced'].mean():.1%} divorce rate
617
+
618
+ Outputs:
619
+ - Kaplan-Meier survival curves (overall, by type, by era, by marriage #)
620
+ - Cox PH model (hazard ratios for each factor)
621
+ - Longevity prior table (base rates by type/era/age/marriage#)
622
+ - Full survival recipe for integration
623
+ """)