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.4 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
  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 humanize import naturalsize, intcomma
  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 DISTINCT 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. _all_scopes = ['locmds', 'ol']
  39. def get_scope(name):
  40. return globals()[f'scope_{name}']
  41. class _LoadThread(threading.Thread):
  42. """
  43. Thread worker for copying database results to a stream we can read.
  44. """
  45. def __init__(self, dbc, query, dir='out'):
  46. super().__init__()
  47. self.database = dbc
  48. self.query = query
  49. rfd, wfd = os.pipe()
  50. self.reader = os.fdopen(rfd)
  51. self.writer = os.fdopen(wfd, 'w')
  52. self.chan = self.writer if dir == 'out' else self.reader
  53. def run(self):
  54. with self.chan, self.database.cursor() as cur:
  55. cur.copy_expert(self.query, self.chan)
  56. def load_table(dbc, query):
  57. cq = sql.SQL('COPY ({}) TO STDOUT WITH CSV HEADER')
  58. q = sql.SQL(query)
  59. thread = _LoadThread(dbc, cq.format(q))
  60. thread.start()
  61. data = pd.read_csv(thread.reader)
  62. thread.join()
  63. return data
  64. def save_table(dbc, table, data: pd.DataFrame):
  65. cq = sql.SQL('COPY {} FROM STDIN WITH CSV')
  66. thread = _LoadThread(dbc, cq.format(table), 'in')
  67. thread.start()
  68. data.to_csv(thread.writer, header=False, index=False)
  69. thread.writer.close()
  70. thread.join()
  71. def cluster_isbns(isbn_recs, edges):
  72. """
  73. Compute ISBN clusters.
  74. """
  75. _log.info('initializing isbn vector')
  76. isbns = isbn_recs.groupby('isbn_id').record.min()
  77. index = isbns.index
  78. clusters = isbns.values
  79. _log.info('mapping edge IDs')
  80. edges = edges.assign(left_ino=index.get_indexer(edges.left_isbn).astype('i4'))
  81. assert np.all(edges.left_ino >= 0)
  82. edges = edges.assign(right_ino=index.get_indexer(edges.right_isbn).astype('i4'))
  83. assert np.all(edges.right_ino >= 0)
  84. _log.info('clustering')
  85. iters = _make_clusters(clusters, edges.left_ino.values, edges.right_ino.values)
  86. isbns = isbns.reset_index(name='cluster')
  87. _log.info('produced %s clusters in %d iterations',
  88. intcomma(isbns.cluster.nunique()), iters)
  89. return isbns.loc[:, ['isbn_id', 'cluster']]
  90. @njit
  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. nchanged = 0
  105. iters = iters + 1
  106. for i in range(len(ls)):
  107. left = ls[i]
  108. right = rs[i]
  109. if clusters[left] < clusters[right]:
  110. clusters[right] = clusters[left]
  111. nchanged += 1
  112. return iters
  113. def _import_clusters(dbc, schema, frame):
  114. schema_i = sql.Identifier(schema)
  115. with dbc, dbc.cursor() as cur:
  116. _log.info('creating cluster table')
  117. cur.execute(sql.SQL('DROP TABLE IF EXISTS {}.isbn_cluster CASCADE').format(schema_i))
  118. cur.execute(sql.SQL('''
  119. CREATE TABLE {}.isbn_cluster (
  120. isbn_id INTEGER NOT NULL,
  121. cluster INTEGER NOT NULL
  122. )
  123. ''').format(schema_i))
  124. _log.info('loading %d clusters into %s.isbn_cluster', len(frame), schema)
  125. save_table(dbc, sql.SQL('{}.isbn_cluster').format(schema_i), frame)
  126. cur.execute(sql.SQL('ALTER TABLE {}.isbn_cluster ADD PRIMARY KEY (isbn_id)').format(schema_i))
  127. cur.execute(sql.SQL('CREATE INDEX isbn_cluster_idx ON {}.isbn_cluster (cluster)').format(schema_i))
  128. cur.execute(sql.SQL('ANALYZE {}.isbn_cluster').format(schema_i))
  129. @task(s.init)
  130. def cluster(c, scope=None, force=False):
  131. "Cluster ISBNs"
  132. with s.database(autocommit=True) as db:
  133. if scope is None:
  134. step = 'cluster'
  135. schema = 'public'
  136. scopes = _all_scopes
  137. else:
  138. step = f'{scope}-cluster'
  139. schema = scope
  140. scopes = [scope]
  141. for scope in scopes:
  142. s.check_prereq(get_scope(scope).prereq)
  143. s.start(step, force=force)
  144. isbn_recs = []
  145. isbn_edges = []
  146. for scope in scopes:
  147. sco = get_scope(scope)
  148. _log.info('reading ISBNs for %s', scope)
  149. isbn_recs.append(load_table(db, sco.node_query))
  150. _log.info('reading edges for %s', scope)
  151. isbn_edges.append(load_table(db, sco.edge_query))
  152. isbn_recs = pd.concat(isbn_recs, ignore_index=True)
  153. isbn_edges = pd.concat(isbn_edges, ignore_index=True)
  154. _log.info('clustering %s ISBN records with %s edges',
  155. intcomma(len(isbn_recs)), intcomma(len(isbn_edges)))
  156. loc_clusters = cluster_isbns(isbn_recs, isbn_edges)
  157. _log.info('saving cluster records to database')
  158. _import_clusters(db, schema, loc_clusters)
  159. s.finish(step)
  160. @task(s.init)
  161. def book_authors(c, force=False):
  162. "Analyze book authors"
  163. s.check_prereq('az-index')
  164. s.check_prereq('bx-index')
  165. s.check_prereq('viaf-index')
  166. s.check_prereq('loc-mds-book-index')
  167. s.start('book-authors', force=force)
  168. _log.info('Analzye book authors')
  169. s.psql(c, 'author-info.sql', True)
  170. s.finish('book-authors')
Tip!

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

Comments

Loading...