================================================================================
DWM PRACTICAL EXAMINATION: ALL EXPERIMENTS IN ONE SINGLE MASTER TEXT FILE
Easy, short, tested codes for quick reference, copy-paste, and exam revision.
================================================================================


================================================================================
EXPERIMENT 1 & 3: SQL ESSENTIALS, JOINS, SUBQUERIES & WINDOW FUNCTIONS
Database Engine: PostgreSQL / Standard ANSI SQL
================================================================================

--------------------------------------------------------------------------------
PART A: BASIC SQL (DDL, DML, AGGREGATES, VIEWS, INDEXES)
--------------------------------------------------------------------------------
-- 1. Table Creation with Constraints
CREATE TABLE departments (
    dept_id SERIAL PRIMARY KEY,
    dept_name VARCHAR(50) NOT NULL UNIQUE,
    location VARCHAR(50) DEFAULT 'Headquarters'
);

CREATE TABLE employees (
    emp_id SERIAL PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE,
    gender CHAR(1) CHECK (gender IN ('M', 'F', 'O')),
    salary NUMERIC(10, 2) CHECK (salary > 0),
    hire_date DATE DEFAULT CURRENT_DATE,
    dept_id INT REFERENCES departments(dept_id)
);

-- 2. Insert Records
INSERT INTO departments VALUES (1, 'Engineering', 'Building A'), (2, 'HR', 'Building B'), (3, 'Sales', 'Building C');
INSERT INTO employees VALUES
(101, 'Aarav', 'Sharma', 'aarav@company.com', 'M', 75000, '2021-03-15', 1),
(102, 'Priya', 'Patel', 'priya@company.com', 'F', 82000, '2020-07-01', 1),
(103, 'Rohan', 'Verma', 'rohan@company.com', 'M', 52000, '2022-01-10', 2),
(104, 'Ananya', 'Iyer', 'ananya@company.com', 'F', 68000, '2021-11-20', 3);

-- 3. Filtering & Aggregates
SELECT dept_id, COUNT(*) AS emp_count, ROUND(AVG(salary), 2) AS avg_sal
FROM employees
GROUP BY dept_id
HAVING AVG(salary) > 60000;

-- 4. Case When & View Creation
CREATE VIEW high_earners AS
SELECT first_name, salary,
       CASE WHEN salary >= 75000 THEN 'High' ELSE 'Mid' END AS tier
FROM employees;

--------------------------------------------------------------------------------
PART B: ALL 6 SQL JOINS (INNER, LEFT, RIGHT, FULL, CROSS, SELF)
--------------------------------------------------------------------------------
-- 1. INNER JOIN (Matching records only)
SELECT e.first_name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;

-- 2. LEFT JOIN (All employees, even if dept_id is NULL)
SELECT e.first_name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;

-- 3. RIGHT JOIN (All departments, even if no employees assigned)
SELECT d.dept_name, e.first_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;

-- 4. FULL OUTER JOIN (All records from both tables)
SELECT e.first_name, d.dept_name
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.dept_id;

-- 5. CROSS JOIN (Cartesian product: M x N rows)
SELECT e.first_name, d.dept_name FROM employees e CROSS JOIN departments d;

-- 6. SELF JOIN (Hierarchical: Employee and Manager)
-- Assuming manager_id in employees table:
SELECT e.first_name AS Employee, m.first_name AS Manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id;

--------------------------------------------------------------------------------
PART C: SUBQUERIES & COMMON TABLE EXPRESSIONS (CTE)
--------------------------------------------------------------------------------
-- 1. Subquery in WHERE (Higher than class average)
SELECT first_name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

-- 2. Correlated Subquery
SELECT e.first_name, e.salary, e.dept_id
FROM employees e
WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);

-- 3. CTE (WITH Clause)
WITH DeptStats AS (
    SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id
)
SELECT e.first_name, e.salary, d.avg_sal
FROM employees e
JOIN DeptStats d ON e.dept_id = d.dept_id;

--------------------------------------------------------------------------------
PART D: ALL WINDOW FUNCTIONS (OVER, PARTITION BY, ORDER BY)
--------------------------------------------------------------------------------
-- 1. ROW_NUMBER(), RANK(), DENSE_RANK() (Notice tie handling)
SELECT first_name, dept_id, salary,
       ROW_NUMBER() OVER(PARTITION BY dept_id ORDER BY salary DESC) AS row_num,
       RANK()       OVER(PARTITION BY dept_id ORDER BY salary DESC) AS rank_num,
       DENSE_RANK() OVER(PARTITION BY dept_id ORDER BY salary DESC) AS dense_rank_num
