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 7.2 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
232
233
234
235
236
237
238
239
240
241
242
243
244
  1. import os
  2. import logging
  3. import subprocess as sp
  4. import gzip
  5. import threading
  6. from textwrap import dedent
  7. from functools import reduce
  8. from natural.number import number
  9. from psycopg2 import sql
  10. import pandas as pd
  11. import numpy as np
  12. from numba import njit
  13. import support as s
  14. from invoke import task
  15. _log = logging.getLogger(__name__)
  16. class scope_locmds:
  17. name = 'LOC-MDS'
  18. prereq = 'loc-mds-book-index'
  19. node_query = dedent('''
  20. SELECT isbn_id, MIN(bc_of_loc_rec(rec_id)) AS record
  21. FROM locmds.book_rec_isbn GROUP BY isbn_id
  22. ''')
  23. edge_query = dedent('''
  24. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  25. FROM locmds.book_rec_isbn l JOIN locmds.book_rec_isbn r ON (l.rec_id = r.rec_id)
  26. ''')
  27. class scope_ol:
  28. name = 'OpenLibrary'
  29. prereq = 'ol-index'
  30. node_query = dedent('''
  31. SELECT isbn_id, MIN(book_code) AS record
  32. FROM ol.isbn_link GROUP BY isbn_id
  33. ''')
  34. edge_query = dedent('''
  35. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  36. FROM ol.isbn_link l JOIN ol.isbn_link r ON (l.book_code = r.book_code)
  37. ''')
  38. class scope_gr:
  39. name = 'GoodReads'
  40. prereq = 'gr-index-books'
  41. node_query = dedent('''
  42. SELECT DISTINCT isbn_id, MIN(book_code) AS record
  43. FROM gr.book_isbn GROUP BY isbn_id
  44. ''')
  45. edge_query = dedent('''
  46. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  47. FROM gr.book_isbn l JOIN gr.book_isbn r ON (l.book_code = r.book_code)
  48. ''')
  49. class scope_locid:
  50. name = 'LOC'
  51. prereq = 'loc-id-book-index'
  52. node_query = dedent('''
  53. SELECT isbn_id, MIN(book_code) AS record
  54. FROM locid.isbn_link GROUP BY isbn_id
  55. ''')
  56. edge_query = dedent('''
  57. SELECT DISTINCT l.isbn_id AS left_isbn, r.isbn_id AS right_isbn
  58. FROM locid.isbn_link l JOIN locid.isbn_link r ON (l.book_code = r.book_code)
  59. ''')
  60. _all_scopes = ['ol', 'gr', 'locmds']
  61. def get_scope(name):
  62. return globals()[f'scope_{name}']
  63. class _LoadThread(threading.Thread):
  64. """
  65. Thread worker for copying database results to a stream we can read.
  66. """
  67. def __init__(self, dbc, query, dir='out'):
  68. super().__init__()
  69. self.database = dbc
  70. self.query = query
  71. rfd, wfd = os.pipe()
  72. self.reader = os.fdopen(rfd)
  73. self.writer = os.fdopen(wfd, 'w')
  74. self.chan = self.writer if dir == 'out' else self.reader
  75. def run(self):
  76. with self.chan, self.database.cursor() as cur:
  77. cur.copy_expert(self.query, self.chan)
  78. def load_table(dbc, query):
  79. cq = sql.SQL('COPY ({}) TO STDOUT WITH CSV HEADER')
  80. q = sql.SQL(query)
  81. thread = _LoadThread(dbc, cq.format(q))
  82. thread.start()
  83. data = pd.read_csv(thread.reader)
  84. thread.join()
  85. return data
  86. def save_table(dbc, table, data: pd.DataFrame):
  87. cq = sql.SQL('COPY {} FROM STDIN WITH CSV')
  88. thread = _LoadThread(dbc, cq.format(table), 'in')
  89. thread.start()
  90. data.to_csv(thread.writer, header=False, index=False)
  91. thread.writer.close()
  92. thread.join()
  93. def cluster_isbns(isbn_recs, edges):
  94. """
  95. Compute ISBN clusters.
  96. """
  97. _log.info('initializing isbn vector')
  98. isbns = isbn_recs.groupby('isbn_id').record.min()
  99. index = isbns.index
  100. clusters = isbns.values
  101. _log.info('mapping edge IDs')
  102. edges = edges.assign(left_ino=index.get_indexer(edges.left_isbn).astype('i4'))
  103. assert np.all(edges.left_ino >= 0)
  104. edges = edges.assign(right_ino=index.get_indexer(edges.right_isbn).astype('i4'))
  105. assert np.all(edges.right_ino >= 0)
  106. _log.info('clustering')
  107. iters = _make_clusters(clusters, edges.left_ino.values, edges.right_ino.values)
  108. isbns = isbns.reset_index(name='cluster')
  109. _log.info('produced %s clusters in %d iterations',
  110. number(isbns.cluster.nunique()), iters)
  111. return isbns.loc[:, ['isbn_id', 'cluster']]
  112. @njit
  113. def _make_clusters(clusters, ls, rs):
  114. """
  115. Compute book clusters. The input is initial cluster assignments and the left and right
  116. indexes for co-occuring ISBN edges; these are ISBNs that have connections to the same
  117. record in the bipartite ISBN-record graph.
  118. Args:
  119. clusters(ndarray): the initial cluster assignments
  120. ls(ndarray): the indexes of the left hand side of edges
  121. rs(ndarray): the indexes of the right hand side of edges
  122. """
  123. iters = 0
  124. nchanged = len(ls)
  125. while nchanged > 0:
  126. nchanged = 0
  127. iters = iters + 1
  128. for i in range(len(ls)):
  129. left = ls[i]
  130. right = rs[i]
  131. if clusters[left] < clusters[right]:
  132. clusters[right] = clusters[left]
  133. nchanged += 1
  134. return iters
  135. def _import_clusters(dbc, schema, frame):
  136. schema_i = sql.Identifier(schema)
  137. with dbc, dbc.cursor() as cur:
  138. _log.info('creating cluster table')
  139. cur.execute(sql.SQL('DROP TABLE IF EXISTS {}.isbn_cluster CASCADE').format(schema_i))
  140. cur.execute(sql.SQL('''
  141. CREATE TABLE {}.isbn_cluster (
  142. isbn_id INTEGER NOT NULL,
  143. cluster INTEGER NOT NULL
  144. )
  145. ''').format(schema_i))
  146. _log.info('loading %d clusters into %s.isbn_cluster', len(frame), schema)
  147. save_table(dbc, sql.SQL('{}.isbn_cluster').format(schema_i), frame)
  148. cur.execute(sql.SQL('ALTER TABLE {}.isbn_cluster ADD PRIMARY KEY (isbn_id)').format(schema_i))
  149. cur.execute(sql.SQL('CREATE INDEX isbn_cluster_idx ON {}.isbn_cluster (cluster)').format(schema_i))
  150. cur.execute(sql.SQL('ANALYZE {}.isbn_cluster').format(schema_i))
  151. @task(s.init)
  152. def cluster(c, scope=None, force=False):
  153. "Cluster ISBNs"
  154. with s.database(autocommit=True) as db:
  155. if scope is None:
  156. step = 'cluster'
  157. schema = 'public'
  158. scopes = _all_scopes
  159. else:
  160. step = f'{scope}-cluster'
  161. schema = scope
  162. scopes = [scope]
  163. for scope in scopes:
  164. s.check_prereq(get_scope(scope).prereq)
  165. s.start(step, force=force)
  166. isbn_recs = []
  167. isbn_edges = []
  168. for scope in scopes:
  169. sco = get_scope(scope)
  170. _log.info('reading ISBNs for %s', scope)
  171. isbn_recs.append(load_table(db, sco.node_query))
  172. _log.info('reading edges for %s', scope)
  173. isbn_edges.append(load_table(db, sco.edge_query))
  174. isbn_recs = pd.concat(isbn_recs, ignore_index=True)
  175. isbn_edges = pd.concat(isbn_edges, ignore_index=True)
  176. _log.info('clustering %s ISBN records with %s edges',
  177. number(len(isbn_recs)), number(len(isbn_edges)))
  178. loc_clusters = cluster_isbns(isbn_recs, isbn_edges)
  179. _log.info('saving cluster records to database')
  180. _import_clusters(db, schema, loc_clusters)
  181. s.finish(step)
  182. @task(s.init)
  183. def book_author_names(c, force=False):
  184. "Analyze book authors (name-based linking)"
  185. s.check_prereq('az-index')
  186. s.check_prereq('bx-index')
  187. s.check_prereq('viaf-index')
  188. s.check_prereq('loc-mds-book-index')
  189. s.check_prereq('gr-index-ratings')
  190. s.check_prereq('cluster')
  191. s.start('book-author-names', force=force)
  192. _log.info('Analzye book authors')
  193. s.psql(c, 'author-info.sql', True)
  194. s.finish('book-author-names')
Tip!

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

Comments

Loading...