import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score

X_blobs, y_blobs = make_blobs(
    n_samples=[200, 200, 200],
    centers=[(-5, -2), (0, 0), (5, 4)],
    cluster_std=[0.4, 0.8, 1.5],
    random_state=42
)

rng = np.random.RandomState(42)
noise = rng.uniform(-10, 10, size=(50, 2))

X = np.vstack([X_blobs, noise])

print(f"Total dataset points: {len(X)} (600 cluster points + 50 noise points)")

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

dbscan = DBSCAN(eps=0.3, min_samples=5)
labels = dbscan.fit_predict(X_scaled)

unique_labels = set(labels)
n_clusters = len(unique_labels) - (1 if -1 in unique_labels else 0)
n_noise = np.sum(labels == -1)

print(f"Number of clusters found: {n_clusters}")
print(f"Number of noise points   : {n_noise}")

mask = (labels != -1)

if len(set(labels[mask])) > 1:
    score = silhouette_score(X_scaled[mask], labels[mask])
    print(f"Silhouette Score (excluding noise): {score:.4f}")
else:
    print("Silhouette Score: Not defined")

plt.figure(figsize=(8, 5))
plt.scatter(
    X_scaled[:, 0], X_scaled[:, 1],
    c=labels, cmap='rainbow', s=30, alpha=0.7, edgecolor='k'
)
plt.title(f"DBSCAN Clustering (Clusters: {n_clusters}, Noise Points: {n_noise})")
plt.xlabel("Feature 1 (Standardized)")
plt.ylabel("Feature 2 (Standardized)")
plt.colorbar(label="Cluster Label (-1 = Noise)")
plt.grid(True, linestyle='--', alpha=0.5)
plt.show()