FROM employees;

-- 2. LAG() and LEAD() (Navigation between rows)
SELECT first_name, salary,
       LAG(salary, 1, 0) OVER(ORDER BY hire_date) AS prev_hired_salary,
       LEAD(salary, 1, 0) OVER(ORDER BY hire_date) AS next_hired_salary
FROM employees;

-- 3. Running Total using SUM() OVER()
SELECT first_name, hire_date, salary,
       SUM(salary) OVER(ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_payroll
FROM employees;

-- 4. FIRST_VALUE() & LAST_VALUE() with correct frame
SELECT first_name, dept_id, salary,
       FIRST_VALUE(salary) OVER(PARTITION BY dept_id ORDER BY salary DESC
           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS highest_dept_salary,
       LAST_VALUE(salary) OVER(PARTITION BY dept_id ORDER BY salary DESC
           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lowest_dept_salary
FROM employees;

-- 5. NTILE(4) (Quartiles)
SELECT first_name, salary, NTILE(4) OVER(ORDER BY salary DESC) AS quartile
FROM employees;


================================================================================
EXPERIMENT 2: STAR SCHEMA (FOOD DELIVERY DATA WAREHOUSE) & 15 ANALYTICAL QUERIES
================================================================================

--------------------------------------------------------------------------------
1. SEVEN DIMENSION TABLES DDL
--------------------------------------------------------------------------------
CREATE TABLE Customer_Dim (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(100),
    email VARCHAR(100),
    phone VARCHAR(15),
    membership_tier VARCHAR(20)
);

CREATE TABLE Restaurant_Dim (
    restaurant_id INT PRIMARY KEY,
    restaurant_name VARCHAR(100),
    cuisine_type VARCHAR(50),
    restaurant_rating NUMERIC(2, 1)
);

CREATE TABLE Delivery_Partner_Dim (
    partner_id INT PRIMARY KEY,
    partner_name VARCHAR(100),
    vehicle_type VARCHAR(30)
);

CREATE TABLE Time_Dim (
    time_id INT PRIMARY KEY,
    full_date DATE,
    day INT,
    month INT,
    month_name VARCHAR(15),
    quarter CHAR(2),
    year INT
);

CREATE TABLE Discount_Dim (
    discount_id INT PRIMARY KEY,
    promo_code VARCHAR(30),
    discount_percentage NUMERIC(5, 2)
);

CREATE TABLE Payment_Method_Dim (
    payment_id INT PRIMARY KEY,
    payment_type VARCHAR(50),
    is_digital BOOLEAN
);

CREATE TABLE Location_Dim (
    location_id INT PRIMARY KEY,
    city VARCHAR(50),
    state VARCHAR(50)
);

--------------------------------------------------------------------------------
2. CENTRAL FACT TABLE DDL
--------------------------------------------------------------------------------
CREATE TABLE Fact_Order (
    fact_order_id BIGSERIAL PRIMARY KEY,
    order_id VARCHAR(30) UNIQUE,
    customer_id INT REFERENCES Customer_Dim(customer_id),
    restaurant_id INT REFERENCES Restaurant_Dim(restaurant_id),
    partner_id INT REFERENCES Delivery_Partner_Dim(partner_id),
    time_id INT REFERENCES Time_Dim(time_id),
    discount_id INT REFERENCES Discount_Dim(discount_id),
    payment_id INT REFERENCES Payment_Method_Dim(payment_id),
    location_id INT REFERENCES Location_Dim(location_id),
    order_amount NUMERIC(10, 2),
    discount_amount NUMERIC(10, 2),
    net_payable NUMERIC(10, 2),
    customer_rating INT
);

--------------------------------------------------------------------------------
3. ALL 15 ANALYTICAL SQL QUERIES
--------------------------------------------------------------------------------
-- Query 1: Total Order Amount by Restaurant and Year
SELECT r.restaurant_name, t.year, SUM(f.order_amount) AS total_amount
FROM Fact_Order f
JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id
JOIN Time_Dim t ON f.time_id = t.time_id
GROUP BY r.restaurant_name, t.year;

-- Query 2: Average Order Amount per Customer
SELECT c.customer_name, ROUND(AVG(f.order_amount), 2) AS avg_amount
FROM Fact_Order f JOIN Customer_Dim c ON f.customer_id = c.customer_id
GROUP BY c.customer_name;

-- Query 3: Order Trend with Previous Value using LAG()
SELECT f.order_id, c.customer_name, f.order_amount,
       LAG(f.order_amount, 1, 0.0) OVER(PARTITION BY c.customer_id ORDER BY t.full_date) AS prev_amount
FROM Fact_Order f
JOIN Customer_Dim c ON f.customer_id = c.customer_id
JOIN Time_Dim t ON f.time_id = t.time_id;

-- Query 4: Restaurants with Total Order Amount Greater Than Rs. 500
SELECT r.restaurant_name, SUM(f.order_amount) AS total_sales
FROM Fact_Order f JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id
GROUP BY r.restaurant_name HAVING SUM(f.order_amount) > 500;

-- Query 5: Running Total of Order Amount by Year
SELECT f.order_id, t.year, f.order_amount,
       SUM(f.order_amount) OVER(PARTITION BY t.year ORDER BY t.full_date
           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS yearly_running_total
FROM Fact_Order f JOIN Time_Dim t ON f.time_id = t.time_id;

-- Query 6: Top Restaurants by Revenue using RANK()
WITH Sales AS (
    SELECT r.restaurant_name, SUM(f.order_amount) AS rev
    FROM Fact_Order f JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id GROUP BY r.restaurant_name
)
SELECT restaurant_name, rev, RANK() OVER(ORDER BY rev DESC) AS rank_pos FROM Sales;

-- Query 7: First Restaurant Ordered by Each Customer using FIRST_VALUE()
SELECT DISTINCT c.customer_name,
       FIRST_VALUE(r.restaurant_name) OVER(PARTITION BY c.customer_id ORDER BY t.full_date
           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS first_restaurant
FROM Fact_Order f
JOIN Customer_Dim c ON f.customer_id = c.customer_id
JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id
JOIN Time_Dim t ON f.time_id = t.time_id;

-- Query 8: Maximum Customer Rating by Restaurant
SELECT r.restaurant_name, MAX(f.customer_rating) AS max_rating
FROM Fact_Order f JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id
GROUP BY r.restaurant_name;

-- Query 9: Top Tier Restaurants by Revenue using NTILE()
WITH Rev AS (
    SELECT r.restaurant_name, SUM(f.order_amount) AS total
    FROM Fact_Order f JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id GROUP BY r.restaurant_name
)
SELECT restaurant_name, total, NTILE(2) OVER(ORDER BY total DESC) AS tier FROM Rev;

-- Query 10: Compare Monthly Orders with Next Month using LEAD()
WITH Monthly AS (
    SELECT t.year, t.month_name, COUNT(*) AS orders
    FROM Fact_Order f JOIN Time_Dim t ON f.time_id = t.time_id GROUP BY t.year, t.month, t.month_name
)
SELECT year, month_name, orders, LEAD(orders, 1, 0) OVER(ORDER BY year) AS next_month_orders FROM Monthly;

-- Query 11: Total Orders by Restaurant and State
SELECT r.restaurant_name, l.state, COUNT(f.order_id) AS total_orders
FROM Fact_Order f
JOIN Restaurant_Dim r ON f.restaurant_id = r.restaurant_id
JOIN Location_Dim l ON f.location_id = l.location_id
GROUP BY r.restaurant_name, l.state;

-- Query 12: Monthly Order Amount by City
SELECT l.city, t.month_name, SUM(f.order_amount) AS city_rev
FROM Fact_Order f
JOIN Location_Dim l ON f.location_id = l.location_id
JOIN Time_Dim t ON f.time_id = t.time_id
GROUP BY l.city, t.year, t.month, t.month_name;

-- Query 13: Last Order Amount per Customer using LAST_VALUE()
SELECT DISTINCT c.customer_name,
       LAST_VALUE(f.order_amount) OVER(PARTITION BY c.customer_id ORDER BY t.full_date
           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_order_amt
FROM Fact_Order f
JOIN Customer_Dim c ON f.customer_id = c.customer_id
JOIN Time_Dim t ON f.time_id = t.time_id;

-- Query 14: High Value Orders (greater than Rs. 500)
SELECT f.order_id, c.customer_name, f.order_amount
FROM Fact_Order f JOIN Customer_Dim c ON f.customer_id = c.customer_id
WHERE f.order_amount > 500;

-- Query 15: Compare Daily Orders Using LAG()
WITH Daily AS (
    SELECT t.full_date, SUM(f.order_amount) AS day_rev
    FROM Fact_Order f JOIN Time_Dim t ON f.time_id = t.time_id GROUP BY t.full_date
)
SELECT full_date, day_rev, LAG(day_rev, 1, 0.0) OVER(ORDER BY full_date) AS prev_day_rev FROM Daily;


================================================================================
EXPERIMENT 3: OLAP OPERATIONS (PYTHON PANDAS & SQL)
Operations: Roll-up, Drill-down, Slice, Dice, Pivot
================================================================================

--------------------------------------------------------------------------------
1. PYTHON PANDAS CODE (40 Lines)
--------------------------------------------------------------------------------
import os
import pandas as pd

# ===== USER SETTINGS =====
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "sales_olap.csv")
DIMENSIONS = ["Region", "City"]   # [Coarse, Finer]
MEASURE = "Sales"                 # Column to aggregate
SLICE_COL, SLICE_VAL = "Year", 2024
DICE_FILTERS = {"Region": ["North", "West"], "Product_Category": ["Electronics", "Home"]}
PIVOT_ROWS, PIVOT_COLS = "Region", "Product_Category"

# 1. Load dataset
df = pd.read_csv(FILE_PATH)
print(f"Loaded {df.shape[0]} rows. Columns: {list(df.columns)}")

# 2. Roll-up: Summarize up hierarchy (City -> Region)
rollup = df.groupby(DIMENSIONS[0])[MEASURE].sum().reset_index()
print("\n--- 1. ROLL-UP (Summarize by Coarser Dimension: Region) ---")
print(rollup)

# 3. Drill-down: Expand hierarchy to finer detail (Region -> City)
drilldown = df.groupby(DIMENSIONS)[MEASURE].sum().reset_index()
print("\n--- 2. DRILL-DOWN (Detailed View: Region + City) ---")
print(drilldown.head(6))

# 4. Slice: 1-Dimensional Filter
slice_df = df[df[SLICE_COL] == SLICE_VAL].groupby(DIMENSIONS[0])[MEASURE].sum().reset_index()
print(f"\n--- 3. SLICE ({SLICE_COL} == {SLICE_VAL}) ---")
print(slice_df)

# 5. Dice: Multi-Dimensional Filter (Sub-cube)
dice_mask = pd.Series(True, index=df.index)
for col, vals in DICE_FILTERS.items():
    dice_mask &= df[col].isin(vals)
dice_df = df[dice_mask].groupby(list(DICE_FILTERS.keys()))[MEASURE].sum().reset_index()
print("\n--- 4. DICE (Sub-cube Multi-Filter) ---")
print(dice_df)

# 6. Pivot: Rotate dimensions (Cross-tabulation)
pivot_df = df.pivot_table(index=PIVOT_ROWS, columns=PIVOT_COLS, values=MEASURE, aggfunc="sum", margins=True)
print("\n--- 5. PIVOT TABLE (Cross-Tabulation with Margins) ---")
print(pivot_df)

--------------------------------------------------------------------------------
2. SQL OLAP EQUIVALENTS (ROLLUP, CUBE, GROUPING SETS)
--------------------------------------------------------------------------------
-- Rollup in SQL:
SELECT region, city, SUM(sales) FROM sales GROUP BY ROLLUP(region, city);

-- Cube in SQL (All 2^N combinations):
SELECT region, category, SUM(sales) FROM sales GROUP BY CUBE(region, category);

-- Pivot in SQL using CASE WHEN:
SELECT region,
       SUM(CASE WHEN category = 'Electronics' THEN sales ELSE 0 END) AS Electronics,
       SUM(CASE WHEN category = 'Clothing'    THEN sales ELSE 0 END) AS Clothing
FROM sales GROUP BY region;


================================================================================
EXPERIMENT 4: DATA EXPLORATION, CLEANING, PREPROCESSING & VISUALISATION
================================================================================

--------------------------------------------------------------------------------
1. DATA EXPLORATION CODE (data_exploration.py)
--------------------------------------------------------------------------------
import os, pandas as pd
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH)

print("Shape:", df.shape)
print("Data Types:\n", df.dtypes)
print("Describe:\n", df.describe().round(2))
print("Missing Values:\n", df.isnull().sum()[df.isnull().sum() > 0])
print("Duplicates Count:", df.duplicated().sum())
print("Value Counts:\n", df["Contract_Type"].value_counts())

--------------------------------------------------------------------------------
2. DATA CLEANING CODE (data_cleaning.py)
--------------------------------------------------------------------------------
import os, pandas as pd, numpy as np
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH)

# Drop duplicates
df = df.drop_duplicates()

# Impute missing values (Numerical: Median, Categorical: Mode)
num_cols = list(df.select_dtypes(include=[np.number]).columns)
cat_cols = [c for c in df.columns if c not in num_cols]
for col in num_cols: df[col] = df[col].fillna(df[col].median())
for col in cat_cols: df[col] = df[col].fillna(df[col].mode()[0])

# IQR Outlier Capping
for col in num_cols:
    if "id" in col.lower(): continue
    q1, q3 = df[col].quantile(0.25), df[col].quantile(0.75)
    iqr = q3 - q1
    df[col] = np.clip(df[col], q1 - 1.5 * iqr, q3 + 1.5 * iqr)

df = df.rename(columns={"Tenure_Months": "Tenure", "Monthly_Charges": "Monthly_Fee"})
print("Cleaned Shape:", df.shape)

--------------------------------------------------------------------------------
3. PREPROCESSING & DISCRETIZATION (preprocessing.py)
--------------------------------------------------------------------------------
import os, pandas as pd, numpy as np
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH).drop_duplicates().fillna(0)

# Discretization (Equal-width binning)
df["Age_Bin"] = pd.cut(df["Age"], bins=3, labels=["Young", "Middle", "Senior"])

# Label Encoding & One-Hot Encoding
df["Contract_Code"] = pd.factorize(df["Contract_Type"])[0]
df_ohe = pd.get_dummies(df, columns=["Contract_Type"], drop_first=True, dtype=int)

# Normalization & Standardization
num_col = "Age"
norm = (df[num_col] - df[num_col].min()) / (df[num_col].max() - df[num_col].min())
std = (df[num_col] - df[num_col].mean()) / df[num_col].std()

# Train-Test Split (80% Train, 20% Test)
shuffled = df.sample(frac=1, random_state=42)
split = int(0.8 * len(df))
train_df, test_df = shuffled.iloc[:split], shuffled.iloc[split:]
print(f"Train: {len(train_df)} | Test: {len(test_df)}")

--------------------------------------------------------------------------------
4. DATA VISUALISATION (data_visualisation.py)
--------------------------------------------------------------------------------
import os, matplotlib, matplotlib.pyplot as plt, seaborn as sns, pandas as pd, numpy as np
matplotlib.use('Agg')
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH).dropna()
num_cols = list(df.select_dtypes(include=[np.number]).columns)

plt.figure(); sns.histplot(df[num_cols[0]], kde=True); plt.savefig("01_hist.png"); plt.close()
plt.figure(); sns.countplot(data=df, x="Contract_Type"); plt.savefig("02_count.png"); plt.close()
plt.figure(); sns.boxplot(data=df, x="Contract_Type", y=num_cols[0]); plt.savefig("03_box.png"); plt.close()
plt.figure(); sns.scatterplot(data=df, x=num_cols[0], y=num_cols[1]); plt.savefig("04_scatter.png"); plt.close()
plt.figure(); sns.heatmap(df[num_cols].corr(), annot=True); plt.savefig("05_heatmap.png"); plt.close()
g = sns.pairplot(df[num_cols[:3]], corner=True); g.savefig("06_pair.png"); plt.close('all')
print("Visualisations generated.")


================================================================================
EXPERIMENT 5: APRIORI ALGORITHM (FREQUENT PATTERNS ONLY)
No ML libraries - Pure Python Loops - Supports Text List and One-Hot Formats
================================================================================

import os
from itertools import combinations
import numpy as np
import pandas as pd

# ===== USER SETTINGS =====
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "transactions_list.csv")
MIN_SUPPORT = 0.3      # Minimum support ratio (e.g. 0.3 = 30%)
GENERATE_RULES = False  # Set to False for 'Frequent Patterns Only', True for 'Association Rules'
MIN_CONFIDENCE = 0.5   # Minimum confidence threshold (only used if GENERATE_RULES=True)

