|
| 1 | +""" |
| 2 | +Run DBSCAN to generate clusters of hashes. |
| 3 | +""" |
| 4 | + |
| 5 | +import argparse |
| 6 | +from array import array |
| 7 | +import sys |
| 8 | +from scipy.sparse import csr_matrix |
| 9 | +from tqdm import tqdm |
| 10 | +import math |
| 11 | + |
| 12 | +# from sklearnex import patch_sklearn |
| 13 | +# patch_sklearn() |
| 14 | +from sklearn.cluster import DBSCAN, OPTICS |
| 15 | +from sklearn.neighbors._base import _check_precomputed, _is_sorted_by_data |
| 16 | +import numpy as np |
| 17 | +import pandas as pd |
| 18 | + |
| 19 | +from memes.utils import read_year, DATA_DIR, construct_output_filename |
| 20 | +from memes.clustering.utils import to_binary_array, to_int |
| 21 | + |
| 22 | + |
| 23 | +def read_distances(path, sample=None, return_csr=True, threshold=10, dist_func=lambda x: x, keeplist=None, upper=False): |
| 24 | + data = array("I") |
| 25 | + rows = array("I") |
| 26 | + cols = array("I") |
| 27 | + # try only taking pairs w distance <= 10 |
| 28 | + # per zsavvas |
| 29 | + THRESHOLD = threshold |
| 30 | + |
| 31 | + class np_buffer_wrapper: |
| 32 | + """ |
| 33 | + Create an array interface for numpy so we can directly refer to |
| 34 | + memory location. |
| 35 | + """ |
| 36 | + def __init__(self, ptr, shape, typestr): |
| 37 | + self.__array_interface__ = { |
| 38 | + "shape": shape, |
| 39 | + "typestr": typestr, |
| 40 | + "data": (ptr, True), |
| 41 | + } |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def from_array(cls, array): |
| 45 | + endianness = {"little": "<", "big": ">"} |
| 46 | + ptr, size = array.buffer_info() |
| 47 | + byteorder = endianness[sys.byteorder] |
| 48 | + # TODO: right now we assume unsigned int. best to infer from the |
| 49 | + # array |
| 50 | + basictype = "u" |
| 51 | + numbytes = array.itemsize |
| 52 | + typestr = byteorder + basictype + str(numbytes) |
| 53 | + return cls(ptr, (size,), typestr) |
| 54 | + |
| 55 | + def add_row(ind1, ind2, dist): |
| 56 | + nonlocal data |
| 57 | + nonlocal rows |
| 58 | + nonlocal cols |
| 59 | + nonlocal keeplist |
| 60 | + if keeplist is not None: |
| 61 | + if not (int(ind1) in keeplist and int(ind2) in keeplist): |
| 62 | + return |
| 63 | + ind1 = keeplist[int(ind1)] |
| 64 | + ind2 = keeplist[int(ind2)] |
| 65 | + if int(ind1) > sample or int(ind2) > sample: |
| 66 | + return |
| 67 | + if int(dist) > THRESHOLD: |
| 68 | + return |
| 69 | + if return_csr: |
| 70 | + if upper: |
| 71 | + data.extend([int(dist)]) |
| 72 | + rows.extend([int(ind1)]) |
| 73 | + cols.extend([int(ind2)]) |
| 74 | + else: |
| 75 | + data.extend([int(dist), int(dist)]) |
| 76 | + rows.extend([int(ind1), int(ind2)]) |
| 77 | + cols.extend([int(ind2), int(ind1)]) |
| 78 | + |
| 79 | + print("reading distances") |
| 80 | + if sample is None: |
| 81 | + sample = math.inf |
| 82 | + with open(path, "r") as f: |
| 83 | + for i, line in tqdm(enumerate(f)): |
| 84 | + if i > sample: |
| 85 | + break |
| 86 | + try: |
| 87 | + ind1, ind2, dist = line.strip().split("\t") |
| 88 | + add_row(ind1, ind2, dist) |
| 89 | + except Exception as e: |
| 90 | + # NOTE: this exception handling addresses a bug in distance |
| 91 | + # calculations that has since been fixed. |
| 92 | + pass |
| 93 | + # ind1, ind2, dist_ind3, ind4, dist2 = line.strip().split("\t") |
| 94 | + # dist = dist_ind3[: -len(ind1)] |
| 95 | + # add_row(ind1, ind2, dist) |
| 96 | + |
| 97 | + # ind3 = dist_ind3[len(dist) :] |
| 98 | + # add_row(ind3, ind4, dist2) |
| 99 | + d = np.array(np_buffer_wrapper.from_array(data), copy=False) |
| 100 | + r = np.array(np_buffer_wrapper.from_array(rows), copy=False) |
| 101 | + c = np.array(np_buffer_wrapper.from_array(cols), copy=False) |
| 102 | + d = dist_func(d) |
| 103 | + if return_csr: |
| 104 | + print("constructing matrix") |
| 105 | + return csr_matrix((d, (r, c))) |
| 106 | + return np.stack([d, r, c]) |
| 107 | + |
| 108 | + |
| 109 | +def hash_to_ind(path): |
| 110 | + """path to file of unique hashes. |
| 111 | +
|
| 112 | + same as path being passed into the distance calculation. |
| 113 | + """ |
| 114 | + hashes = {} |
| 115 | + print("reading index") |
| 116 | + with open(path, "r") as f: |
| 117 | + for i, line in tqdm(enumerate(f)): |
| 118 | + hashes[line.strip()] = i |
| 119 | + return hashes |
| 120 | + |
| 121 | + |
| 122 | +def ind_to_hash(path): |
| 123 | + """path to file of unique hashes. |
| 124 | +
|
| 125 | + same as path being passed into the distance calculation. |
| 126 | + """ |
| 127 | + hashes = list() |
| 128 | + print("reading index") |
| 129 | + with open(path, "r") as f: |
| 130 | + for i, line in tqdm(enumerate(f)): |
| 131 | + hashes.append(line.strip()) |
| 132 | + return hashes |
| 133 | + |
| 134 | + |
| 135 | +np.random.seed(0xB1AB) |
| 136 | + |
| 137 | + |
| 138 | +def main(args): |
| 139 | + |
| 140 | + distances = read_distances(args.distances, args.sample) |
| 141 | + # distances = _check_precomputed(distances) |
| 142 | + hash_index = ind_to_hash(args.hash_index) |
| 143 | + |
| 144 | + print("clustering") |
| 145 | + |
| 146 | + dbscan = DBSCAN(metric="precomputed", eps=args.eps, min_samples=args.min_samples, n_jobs=16) |
| 147 | + # try using OPTICS instead for lower memory |
| 148 | + # dbscan = OPTICS(metric="precomputed", min_samples=args.min_samples) |
| 149 | + |
| 150 | + dbscan.fit(distances) |
| 151 | + clusters = pd.Series(dbscan.labels_, index=list(range(distances.shape[0]))) |
| 152 | + cluster_dict = clusters.to_dict() |
| 153 | + print("writing output file") |
| 154 | + |
| 155 | + outpath = construct_output_filename( |
| 156 | + subdir=DATA_DIR / "clusters", |
| 157 | + prefix=args.prefix, |
| 158 | + suffix="clusters", |
| 159 | + ext="tsv", |
| 160 | + ) |
| 161 | + with open(outpath, "w") as f: |
| 162 | + for ind, cluster in cluster_dict.items(): |
| 163 | + phash = hash_index[ind] |
| 164 | + f.write(f"{phash}\t{cluster}\n") |
| 165 | + print(clusters.value_counts()) |
| 166 | + print("done") |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + parser = argparse.ArgumentParser() |
| 171 | + parser.add_argument("distances") |
| 172 | + parser.add_argument("hash_index") |
| 173 | + parser.add_argument("--eps", type=float, default=8) |
| 174 | + parser.add_argument("--min_samples", type=float, default=3) |
| 175 | + parser.add_argument("--sample", type=int) |
| 176 | + parser.add_argument("--prefix", default=None) |
| 177 | + main(parser.parse_args(sys.argv[1:])) |
0 commit comments