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

analyze.py 6.1 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
  1. import logging
  2. import subprocess as sp
  3. import gzip
  4. from functools import reduce
  5. from humanize import naturalsize, intcomma
  6. import pandas as pd
  7. import numpy as np
  8. from numba import njit
  9. import support as s
  10. from invoke import task
  11. _log = logging.getLogger(__name__)
  12. rec_names = {'loc': 'LOC', 'ol': 'OpenLibrary', 'gr': 'GoodReads'}
  13. rec_queries = {
  14. 'loc': '''
  15. SELECT isbn_id, MIN(bc_of_loc_rec(rec_id)) AS record
  16. FROM loc_rec_isbn GROUP BY isbn_id
  17. ''',
  18. 'ol': '''
  19. SELECT DISTINCT isbn_id, MIN(book_code) AS record
  20. FROM ol_isbn_link GROUP BY isbn_id
  21. ''',
  22. 'gr': '''
  23. SELECT DISTINCT isbn_id, MIN(book_code) AS record
  24. FROM gr_book_isbn GROUP BY isbn_id
  25. '''
  26. }
  27. rec_edge_queries = {
  28. 'loc': '''
  29. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  30. FROM loc_rec_isbn l JOIN loc_rec_isbn r ON (l.rec_id = r.rec_id)
  31. ''',
  32. 'ol': '''
  33. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  34. FROM ol_isbn_link l JOIN ol_isbn_link r ON (l.book_code = r.book_code)
  35. ''',
  36. 'gr': '''
  37. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  38. FROM gr_book_isbn l JOIN gr_book_isbn r ON (l.book_code = r.book_code)
  39. '''
  40. }
  41. prereqs = {'loc': 'loc-index', 'ol': 'ol-index', 'gr': 'gr-index-books'}
  42. def cluster_isbns(isbn_recs, edges):
  43. """
  44. Compute ISBN clusters.
  45. """
  46. _log.info('initializing isbn vector')
  47. isbns = isbn_recs.groupby('isbn_id').record.min()
  48. index = isbns.index
  49. clusters = isbns.values
  50. _log.info('mapping edge IDs')
  51. edges = edges.assign(left_ino=index.get_indexer(edges.left_isbn).astype('i4'))
  52. assert np.all(edges.left_ino >= 0)
  53. edges = edges.assign(right_ino=index.get_indexer(edges.right_isbn).astype('i4'))
  54. assert np.all(edges.right_ino >= 0)
  55. _log.info('clustering')
  56. iters = _make_clusters(clusters, edges.left_ino.values, edges.right_ino.values)
  57. isbns = isbns.reset_index(name='cluster')
  58. _log.info('produced %s clusters in %d iterations',
  59. intcomma(isbns.cluster.nunique()), iters)
  60. return isbns.loc[:, ['isbn_id', 'cluster']]
  61. @njit
  62. def _make_clusters(clusters, ls, rs):
  63. """
  64. Compute book clusters. The input is initial cluster assignments and the left and right
  65. indexes for co-occuring ISBN edges; these are ISBNs that have connections to the same
  66. record in the bipartite ISBN-record graph.
  67. Args:
  68. clusters(ndarray): the initial cluster assignments
  69. ls(ndarray): the indexes of the left hand side of edges
  70. rs(ndarray): the indexes of the right hand side of edges
  71. """
  72. iters = 0
  73. nchanged = len(ls)
  74. while nchanged > 0:
  75. nchanged = 0
  76. iters = iters + 1
  77. for i in range(len(ls)):
  78. left = ls[i]
  79. right = rs[i]
  80. if clusters[left] < clusters[right]:
  81. clusters[right] = clusters[left]
  82. nchanged += 1
  83. return iters
  84. def _export_isbns(scope, file):
  85. query = rec_queries[scope]
  86. query = query.strip().replace('\n', ' ')
  87. if file.exists():
  88. _log.info('%s already exists, not re-exporting', file)
  89. return
  90. _log.info('exporting ISBNs from %s to %s', rec_names[scope], file)
  91. tmp = file.with_name('.tmp.' + file.name)
  92. s.pipeline([
  93. ['psql', '-v', 'ON_ERROR_STOP=on', '-c',
  94. f'\\copy ({query}) TO STDOUT WITH CSV HEADER'],
  95. ['gzip', '-4']
  96. ], outfile=tmp)
  97. tmp.replace(file)
  98. def _export_edges(scope, file):
  99. query = rec_edge_queries[scope]
  100. query = query.strip().replace('\n', ' ')
  101. if file.exists():
  102. _log.info('%s already exists, not re-exporting', file)
  103. return
  104. _log.info('exporting ISBN-ISBN edges from %s to %s', rec_names[scope], file)
  105. tmp = file.with_name('.tmp.' + file.name)
  106. s.pipeline([
  107. ['psql', '-v', 'ON_ERROR_STOP=on', '-c',
  108. f'\\copy ({query}) TO STDOUT WITH CSV HEADER'],
  109. ['gzip', '-4']
  110. ], outfile=tmp)
  111. tmp.replace(file)
  112. def _import_clusters(tbl, file):
  113. sql = f'''
  114. DROP TABLE IF EXISTS {tbl} CASCADE;
  115. CREATE TABLE {tbl} (
  116. isbn_id INTEGER NOT NULL,
  117. cluster INTEGER NOT NULL
  118. );
  119. \copy {tbl} FROM '{file}' WITH (FORMAT CSV);
  120. ALTER TABLE {tbl} ADD PRIMARY KEY (isbn_id);
  121. CREATE INDEX {tbl}_idx ON {tbl} (cluster);
  122. ANALYZE {tbl};
  123. '''
  124. _log.info('running psql for %s', tbl)
  125. kid = sp.Popen(['psql', '-v', 'ON_ERROR_STOP=on', '-a'], stdin=sp.PIPE)
  126. kid.stdin.write(sql.encode('ascii'))
  127. kid.communicate()
  128. rc = kid.wait()
  129. if rc:
  130. _log.error('psql exited with code %d', rc)
  131. raise RuntimeError('psql error')
  132. @task(s.init)
  133. def cluster(c, scope=None, force=False):
  134. "Cluster ISBNs"
  135. s.check_prereq('loc-index')
  136. s.check_prereq('ol-index')
  137. s.check_prereq('gr-index-books')
  138. if scope is None:
  139. step = 'cluster'
  140. fn = 'clusters.csv'
  141. table = 'isbn_cluster'
  142. scopes = list(rec_names.keys())
  143. else:
  144. step = f'{scope}-cluster'
  145. fn = f'{scope}-clusters.csv'
  146. table = f'{scope}_isbn_cluster'
  147. scopes = [scope]
  148. for scope in scopes:
  149. s.check_prereq(prereqs[scope])
  150. s.start(step, force=force)
  151. isbn_recs = []
  152. isbn_edges = []
  153. for scope in scopes:
  154. i_fn = s.data_dir / f'{scope}-isbns.csv.gz'
  155. _export_isbns(scope, i_fn)
  156. _log.info('reading ISBNs from %s', i_fn)
  157. isbn_recs.append(pd.read_csv(i_fn, dtype='i4'))
  158. e_fn = s.data_dir / f'{scope}-edges.csv.gz'
  159. _export_edges(scope, e_fn)
  160. _log.info('reading edges from %s', e_fn)
  161. isbn_edges.append(pd.read_csv(e_fn, dtype='i4'))
  162. isbn_recs = pd.concat(isbn_recs, ignore_index=True)
  163. isbn_edges = pd.concat(isbn_edges, ignore_index=True)
  164. _log.info('clustering %s ISBN records with %s edges',
  165. intcomma(len(isbn_recs)), intcomma(len(isbn_edges)))
  166. loc_clusters = cluster_isbns(isbn_recs, isbn_edges)
  167. _log.info('writing ISBN records to %s', fn)
  168. loc_clusters.to_csv(s.data_dir / fn, index=False, header=False)
  169. _log.info('importing ISBN records')
  170. _import_clusters(table, s.data_dir / fn)
  171. s.finish(step)
Tip!

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

Comments

Loading...