# 1. Load transactions into list of sets (Supports Delimited text and One-Hot)
df = pd.read_csv(FILE_PATH)
non_id = [c for c in df.columns if "id" not in c.lower()]

if len(non_id) >= 2 and df[non_id].isin([0, 1]).all().all():
    # One-Hot Matrix format
    transactions = [frozenset(c for c in non_id if row[c] == 1) for _, row in df.iterrows()]
else:
    # Delimited text format
    col = non_id[0]
    delim = ';' if ';' in str(df[col].iloc[0]) else ','
    transactions = [frozenset(x.strip() for x in str(r).split(delim) if x.strip()) for r in df[col].dropna()]

n = len(transactions)
min_count = int(np.ceil(MIN_SUPPORT * n)) if 0.0 < MIN_SUPPORT <= 1.0 else int(MIN_SUPPORT)
print(f"Loaded {n} transactions from {os.path.basename(FILE_PATH)}")
print(f"Min Support Threshold = {min_count} transactions ({min_count/n:.1%})\n")

def support(itemset):
    return sum(1 for t in transactions if itemset.issubset(t))

# 2. Generate L1 (Frequent 1-itemsets)
items = sorted(list({item for t in transactions for item in t}))
c1 = [frozenset([i]) for i in items]
l_curr = {c: support(c) for c in c1 if support(c) >= min_count}

