<jupyter_start><jupyter_text>This example demonstrates one possible way to cluster data sets that are too large to fit into memory using MDTraj and `scipy.cluster`. The idea for the algorithim is that we'll cluster every N-th frame directly, and then, considering the clusters fixed "assign" the remaining frames to the nearest cluster. It's not the most sophisticated algorithm, but it's a good demonstration of how MDTraj can be integrated with other data science tools.<jupyter_code>from __future__ import print_function
import random
from collections import defaultdict
import mdtraj as md
import numpy as np
import scipy.cluster.hierarchy
stride = 5
subsampled = md.load('ala2.h5', stride=stride)
print(subsampled)<jupyter_output><empty_output><jupyter_text>Compute the pairwise RMSD between all of the frames. This requiresN^2 memory, which is why we might need to stride.<jupyter_code>distances = np.empty((subsampled.n_frames, subsampled.n_frames))
for i in range(subsampled.n_frames):
    distances[i] = md.rmsd(subsampled, subsampled, i)<jupyter_output><empty_output><jupyter_text>Now that we have the distances, we can use out favorite clusteringalgorithm. I like ward.<jupyter_code>n_clusters = 3
linkage = scipy.cluster.hierarchy.ward(distances)
labels = scipy.cluster.hierarchy.fcluster(linkage, t=n_clusters, criterion='maxclust')

labels<jupyter_output><empty_output><jupyter_text>Now, we need to extract n_leaders random samples from each of the clusters.One way to do this is by building a map from each of the cluster labelsto the list of the indices of the subsampled confs which belong to it.<jupyter_code>mapping = defaultdict(lambda : [])
for i, label in enumerate(labels):
    mapping[label].append(i)

mapping<jupyter_output><empty_output><jupyter_text>Now we can iterate through the mapping and select n_leaders randomsamples from each list. As we select them, we'll extract theconformation and append it to a new trajectory called `leaders`, whichwill start empty.<jupyter_code>n_leaders_per_cluster = 2
leaders = md.Trajectory(xyz=np.empty((0, subsampled.n_atoms, 3)),
                        topology=subsampled.topology)
leader_labels = []
for label, indices in mapping.items():
    leaders = leaders.join(subsampled[np.random.choice(indices, n_leaders_per_cluster)])
    leader_labels.extend([label] * n_leaders_per_cluster)

print(leaders)
print(leader_labels)<jupyter_output><empty_output><jupyter_text>Now our `leaders` trajectory contains a set of representitive conformationsfor each cluster. Here comes the second pass of the two-pass clustering.Let's now consider these clusters as fixed objects and iterate through*every* frame in our data set, assigning each frame to the clusterit's closest to. We take the simple approach here of computing the distancefrom each frame to each leader and assigning the frame to the cluster whoseleader is closest.Note that this whole algorithm never requires having the entiredataset in memory at once<jupyter_code>labels = []
for frame in md.iterload('ala2.h5', chunk=1):
    labels.append(leader_labels[np.argmin(md.rmsd(leaders, frame, 0))])
labels = np.array(labels)

print(labels)
print(labels.shape)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07572452477407292, 'fraction_numerical': 0.00373948270489249, 'mean_word_length': 6.0394736842105265, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '550463', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 974, 'n_tokens_neox': 937, 'n_words': 339, 'path': 'uci-pharmsci/lectures/cluster_and_visualize/MDTraj Examples/two-pass-clustering.ipynb', 'repo_name': 'davidlmobley/drug-computing', 'size': '3209'}