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
|
- """
- Inspect a book cluster.
- Usage:
- inspect-idgraph.py [options] --stats
- inspect-idgraph.py [options] --records CLUSTER
- inspect-idgraph.py [options] --graph CLUSTER
- inspect-idgraph.py [options] --full-graph
- Options:
- -o FILE
- Write output to FILE
- -f, --format FMT
- Output in format FMT.
- CLUSTER
- The cluster number to inspect.
- """
- import sys
- import re
- import json
- from xml.etree import ElementTree as etree
- from textwrap import dedent as d
- from docopt import docopt
- import pandas as pd
- from bookdata import tracking, db, script_log
- from bookdata.graph import GraphLoader
- class GMLWriter:
- def __init__(self, out):
- self.output = out
- self._n_attrs = set(['id'])
- def _p(self, code, *args):
- print(code.format(*args), file=self.output)
- def node_attr(self, name):
- self._n_attrs.add(name)
- def start(self):
- self._p('graph [')
- self._p(' directed 0')
- def finish(self):
- self._p(']')
- def node(self, **attrs):
- self._p(' node [')
- for k, v in attrs.items():
- if k not in self._n_attrs:
- raise RuntimeError('unknown node attribute ' + k)
- if k == 'label':
- v = str(v)
- if v is not None:
- self._p(' {} {}', k, json.dumps(v))
- self._p(' ]')
- def edge(self, **attrs):
- self._p(' edge [')
- for k, v in attrs.items():
- if v is not None:
- self._p(' {} {}', k, json.dumps(v))
- self._p(' ]')
- class GraphMLWriter:
- _g_started = False
- def __init__(self, out):
- self.output = out
- self.tb = etree.TreeBuilder()
- self._ec = 0
- def node_attr(self, name, type='string'):
- self.tb.start('key', {
- 'id': name,
- 'for': 'node',
- 'attr.name': name,
- 'attr.type': type
- })
- self.tb.end('key')
- def start(self):
- self.tb.start('graphml', {
- 'xmlns': 'http://graphml.graphdrawing.org/xmlns',
- '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': d('''
- http://graphml.graphdrawing.org/xmlns
- http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd
- ''').strip(),
- })
- def finish(self):
- self.tb.end('graph')
- self.tb.end('graphml')
- elt = self.tb.close()
- tree = etree.ElementTree(elt)
- tree.write(self.output, encoding='unicode')
- def node(self, id, **attrs):
- if not self._g_started:
- self.tb.start('graph', {
- 'edgedefault': 'undirected'
- })
- self._g_started = True
- self.tb.start('node', {
- 'id': id
- })
- for k, v in attrs.items():
- if v is not None:
- self.tb.start('data', {'key': k})
- self.tb.data(str(v))
- self.tb.end('data')
- self.tb.end('node')
- def edge(self, source, target):
- self._ec += 1
- eid = self._ec
- self.tb.start('edge', {
- 'id': f'e{eid}',
- 'source': source,
- 'target': target
- })
- self.tb.end('edge')
- def stats(dbc, out, opts):
- "Compute statistics of the clustering"
- with dbc.cursor() as cur:
- _log.info('getting aggregate stats')
- cur.execute('SELECT COUNT(*), MAX(isbns) FROM cluster_stats')
- n_clusters, m_isbns = cur.fetchone()
- print(f'Clusters: {n_clusters}', file=out)
- print(f'Largest has {m_isbns} ISBNs', file=out)
- _log.info('computing top stats')
- print('Top clusters by size:', file=out)
- top = pd.read_sql('SELECT * FROM cluster_stats ORDER BY isbns DESC LIMIT 10', dbc)
- print(top.fillna(0), file=out)
- def records(dbc, out, opts):
- "Dump ISBN records from a cluster to a CSV file"
- cluster = opts['CLUSTER']
- bc_recs = []
- _log.info('inspecting cluster %s', cluster)
- _log.info('fetching LOC records')
- bc_recs.append(pd.read_sql(f'''
- SELECT isbn, 'LOC' AS source, rec_id AS record, NULL AS work, title
- FROM locmds.book_rec_isbn
- JOIN isbn_id USING (isbn_id)
- JOIN isbn_cluster USING (isbn_id)
- LEFT JOIN locmds.book_title USING (rec_id)
- WHERE cluster = {cluster}
- ''', dbc))
- _log.info('fetching OL records')
- bc_recs.append(pd.read_sql(f'''
- SELECT isbn, 'OL' AS source,
- edition_id AS record, work_id AS work,
- title
- FROM ol.isbn_link
- JOIN isbn_id USING (isbn_id)
- JOIN isbn_cluster USING (isbn_id)
- LEFT JOIN ol.edition_title USING (edition_id)
- WHERE cluster = {cluster}
- ''', dbc))
- _log.info('fetching GR records')
- bc_recs.append(pd.read_sql(f'''
- SELECT isbn, 'GR' AS source,
- gr_book_id AS record, gr_work_id AS work,
- work_title
- FROM gr.book_isbn
- JOIN isbn_id USING (isbn_id)
- JOIN isbn_cluster USING (isbn_id)
- JOIN gr.book_ids USING (gr_book_id)
- LEFT JOIN gr.work_title USING (gr_work_id)
- WHERE cluster = {cluster}
- ''', dbc))
- bc_recs = pd.concat(bc_recs, ignore_index=True)
- bc_recs.sort_values('isbn', inplace=True)
- _log.info('fetched %d records', len(bc_recs))
- bc_recs.to_csv(out, index=False)
- def graph(dbc, out, opts):
- cluster = opts['CLUSTER']
- _log.info('exporting graph for cluster %s', cluster)
- format = opts.get('--format', 'gml')
- if format == 'gml':
- gw = GMLWriter(out)
- elif format == 'graphml':
- gw = GraphMLWriter(out)
- else:
- raise ValueError('invalid format ' + format)
- gw.start()
- gw.node_attr('label')
- gw.node_attr('category')
- gw.node_attr('title')
- gl = GraphLoader()
- with dbc.cursor() as cur:
- gl.set_cluster(cluster, dbc)
- _log.info('fetching ISBNs')
- cur.execute(gl.q_isbns())
- for iid, isbn in cur:
- gw.node(id=f'i{iid}', label=isbn, category='ISBN')
- _log.info('fetching LOC records')
- cur.execute(gl.q_loc_nodes(True))
- for rid, title in cur:
- gw.node(id=f'l{rid}', label=rid, category='LOC', title=title)
- _log.info('fetching LOC ISBN links')
- cur.execute(gl.q_loc_edges())
- for iid, rid in cur:
- gw.edge(source=f'l{rid}', target=f'i{iid}')
- _log.info('fetching OL editions')
- cur.execute(gl.q_ol_edition_nodes(True))
- for eid, ek, e_title in cur:
- gw.node(id=f'ole{eid}', label=ek, category='OLE', title=e_title)
- _log.info('fetching OL works')
- cur.execute(gl.q_ol_work_nodes(True))
- for wid, wk, w_title in cur:
- gw.node(id=f'olw{wid}', label=wk, category='OLW', title=w_title)
- _log.info('fetching OL ISBN edges')
- cur.execute(gl.q_ol_edition_edges())
- for iid, eid in cur:
- gw.edge(source=f'ole{eid}', target=f'i{iid}')
- _log.info('fetching OL edition/work edges')
- cur.execute(gl.q_ol_work_edges())
- for eid, wid in cur:
- gw.edge(source=f'ole{eid}', target=f'olw{wid}')
- _log.info('fetching GR books')
- cur.execute(gl.q_gr_book_edges())
- bids = set()
- for iid, bid in cur:
- if bid not in bids:
- gw.node(id=f'grb{bid}', label=bid, category='GRB')
- bids.add(bid)
- gw.edge(source=f'grb{bid}', target=f'i{iid}')
- _log.info('fetching GR works')
- cur.execute(gl.q_gr_work_nodes(True))
- for wid, title in cur:
- gw.node(id=f'grw{wid}', label=wid, category='GRW', title=title)
- _log.info('fetching GR work/edition edges')
- cur.execute(gl.q_gr_work_edges())
- for bid, wid in cur:
- gw.edge(source=f'grw{wid}', target=f'grb{bid}')
- gw.finish()
- _log.info('exported graph')
- def full_graph(opts):
- gl = GraphLoader()
- with db.engine().connect() as cxn:
- g = gl.load_minimal_graph(cxn)
- ofn = opts['-o']
- _log.info('saving graph to %s', ofn)
- g.save(ofn)
- _log = script_log(__name__)
- opts = docopt(__doc__)
- if opts['-o']:
- out = open(opts['-o'], 'w', encoding='utf8')
- else:
- out = sys.stdout
- if opts['--full-graph']:
- full_graph(opts)
- else:
- with db.connect() as dbc:
- if opts['--stats']:
- stats(dbc, out, opts)
- elif opts['--records']:
- records(dbc, out, opts)
- elif opts['--graph']:
- graph(dbc, out, opts)
|