all_frequent = dict(l_curr)
k = 1

# 3. Iterative Ck and Lk generation
while l_curr:
    print(f"--- Frequent {k}-Itemsets (L{k}) ---")
    for itemset, cnt in sorted(l_curr.items(), key=lambda x: sorted(list(x[0]))):
        print(f"{{{', '.join(sorted(itemset))}}} -> Support: {cnt}/{n} ({cnt/n:.1%})")
        
    lk_list = list(l_curr.keys())
    ck = {lk_list[i] | lk_list[j] for i in range(len(lk_list)) for j in range(i + 1, len(lk_list)) if len(lk_list[i] | lk_list[j]) == k + 1}
    l_next = {c: support(c) for c in ck if support(c) >= min_count}
    
    all_frequent.update(l_next)
    l_curr = l_next
    k += 1

print(f"\nTotal Frequent Patterns: {len(all_frequent)}")

# 4. Association Rules (Optional - Enabled if GENERATE_RULES = True)
if GENERATE_RULES:
    print(f"\n--- ASSOCIATION RULES (Min Confidence >= {MIN_CONFIDENCE:.1%}) ---")
    rule_count = 0
    for itemset in all_frequent:
        if len(itemset) >= 2:
            for r in range(1, len(itemset)):
                for left in combinations(sorted(itemset), r):
                    A = frozenset(left)
                    B = itemset - A
                    conf = support(itemset) / support(A)
                    if conf >= MIN_CONFIDENCE:
                        rule_count += 1
                        print(f"{{{', '.join(sorted(A))}}} -> {{{', '.join(sorted(B))}}} | Confidence = {conf:.2%}")
    print(f"Total Association Rules Generated: {rule_count}")
