Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

cluster.py 6.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
  1. """
  2. Usage:
  3. cluster.py [-T FILE] [SCOPE]
  4. Options:
  5. -T FILE
  6. Write transcript to FILE.
  7. SCOPE
  8. Cluster SCOPE.
  9. """
  10. import os
  11. import sys
  12. import gzip
  13. import threading
  14. from textwrap import dedent
  15. from functools import reduce
  16. from natural.number import number
  17. from psycopg2 import sql
  18. import hashlib
  19. from docopt import docopt
  20. import pandas as pd
  21. import numpy as np
  22. from bookdata import db, tracking, script_log
  23. _log = script_log(__name__)
  24. class scope_loc_mds:
  25. name = 'LOC-MDS'
  26. schema = 'locmds'
  27. node_query = dedent('''
  28. SELECT isbn_id, MIN(bc_of_loc_rec(rec_id)) AS record
  29. FROM locmds.book_rec_isbn GROUP BY isbn_id
  30. ''')
  31. edge_query = dedent('''
  32. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  33. FROM locmds.book_rec_isbn l JOIN locmds.book_rec_isbn r ON (l.rec_id = r.rec_id)
  34. ''')
  35. class scope_ol:
  36. name = 'OpenLibrary'
  37. schema = 'ol'
  38. node_query = dedent('''
  39. SELECT isbn_id, MIN(book_code) AS record
  40. FROM ol.isbn_link GROUP BY isbn_id
  41. ''')
  42. edge_query = dedent('''
  43. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  44. FROM ol.isbn_link l JOIN ol.isbn_link r ON (l.book_code = r.book_code)
  45. ''')
  46. class scope_gr:
  47. name = 'GoodReads'
  48. schema = 'gr'
  49. node_query = dedent('''
  50. SELECT DISTINCT isbn_id, MIN(book_code) AS record
  51. FROM gr.book_isbn GROUP BY isbn_id
  52. ''')
  53. edge_query = dedent('''
  54. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  55. FROM gr.book_isbn l JOIN gr.book_isbn r ON (l.book_code = r.book_code)
  56. ''')
  57. class scope_loc_id:
  58. name = 'LOC'
  59. schema = 'locid'
  60. node_query = dedent('''
  61. SELECT isbn_id, MIN(book_code) AS record
  62. FROM locid.isbn_link GROUP BY isbn_id
  63. ''')
  64. edge_query = dedent('''
  65. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  66. FROM locid.isbn_link l JOIN locid.isbn_link r ON (l.book_code = r.book_code)
  67. ''')
  68. _all_scopes = ['ol', 'gr', 'loc-mds']
  69. def get_scope(name):
  70. n = name.replace('-', '_')
  71. return globals()[f'scope_{n}']
  72. def cluster_isbns(isbn_recs, edges):
  73. """
  74. Compute ISBN clusters.
  75. """
  76. _log.info('initializing isbn vector')
  77. isbns = isbn_recs.groupby('isbn_id').record.min()
  78. index = isbns.index
  79. clusters = isbns.values
  80. _log.info('mapping edge IDs')
  81. edges = edges.assign(left_ino=index.get_indexer(edges.left_isbn).astype('i4'))
  82. assert np.all(edges.left_ino >= 0)
  83. edges = edges.assign(right_ino=index.get_indexer(edges.right_isbn).astype('i4'))
  84. assert np.all(edges.right_ino >= 0)
  85. _log.info('clustering')
  86. iters = _make_clusters(clusters, edges.left_ino.values, edges.right_ino.values)
  87. isbns = isbns.reset_index(name='cluster')
  88. _log.info('produced %s clusters in %d iterations',
  89. number(isbns.cluster.nunique()), iters)
  90. return isbns.loc[:, ['isbn_id', 'cluster']]
  91. def _make_clusters(clusters, ls, rs):
  92. """
  93. Compute book clusters. The input is initial cluster assignments and the left and right
  94. indexes for co-occuring ISBN edges; these are ISBNs that have connections to the same
  95. record in the bipartite ISBN-record graph.
  96. Args:
  97. clusters(ndarray): the initial cluster assignments
  98. ls(ndarray): the indexes of the left hand side of edges
  99. rs(ndarray): the indexes of the right hand side of edges
  100. """
  101. iters = 0
  102. nchanged = len(ls)
  103. while nchanged > 0:
  104. iters = iters + 1
  105. cdf = pd.DataFrame({
  106. 'idx': rs,
  107. 'cluster': np.minimum(clusters[ls], clusters[rs])
  108. })
  109. c = cdf.groupby('idx')['cluster'].min()
  110. nchanged = np.sum(c.values != clusters[c.index])
  111. _log.info('iteration %d changed %d clusters', iters, nchanged)
  112. clusters[c.index] = c.values
  113. return iters
  114. def _import_clusters(dbc, schema, frame):
  115. with dbc.cursor() as cur:
  116. schema_i = sql.Identifier(schema)
  117. _log.info('creating cluster table')
  118. cur.execute(sql.SQL('DROP TABLE IF EXISTS {}.isbn_cluster CASCADE').format(schema_i))
  119. cur.execute(sql.SQL('''
  120. CREATE TABLE {}.isbn_cluster (
  121. isbn_id INTEGER NOT NULL,
  122. cluster INTEGER NOT NULL
  123. )
  124. ''').format(schema_i))
  125. _log.info('loading %d clusters into %s.isbn_cluster', len(frame), schema)
  126. db.save_table(dbc, sql.SQL('{}.isbn_cluster').format(schema_i), frame)
  127. cur.execute(sql.SQL('ALTER TABLE {}.isbn_cluster ADD PRIMARY KEY (isbn_id)').format(schema_i))
  128. cur.execute(sql.SQL('CREATE INDEX isbn_cluster_idx ON {}.isbn_cluster (cluster)').format(schema_i))
  129. cur.execute(sql.SQL('ANALYZE {}.isbn_cluster').format(schema_i))
  130. def _hash_frame(df):
  131. hash = hashlib.md5()
  132. for c in df.columns:
  133. hash.update(df[c].values.data)
  134. return hash.hexdigest()
  135. def cluster(scope, txout):
  136. "Cluster ISBNs"
  137. with db.connect() as dbc:
  138. _log.info('preparing to cluster scope %s', scope)
  139. if scope:
  140. step = f'{scope}-cluster'
  141. schema = get_scope(scope).schema
  142. scopes = [scope]
  143. else:
  144. step = 'cluster'
  145. schema = 'public'
  146. scopes = _all_scopes
  147. with dbc:
  148. tracking.begin_stage(dbc, step)
  149. isbn_recs = []
  150. isbn_edges = []
  151. for scope in scopes:
  152. sco = get_scope(scope)
  153. _log.info('reading ISBNs for %s', scope)
  154. irs = db.load_table(dbc, sco.node_query)
  155. n_hash = _hash_frame(irs)
  156. isbn_recs.append(irs)
  157. print('READ NODES', scope, n_hash, file=txout)
  158. _log.info('reading edges for %s', scope)
  159. ies = db.load_table(dbc, sco.edge_query)
  160. e_hash = _hash_frame(ies)
  161. isbn_edges.append(ies)
  162. print('READ EDGES', scope, e_hash, file=txout)
  163. isbn_recs = pd.concat(isbn_recs, ignore_index=True)
  164. isbn_edges = pd.concat(isbn_edges, ignore_index=True)
  165. _log.info('clustering %s ISBN records with %s edges',
  166. number(len(isbn_recs)), number(len(isbn_edges)))
  167. loc_clusters = cluster_isbns(isbn_recs, isbn_edges)
  168. _log.info('saving cluster records to database')
  169. _import_clusters(dbc, schema, loc_clusters)
  170. c_hash = _hash_frame(loc_clusters)
  171. print('WRITE CLUSTERS', c_hash, file=txout)
  172. tracking.end_stage(dbc, step, c_hash)
  173. opts = docopt(__doc__)
  174. tx_fn = opts.get('-T', None)
  175. scope = opts.get('SCOPE', None)
  176. if tx_fn == '-' or not tx_fn:
  177. tx_out = sys.stdout
  178. else:
  179. _log.info('writing transcript to %s', tx_fn)
  180. tx_out = open(tx_fn, 'w')
  181. cluster(scope, tx_out)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...