-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmetafilter.py
264 lines (195 loc) · 7.94 KB
/
metafilter.py
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
# metafilter.py
# Functions that process metadata for parallel_crossvalidate.py
import csv, random
def dirty_pairtree(htid):
period = htid.find('.')
prefix = htid[0:period]
postfix = htid[(period+1): ]
if '=' in postfix:
postfix = postfix.replace('+',':')
postfix = postfix.replace('=','/')
dirtyname = prefix + "." + postfix
return dirtyname
def forceint(astring):
try:
intval = int(astring)
except:
intval = 0
return intval
def get_metadata(classpath, volumeIDs, excludeif, excludeifnot, excludebelow, excludeabove):
'''
As the name would imply, this gets metadata matching a given set of volume
IDs. It returns a dictionary containing only those volumes that were present
both in metadata and in the data folder.
It also accepts four dictionaries containing criteria that will exclude volumes
from the modeling process.
'''
print(classpath)
metadict = dict()
with open(classpath, encoding = 'utf-8') as f:
reader = csv.DictReader(f)
anonctr = 0
for row in reader:
volid = dirty_pairtree(row['docid'])
theclass = row['recept'].strip()
# I've put 'remove' in the reception column for certain
# things that are anomalous.
if theclass == 'remove':
continue
bail = False
for key, value in excludeif.items():
if row[key] == value:
bail = True
for key, value in excludeifnot.items():
if row[key] != value:
bail = True
for key, value in excludebelow.items():
if forceint(row[key]) < value:
bail = True
for key, value in excludeabove.items():
if forceint(row[key]) > value:
bail = True
if bail:
continue
birthdate = forceint(row['birth'])
pubdate = forceint(row['inferreddate'])
gender = row['gender'].rstrip()
nation = row['nationality'].rstrip()
#if pubdate >= 1880:
#continue
if nation == 'ca':
nation = 'us'
elif nation == 'ir':
nation = 'uk'
# I hope none of my Canadian or Irish friends notice this.
notes = row['notes'].lower()
author = row['author']
if len(author) < 1 or author == '<blank>':
author = "anonymous" + str(anonctr)
anonctr += 1
title = row['title']
canon = row['canon']
# I'm creating two distinct columns to indicate kinds of
# literary distinction. The reviewed column is based purely
# on the question of whether this work was in fact in our
# sample of contemporaneous reviews. The obscure column incorporates
# information from post-hoc biographies, which trumps
# the question of reviewing when they conflict.
if theclass == 'random':
obscure = 'obscure'
reviewed = 'not'
elif theclass == 'reviewed':
obscure = 'known'
reviewed = 'rev'
elif theclass == 'addcanon':
obscure = 'known'
reviewed = 'addedbecausecanon'
else:
print("Missing class" + theclass)
if notes == 'well-known':
obscure = 'known'
if notes == 'obscure':
obscure = 'obscure'
if canon == 'y':
if theclass == 'addcanon':
actually = 'Norton, added'
else:
actually = 'Norton, in-set'
elif reviewed == 'rev':
actually = 'reviewed'
else:
actually = 'random'
metadict[volid] = dict()
metadict[volid]['reviewed'] = reviewed
metadict[volid]['obscure'] = obscure
metadict[volid]['pubdate'] = pubdate
metadict[volid]['birthdate'] = birthdate
metadict[volid]['gender'] = gender
metadict[volid]['nation'] = nation
metadict[volid]['author'] = author
metadict[volid]['title'] = title
metadict[volid]['canonicity'] = actually
metadict[volid]['pubname'] = row['pubname']
metadict[volid]['firstpub'] = forceint(row['firstpub'])
# These come in as dirty pairtree; we need to make them clean.
cleanmetadict = dict()
allidsinmeta = set([x for x in metadict.keys()])
allidsindir = set([dirty_pairtree(x) for x in volumeIDs])
missinginmeta = len(allidsindir - allidsinmeta)
missingindir = len(allidsinmeta - allidsindir)
print("We have " + str(missinginmeta) + " volumes in missing in metadata, and")
print(str(missingindir) + " volumes missing in the directory.")
print(allidsinmeta - allidsindir)
for anid in volumeIDs:
dirtyid = dirty_pairtree(anid)
if dirtyid in metadict:
cleanmetadict[anid] = metadict[dirtyid]
return cleanmetadict
def sort_by_proximity(idlist, dictionary, target):
proximities = list()
random.shuffle(idlist)
for anid in idlist:
date = dictionary[anid]['pubdate']
proximities.append(abs(target - date))
decorated = list(zip(proximities, idlist))
decorated.sort()
sortedlist = [x[1] for x in decorated]
return sortedlist
def label_classes(metadict, category2sorton, positive_class, sizecap):
''' This takes as input the metadata dictionary generated
by get_metadata. It subsets that dictionary into a
positive class and a negative class. Instances that belong
to neither class get ignored.
'''
all_instances = set([x for x in metadict.keys()])
# The first stage is to find positive instances.
all_positives = set()
for key, value in metadict.items():
if value[category2sorton] == positive_class:
all_positives.add(key)
all_negatives = all_instances - all_positives
iterator = list(all_negatives)
for item in iterator:
if metadict[item]['reviewed'] == 'addedbecausecanon':
all_negatives.remove(item)
if sizecap > 0 and len(all_positives) > sizecap:
positives = random.sample(all_positives, sizecap)
else:
positives = list(all_positives)
print(len(all_positives))
# If there's a sizecap we also want to ensure classes have
# matching sizes and roughly equal distributions over time.
numpositives = len(all_positives)
if sizecap > 0 and len(all_negatives) > numpositives:
if not 'date' in category2sorton:
available_negatives = list(all_negatives)
negatives = list()
for anid in positives:
date = metadict[anid]['pubdate']
available_negatives = sort_by_proximity(available_negatives, metadict, date)
selected_id = available_negatives.pop(0)
negatives.append(selected_id)
else:
# if we're dividing classes by date, we obvs don't want to
# ensure equal distributions over time.
negatives = random.sample(all_negatives, sizecap)
else:
negatives = list(all_negatives)
# Now we have two lists of ids.
IDsToUse = set()
classdictionary = dict()
print()
print("We have " + str(len(positives)) + " positive, and")
print(str(len(negatives)) + " negative instances.")
for anid in positives:
IDsToUse.add(anid)
classdictionary[anid] = 1
for anid in negatives:
IDsToUse.add(anid)
classdictionary[anid] = 0
for key, value in metadict.items():
if value['reviewed'] == 'addedbecausecanon':
IDsToUse.add(key)
classdictionary[key] = 0
# We add the canon supplement, but don't train on it.
return IDsToUse, classdictionary