else:
    print("Association rules skipped (GENERATE_RULES = False as per class instruction).")


================================================================================
EXPERIMENT 6: K-MEANS & K-MEDOIDS CLUSTERING (FROM SCRATCH)
No ML libraries - Pure Python & NumPy Loops Only
================================================================================

--------------------------------------------------------------------------------
1. K-MEANS CLUSTERING FROM SCRATCH (40 Lines)
--------------------------------------------------------------------------------
import os, pandas as pd, numpy as np

FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "mall_customers.csv")
K = 3
MAX_ITER = 100

# 1. Load data
df = pd.read_csv(FILE_PATH)
num_cols = [c for c in df.select_dtypes(include=[np.number]).columns if "id" not in c.lower()]
X = df[num_cols].fillna(df[num_cols].median()).values.astype(float)

# 2. Fit K-Means
np.random.seed(42)
centroids = X[np.random.choice(len(X), size=K, replace=False)].copy()

for it in range(MAX_ITER):
    # Assignment: Find nearest centroid for each point using Euclidean distance
    labels = np.array([np.argmin([np.linalg.norm(x - c) for c in centroids]) for x in X])
    # Update: Recompute centroids as the mean of assigned points
    new_centroids = np.array([X[labels == i].mean(axis=0) if sum(labels == i) > 0 else centroids[i] for i in range(K)])
    if np.allclose(centroids, new_centroids, atol=1e-4):
        break
    centroids = new_centroids

