# Install mlxtend if not present (Colab pre-installs this, but running this ensures compatibility)
!pip install -q mlxtend

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules

# Configure visual aesthetics
sns.set_theme(style="whitegrid")
%matplotlib inline

# Sample transactional dataset (10 retail baskets)
transactions = [
    ['Milk', 'Bread', 'Butter'],
    ['Bread', 'Butter'],
    ['Milk', 'Bread'],
    ['Milk', 'Bread', 'Butter', 'Eggs'],
    ['Bread', 'Eggs'],
    ['Milk', 'Bread', 'Eggs'],
    ['Milk', 'Butter'],
    ['Bread', 'Butter', 'Eggs'],
    ['Milk', 'Bread', 'Butter'],
    ['Bread', 'Milk']
]

# Display the transactional dataset in a readable tabular format
trans_df = pd.DataFrame({
    'Transaction_ID': [f'T{i+1}' for i in range(len(transactions))],
    'Items_Purchased': [", ".join(t) for t in transactions]
})
display(trans_df)

# Initialize and fit TransactionEncoder
te = TransactionEncoder()
te_ary = te.fit(transactions).transform(transactions)

# Create the Boolean transaction DataFrame
df = pd.DataFrame(te_ary, columns=te.columns_)
print("--- Boolean Transaction Matrix ---")
display(df)

# Create and display the Binary Numerical representation (0 and 1)
df_numeric = df.astype(int)
print("\n--- Binary Numerical Transaction Matrix ---")
display(df_numeric)

min_support = 0.30

# Compute frequent itemsets using mlxtend
frequent_itemsets = apriori(
    df,
    min_support=min_support,
    use_colnames=True
)

# Add itemset size (length) column for deeper analysis
frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x))

# Sort by itemset size and then support values in descending order
frequent_itemsets = frequent_itemsets.sort_values(by=['length', 'support'], ascending=[True, False]).reset_index(drop=True)

print(f"Frequent Itemsets generated with min_support={min_support}:")
display(frequent_itemsets)

min_confidence = 0.60

try:
    # Generate association rules
    rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=min_confidence)

    # Format frozen sets into strings for display readability
    rules['antecedents_str'] = rules['antecedents'].apply(lambda x: ', '.join(list(x)))
    rules['consequents_str'] = rules['consequents'].apply(lambda x: ', '.join(list(x)))

    # Select core columns requested
    rules_display = rules[['antecedents_str', 'consequents_str', 'support', 'confidence', 'lift']].copy()
    rules_display.rename(columns={'antecedents_str': 'Antecedents', 'consequents_str': 'Consequents'}, inplace=True)

    # Sort by lift and confidence descending
    rules_display = rules_display.sort_values(by=['lift', 'confidence'], ascending=False).reset_index(drop=True)

    print(f"Association Rules generated with min_confidence={min_confidence}:")
    display(rules_display)
except Exception as e:
    print("An error occurred during rule generation:", str(e))

# Filter for strong rules
strong_rules = rules_display[(rules_display['confidence'] >= 0.60) & (rules_display['lift'] > 1.0)].reset_index(drop=True)

if not strong_rules.empty:
    print("--- Strong Association Rules (Confidence >= 0.60 & Lift > 1.0) ---")
    display(strong_rules)
else:
    print("No association rules satisfied the minimum thresholds (Confidence >= 0.60 and Lift > 1.0) simultaneously.")

# 1. Bar Chart of Frequent Itemsets
plt.figure(figsize=(10, 5))
sorted_itemsets_for_plot = frequent_itemsets.sort_values(by='support', ascending=False)
sns.barplot(
    x=sorted_itemsets_for_plot['support'],
    y=sorted_itemsets_for_plot['itemsets'].apply(lambda x: ', '.join(list(x))),
    hue=sorted_itemsets_for_plot['length'],
    palette="viridis",
    legend=True
)
plt.title('Frequent Itemsets and their Support Values', fontsize=14, fontweight='bold')
plt.xlabel('Support', fontsize=12)
plt.ylabel('Itemsets', fontsize=12)
plt.tight_layout()
plt.show()

# 2. Scatter Plot of Support vs. Confidence vs. Lift
if not rules_display.empty:
    plt.figure(figsize=(8, 6))
    scatter = plt.scatter(
        rules_display['support'],
        rules_display['confidence'],
        c=rules_display['lift'],
        cmap='plasma',
        s=200,
        edgecolors='black',
        alpha=0.85
    )
    plt.colorbar(scatter, label='Lift')
    plt.title('Scatter Plot: Support vs. Confidence (Colored by Lift)', fontsize=14, fontweight='bold')
    plt.xlabel('Support', fontsize=12)
    plt.ylabel('Confidence', fontsize=12)
    plt.tight_layout()
    plt.show()
else:
    print("No rules available to generate Support vs. Confidence scatter plot.")

# 3. Bar Chart of the Strongest Association Rules Ranked by Lift
if not strong_rules.empty:
    plt.figure(figsize=(10, 5))
    # Create labels for rules: e.g., 'A -> B'
    strong_rules['rule_label'] = strong_rules['Antecedents'] + ' -> ' + strong_rules['Consequents']

    sns.barplot(
        x='lift',
        y='rule_label',
        data=strong_rules.sort_values(by='lift', ascending=False),
        palette='magma',
        hue='rule_label',
        legend=False
    )
    plt.title('Strongest Association Rules Ranked by Lift', fontsize=14, fontweight='bold')
    plt.xlabel('Lift', fontsize=12)
    plt.ylabel('Rules', fontsize=12)
    plt.axvline(x=1.0, color='red', linestyle='--', label='Independence (Lift = 1)')
    plt.legend()
    plt.tight_layout()
    plt.show()
else:
    print("No strong rules available (Lift > 1) to generate ranking plot.")
