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

inspect-idgraph.py 8.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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  1. """
  2. Inspect a book cluster.
  3. Usage:
  4. inspect-idgraph.py [options] --stats
  5. inspect-idgraph.py [options] --records CLUSTER
  6. inspect-idgraph.py [options] --graph CLUSTER
  7. inspect-idgraph.py [options] --full-graph
  8. Options:
  9. -o FILE
  10. Write output to FILE
  11. -f, --format FMT
  12. Output in format FMT.
  13. CLUSTER
  14. The cluster number to inspect.
  15. """
  16. import sys
  17. import re
  18. import json
  19. from xml.etree import ElementTree as etree
  20. from textwrap import dedent as d
  21. from docopt import docopt
  22. import pandas as pd
  23. from bookdata import tracking, db, script_log
  24. from bookdata.graph import GraphLoader
  25. class GMLWriter:
  26. def __init__(self, out):
  27. self.output = out
  28. self._n_attrs = set(['id'])
  29. def _p(self, code, *args):
  30. print(code.format(*args), file=self.output)
  31. def node_attr(self, name):
  32. self._n_attrs.add(name)
  33. def start(self):
  34. self._p('graph [')
  35. self._p(' directed 0')
  36. def finish(self):
  37. self._p(']')
  38. def node(self, **attrs):
  39. self._p(' node [')
  40. for k, v in attrs.items():
  41. if k not in self._n_attrs:
  42. raise RuntimeError('unknown node attribute ' + k)
  43. if k == 'label':
  44. v = str(v)
  45. if v is not None:
  46. self._p(' {} {}', k, json.dumps(v))
  47. self._p(' ]')
  48. def edge(self, **attrs):
  49. self._p(' edge [')
  50. for k, v in attrs.items():
  51. if v is not None:
  52. self._p(' {} {}', k, json.dumps(v))
  53. self._p(' ]')
  54. class GraphMLWriter:
  55. _g_started = False
  56. def __init__(self, out):
  57. self.output = out
  58. self.tb = etree.TreeBuilder()
  59. self._ec = 0
  60. def node_attr(self, name, type='string'):
  61. self.tb.start('key', {
  62. 'id': name,
  63. 'for': 'node',
  64. 'attr.name': name,
  65. 'attr.type': type
  66. })
  67. self.tb.end('key')
  68. def start(self):
  69. self.tb.start('graphml', {
  70. 'xmlns': 'http://graphml.graphdrawing.org/xmlns',
  71. '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': d('''
  72. http://graphml.graphdrawing.org/xmlns
  73. http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd
  74. ''').strip(),
  75. })
  76. def finish(self):
  77. self.tb.end('graph')
  78. self.tb.end('graphml')
  79. elt = self.tb.close()
  80. tree = etree.ElementTree(elt)
  81. tree.write(self.output, encoding='unicode')
  82. def node(self, id, **attrs):
  83. if not self._g_started:
  84. self.tb.start('graph', {
  85. 'edgedefault': 'undirected'
  86. })
  87. self._g_started = True
  88. self.tb.start('node', {
  89. 'id': id
  90. })
  91. for k, v in attrs.items():
  92. if v is not None:
  93. self.tb.start('data', {'key': k})
  94. self.tb.data(str(v))
  95. self.tb.end('data')
  96. self.tb.end('node')
  97. def edge(self, source, target):
  98. self._ec += 1
  99. eid = self._ec
  100. self.tb.start('edge', {
  101. 'id': f'e{eid}',
  102. 'source': source,
  103. 'target': target
  104. })
  105. self.tb.end('edge')
  106. def stats(dbc, out, opts):
  107. "Compute statistics of the clustering"
  108. with dbc.cursor() as cur:
  109. _log.info('getting aggregate stats')
  110. cur.execute('SELECT COUNT(*), MAX(isbns) FROM cluster_stats')
  111. n_clusters, m_isbns = cur.fetchone()
  112. print(f'Clusters: {n_clusters}', file=out)
  113. print(f'Largest has {m_isbns} ISBNs', file=out)
  114. _log.info('computing top stats')
  115. print('Top clusters by size:', file=out)
  116. top = pd.read_sql('SELECT * FROM cluster_stats ORDER BY isbns DESC LIMIT 10', dbc)
  117. print(top.fillna(0), file=out)
  118. def records(dbc, out, opts):
  119. "Dump ISBN records from a cluster to a CSV file"
  120. cluster = opts['CLUSTER']
  121. bc_recs = []
  122. _log.info('inspecting cluster %s', cluster)
  123. _log.info('fetching LOC records')
  124. bc_recs.append(pd.read_sql(f'''
  125. SELECT isbn, 'LOC' AS source, rec_id AS record, NULL AS work, title
  126. FROM locmds.book_rec_isbn
  127. JOIN isbn_id USING (isbn_id)
  128. JOIN isbn_cluster USING (isbn_id)
  129. LEFT JOIN locmds.book_title USING (rec_id)
  130. WHERE cluster = {cluster}
  131. ''', dbc))
  132. _log.info('fetching OL records')
  133. bc_recs.append(pd.read_sql(f'''
  134. SELECT isbn, 'OL' AS source,
  135. edition_id AS record, work_id AS work,
  136. title
  137. FROM ol.isbn_link
  138. JOIN isbn_id USING (isbn_id)
  139. JOIN isbn_cluster USING (isbn_id)
  140. LEFT JOIN ol.edition_title USING (edition_id)
  141. WHERE cluster = {cluster}
  142. ''', dbc))
  143. _log.info('fetching GR records')
  144. bc_recs.append(pd.read_sql(f'''
  145. SELECT isbn, 'GR' AS source,
  146. gr_book_id AS record, gr_work_id AS work,
  147. work_title
  148. FROM gr.book_isbn
  149. JOIN isbn_id USING (isbn_id)
  150. JOIN isbn_cluster USING (isbn_id)
  151. JOIN gr.book_ids USING (gr_book_id)
  152. LEFT JOIN gr.work_title USING (gr_work_id)
  153. WHERE cluster = {cluster}
  154. ''', dbc))
  155. bc_recs = pd.concat(bc_recs, ignore_index=True)
  156. bc_recs.sort_values('isbn', inplace=True)
  157. _log.info('fetched %d records', len(bc_recs))
  158. bc_recs.to_csv(out, index=False)
  159. def graph(dbc, out, opts):
  160. cluster = opts['CLUSTER']
  161. _log.info('exporting graph for cluster %s', cluster)
  162. format = opts.get('--format', 'gml')
  163. if format == 'gml':
  164. gw = GMLWriter(out)
  165. elif format == 'graphml':
  166. gw = GraphMLWriter(out)
  167. else:
  168. raise ValueError('invalid format ' + format)
  169. gw.start()
  170. gw.node_attr('label')
  171. gw.node_attr('category')
  172. gw.node_attr('title')
  173. gl = GraphLoader()
  174. with dbc.cursor() as cur:
  175. gl.set_cluster(cluster, dbc)
  176. _log.info('fetching ISBNs')
  177. cur.execute(gl.q_isbns())
  178. for iid, isbn in cur:
  179. gw.node(id=f'i{iid}', label=isbn, category='ISBN')
  180. _log.info('fetching LOC records')
  181. cur.execute(gl.q_loc_nodes(True))
  182. for rid, title in cur:
  183. gw.node(id=f'l{rid}', label=rid, category='LOC', title=title)
  184. _log.info('fetching LOC ISBN links')
  185. cur.execute(gl.q_loc_edges())
  186. for iid, rid in cur:
  187. gw.edge(source=f'l{rid}', target=f'i{iid}')
  188. _log.info('fetching OL editions')
  189. cur.execute(gl.q_ol_edition_nodes(True))
  190. for eid, ek, e_title in cur:
  191. gw.node(id=f'ole{eid}', label=ek, category='OLE', title=e_title)
  192. _log.info('fetching OL works')
  193. cur.execute(gl.q_ol_work_nodes(True))
  194. for wid, wk, w_title in cur:
  195. gw.node(id=f'olw{wid}', label=wk, category='OLW', title=w_title)
  196. _log.info('fetching OL ISBN edges')
  197. cur.execute(gl.q_ol_edition_edges())
  198. for iid, eid in cur:
  199. gw.edge(source=f'ole{eid}', target=f'i{iid}')
  200. _log.info('fetching OL edition/work edges')
  201. cur.execute(gl.q_ol_work_edges())
  202. for eid, wid in cur:
  203. gw.edge(source=f'ole{eid}', target=f'olw{wid}')
  204. _log.info('fetching GR books')
  205. cur.execute(gl.q_gr_book_edges())
  206. bids = set()
  207. for iid, bid in cur:
  208. if bid not in bids:
  209. gw.node(id=f'grb{bid}', label=bid, category='GRB')
  210. bids.add(bid)
  211. gw.edge(source=f'grb{bid}', target=f'i{iid}')
  212. _log.info('fetching GR works')
  213. cur.execute(gl.q_gr_work_nodes(True))
  214. for wid, title in cur:
  215. gw.node(id=f'grw{wid}', label=wid, category='GRW', title=title)
  216. _log.info('fetching GR work/edition edges')
  217. cur.execute(gl.q_gr_work_edges())
  218. for bid, wid in cur:
  219. gw.edge(source=f'grw{wid}', target=f'grb{bid}')
  220. gw.finish()
  221. _log.info('exported graph')
  222. def full_graph(opts):
  223. gl = GraphLoader()
  224. with db.engine().connect() as cxn:
  225. g = gl.load_minimal_graph(cxn)
  226. ofn = opts['-o']
  227. _log.info('saving graph to %s', ofn)
  228. g.save(ofn)
  229. _log = script_log(__name__)
  230. opts = docopt(__doc__)
  231. if opts['-o']:
  232. out = open(opts['-o'], 'w', encoding='utf8')
  233. else:
  234. out = sys.stdout
  235. if opts['--full-graph']:
  236. full_graph(opts)
  237. else:
  238. with db.connect() as dbc:
  239. if opts['--stats']:
  240. stats(dbc, out, opts)
  241. elif opts['--records']:
  242. records(dbc, out, opts)
  243. elif opts['--graph']:
  244. graph(dbc, out, opts)
Tip!

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

Comments

Loading...