wcss = sum(np.sum((X[labels == i] - centroids[i]) ** 2) for i in range(K))
print("Final Centroids:\n", centroids)
print(f"Final WCSS (Inertia): {wcss:.2f}")

--------------------------------------------------------------------------------
2. K-MEDOIDS CLUSTERING FROM SCRATCH (PAM) (45 Lines)
--------------------------------------------------------------------------------
import os, pandas as pd, numpy as np

FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "mall_customers.csv")
K = 3

df = pd.read_csv(FILE_PATH)
num_cols = [c for c in df.select_dtypes(include=[np.number]).columns if "id" not in c.lower()]
X = df[num_cols].fillna(df[num_cols].median()).values.astype(float)

def compute_cost(X, medoid_idx):
    dists = np.array([[np.linalg.norm(x - X[m]) for m in medoid_idx] for x in X])
    labels = np.argmin(dists, axis=1)
    total_cost = np.sum(np.min(dists, axis=1))
    return labels, total_cost

np.random.seed(42)
medoids = list(np.random.choice(len(X), size=K, replace=False))
labels, current_cost = compute_cost(X, medoids)

# PAM Swap Loop
for _ in range(20):
    improved = False
    non_medoids = [i for i in range(len(X)) if i not in medoids][:20]
    for m_pos in range(K):
        for candidate in non_medoids:
            trial = list(medoids)
            trial[m_pos] = candidate
            _, trial_cost = compute_cost(X, trial)
            if trial_cost < current_cost:
                medoids, current_cost = trial, trial_cost
                improved = True
                break
        if improved: break
    if not improved: break

print("Final Medoids (Data point rows):", medoids)
print(f"Total Distance Cost: {current_cost:.2f}")


================================================================================
EXPERIMENT 7: HIERARCHICAL CLUSTERING (LIBRARIES & SCRATCH)
================================================================================

--------------------------------------------------------------------------------
1. HIERARCHICAL CLUSTERING USING LIBRARIES (StandardScaler + Dendrogram)
--------------------------------------------------------------------------------
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score

# ===== USER SETTINGS =====
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "mall_customers.csv")
K = 3

# 1. Load data & Apply MANDATORY StandardScaler
df = pd.read_csv(FILE_PATH)
num_cols = [c for c in df.select_dtypes(include=[np.number]).columns if "id" not in c.lower()]
X = df[num_cols].fillna(df[num_cols].median()).values
X_scaled = StandardScaler().fit_transform(X)

# 2. Compute Linkage & Save Dendrogram
linked = linkage(X_scaled, method="ward")
plt.figure(figsize=(8, 4))
dendrogram(linked, truncate_mode='lastp', p=12)
plt.title("Hierarchical Dendrogram (Ward Linkage)")
plt.savefig("dendrogram.png")
plt.close()

# 3. Compare Linkages & Fit Final Model
for m in ["ward", "complete", "average", "single"]:
    model = AgglomerativeClustering(n_clusters=K, linkage=m)
    labels = model.fit_predict(X_scaled)
    print(f"Linkage {m:<10} | Silhouette: {silhouette_score(X_scaled, labels):.4f}")

final_labels = AgglomerativeClustering(n_clusters=K, linkage="ward").fit_predict(X_scaled)
print("Final Silhouette Score:", round(silhouette_score(X_scaled, final_labels), 4))

--------------------------------------------------------------------------------
2. HIERARCHICAL CLUSTERING FROM SCRATCH (35 Lines)
--------------------------------------------------------------------------------
import math, pandas as pd
df = pd.read_csv("../datasets/dwm_common_dataset.csv")
data = df[["X", "Y"]].values.tolist()
clusters = [[p] for p in data]
K = 3

while len(clusters) > K:
    min_dist, a, b = float("inf"), 0, 1
    for i in range(len(clusters)):
        for j in range(i + 1, len(clusters)):
            for p in clusters[i]:
                for q in clusters[j]:
                    d = math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)
                    if d < min_dist:
                        min_dist, a, b = d, i, j
    clusters[a] = clusters[a] + clusters[b]
    clusters.pop(b)

print("Final Clusters (Scratch):", clusters)


================================================================================
EXPERIMENT 8: NAIVE BAYES CLASSIFICATION (FROM SCRATCH USING LOOPS)
================================================================================

--------------------------------------------------------------------------------
1. CATEGORICAL NAIVE BAYES (WITH LAPLACE SMOOTHING) (40 Lines)
--------------------------------------------------------------------------------
import os, pandas as pd

FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "play_tennis.csv")
TARGET = "PlayTennis"
QUERY = {"Outlook": "Sunny", "Temperature": "Cool", "Humidity": "High", "Wind": "Strong"}

df = pd.read_csv(FILE_PATH)
features = [c for c in df.columns if c != TARGET and not c.lower().endswith("id") and c.lower() != "day"]
classes = list(df[TARGET].unique())
n = len(df)

# Prior P(C)
priors = {c: sum(df[TARGET] == c) / n for c in classes}

# Likelihoods with Laplace Smoothing: P(x_i | C) = (count + 1) / (count(C) + |V_i|)
posteriors = {}
for c in classes:
    p = priors[c]
    sub = df[df[TARGET] == c]
    for f in features:
        val = QUERY[f]
        cnt = sum(sub[f] == val)
        v_size = df[f].nunique()
        p *= (cnt + 1) / (len(sub) + v_size)
    posteriors[c] = p

print("Calculated Posteriors:", posteriors)
print("-> PREDICTED CLASS:", max(posteriors, key=posteriors.get))

--------------------------------------------------------------------------------
2. GAUSSIAN NAIVE BAYES (FOR CONTINUOUS NUMERICAL DATA) (45 Lines)
--------------------------------------------------------------------------------
import os, math, pandas as pd, numpy as np

FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "diabetes_simple.csv")
TARGET = "Outcome"
QUERY = {"Glucose": 140, "BloodPressure": 80, "BMI": 32.5, "Age": 45}

df = pd.read_csv(FILE_PATH)
num_cols = [c for c in df.select_dtypes(include=[np.number]).columns if not c.lower().endswith("id") and c != TARGET]
classes = list(df[TARGET].unique())

def gaussian_pdf(x, mean, var):
    v = var + 1e-9
    return (1.0 / math.sqrt(2 * math.pi * v)) * math.exp(-((x - mean) ** 2) / (2 * v))

posteriors = {}
for c in classes:
    sub = df[df[TARGET] == c]
    log_p = math.log(len(sub) / len(df))
    for col in num_cols:
        mean, var = np.mean(sub[col]), np.var(sub[col])
        log_p += math.log(max(gaussian_pdf(float(QUERY[col]), mean, var), 1e-12))
    posteriors[c] = log_p

print("Log Posteriors:", posteriors)
print("-> PREDICTED CLASS:", max(posteriors, key=posteriors.get))


================================================================================
EXPERIMENT 9: SIMPLE PAGERANK (WITHOUT DAMPING FACTOR) & HITS ALGORITHM
Formula: PR(A) = Sum( PR(T) / C(T) )  or  v_k = A * v_{k-1}
================================================================================

--------------------------------------------------------------------------------
1. SIMPLE PAGERANK WITHOUT DAMPING FACTOR (30 Lines)
--------------------------------------------------------------------------------
GRAPH = {
    'A': ['B', 'C'],
    'B': ['D'],
    'C': ['A', 'B', 'D'],
    'D': ['C']
}
MAX_ITER = 20

nodes = sorted(list(GRAPH.keys()))
N = len(nodes)
pr = {n: 1.0 / N for n in nodes}  # Uniform initial rank: 1/N

for it in range(1, MAX_ITER + 1):
    new_pr = {n: 0.0 for n in nodes}
    # Dangling node share (nodes with 0 outgoing links)
    dangling_share = sum(pr[n] for n in nodes if len(GRAPH[n]) == 0) / N
    
    # Distribute rank: PR(A) = Sum( PR(T) / C(T) )
    for n in nodes:
        out = GRAPH[n]
        if out:
            share = pr[n] / len(out)
            for target in out:
                new_pr[target] += share
                
    pr = {n: new_pr[n] + dangling_share for n in nodes}

print("Final PageRank Scores:")
for p, s in sorted(pr.items(), key=lambda x: x[1], reverse=True):
    print(f"Page {p} -> {s:.4f} ({s*100:.1f}%)")

--------------------------------------------------------------------------------
2. HITS ALGORITHM (HUBS & AUTHORITIES) (35 Lines)
--------------------------------------------------------------------------------
import math
GRAPH = {'A': ['B', 'C'], 'B': ['C'], 'C': ['A'], 'D': ['C']}
nodes = sorted(list(GRAPH.keys()))
in_links = {n: [src for src in nodes if n in GRAPH[src]] for n in nodes}

h = {n: 1.0 for n in nodes}
a = {n: 1.0 for n in nodes}

for _ in range(10):
    # Authority = sum of hubs pointing to it
    new_a = {p: sum(h[q] for q in in_links[p]) for p in nodes}
    norm_a = math.sqrt(sum(v**2 for v in new_a.values()))
    a = {p: new_a[p] / norm_a for p in nodes}
    
    # Hub = sum of authorities it points to
    new_h = {p: sum(a[q] for q in GRAPH[p]) for p in nodes}
    norm_h = math.sqrt(sum(v**2 for v in new_h.values()))
    h = {p: new_h[p] / norm_h for p in nodes}

print("Final Authorities:", {k: round(v, 4) for k, v in a.items()})
print("Final Hubs:", {k: round(v, 4) for k, v in h.items()})
