/
preprocessing.py
300 lines (249 loc) · 11.6 KB
/
preprocessing.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
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
"""
This script runs preprocessing on either a CProject folder or an elasticsearch-dump,
and produces dataframes as input for visualizations.
"""
import pandas as pd
import numpy as np
import os
import pickle
import gzip, bz2
import itertools
import argparse
import config
def get_raw(filename):
with open(filename) as infile:
raw = infile.read()
# the next line needs rewriting as soon as the zenodo-dump conforms to 'records'-format
# [{k:v}, {k:v},...]
rawfacts = pd.read_json('[%s]' % ','.join(raw.splitlines()), orient='records')
return rawfacts
### functions for ingesting from CProject
### functions for preprocessing
def get_dictionary(df):
dicts = df["identifiers"].map(lambda x: x.get("contentmine"))
return dicts.str.extract('([a-z]+)')
def get_wikidataIDs(df):
ids = df["identifiers"].map(lambda x: x.get("wikidata", "None"))
return ids
def clean(df):
for col in df.columns:
if type(df.head(1)[col][0]) == list:
if len(df.head(1)[col][0]) == 1:
notnull = df[df[col].notnull()]
df[col] = notnull[col].map(lambda x: x[0])
def preprocess(rawdatapath):
rawfacts = get_raw(os.path.join(rawdatapath, "facts.json"))
rawmetadata = get_raw(os.path.join(rawdatapath, "metadata.json"))
parsed_facts = rawfacts.join(pd.DataFrame(rawfacts["_source"].to_dict()).T).drop("_source", axis=1)
parsed_metadata = rawmetadata.join(pd.DataFrame(rawmetadata["_source"].to_dict()).T).drop("_source", axis=1)
parsed_metadata.rename(columns={"title":"articleTitle"}, inplace=True)
clean(parsed_facts)
clean(parsed_metadata)
parsed_metadata = parsed_metadata.join(pd.DataFrame(parsed_metadata["journalInfo"].to_dict()).T).drop("journalInfo", axis=1)
clean(parsed_metadata)
parsed_metadata = parsed_metadata.join(pd.DataFrame(parsed_metadata["journal"].to_dict()).T).drop("journal", axis=1)
clean(parsed_metadata)
df = pd.merge(parsed_facts, parsed_metadata, how="inner", on="cprojectID", suffixes=('_fact', '_meta'))
df.rename(columns={"title":"journalTitle"}, inplace=True)
df["sourcedict"] = get_dictionary(df)
df["term"] = df["term"].map(str.lower)
df["wikidataID"] = get_wikidataIDs(df)
df.drop_duplicates("_id_fact", inplace=True)
return df
def get_preprocessed_df(cacheddatapath=None, rawdatapath=None):
try:
with gzip.open(os.path.join(cacheddatapath, "preprocessed_df.pklz"), "rb") as infile:
df = pickle.load(infile)
except:
df = preprocess(rawdatapath)
if rawdatapath is None:
pass
# needs an io error for missing rawdatapath
with gzip.open(os.path.join(cacheddatapath, "preprocessed_df.pklz"), "wb") as outfile:
pickle.dump(df, outfile, protocol=4)
return df
def get_overview_statistics(cacheddatapath):
df = get_preprocessed_df(cacheddatapath)
num_facts = len(df)
num_papers = len(df["pmcid"].unique())
ts = pd.to_datetime(df["firstPublicationDate"]).sort_values()
y_earliest = pd.Timestamp(ts.head(1).values[0]).year
y_latest = pd.Timestamp(ts.tail(1).values[0]).year
m_earliest = pd.Timestamp(ts.head(1).values[0]).month
m_latest = pd.Timestamp(ts.tail(1).values[0]).month
return num_facts, num_papers, y_earliest, m_earliest, y_latest, m_latest
def make_wikidata_dict(cacheddatapath, rawdatapath):
wikidataIDs = {}
df = get_preprocessed_df(cacheddatapath, rawdatapath)
df = df[["term", "wikidataID"]]
for index, row in df.iterrows():
wikidataIDs[row["term"]] = row["wikidataID"]
return wikidataIDs
def get_wikidata_dict(cacheddatapath, rawdatapath):
try:
with gzip.open(os.path.join(cacheddatapath, "wikidata_dict.pklz"), "rb") as infile:
wikidataIDs = pickle.load(infile)
except:
wikidataIDs = make_wikidata_dict(cacheddatapath, rawdatapath)
with gzip.open(os.path.join(cacheddatapath, "wikidata_dict.pklz"), "wb") as outfile:
pickle.dump(wikidataIDs, outfile, protocol=4)
return wikidataIDs
## functions to extract features
def make_series(df, column):
series = df[["firstPublicationDate", "sourcedict", column]]
#series.index = pd.to_datetime(df["firstPublicationDate"])
return series
def get_series(cacheddatapath, rawdatapath, column):
try:
with gzip.open(os.path.join(cacheddatapath, column+"_series.pklz"), "rb") as infile:
series = pickle.load(infile)
except:
df = get_preprocessed_df(cacheddatapath, rawdatapath)
series = make_series(df, column)
with gzip.open(os.path.join(cacheddatapath, column+"_series.pklz"), "wb") as outfile:
pickle.dump(series, outfile, protocol=4)
return series
def count_occurrences(df):
# replace pmcid by doi ideally
groups = df[["pmcid", "term"]].groupby("term").groups
return groups
def get_coocc_pivot(df):
coocc_raw = df[["cprojectID", "term", "sourcedict"]]
coocc_pivot = coocc_raw.pivot_table(index=["sourcedict", 'term'], columns='cprojectID', aggfunc=len)
return coocc_pivot
def count_cooccurrences(df):
coocc_pivot = get_coocc_pivot(df)
labels = coocc_pivot.index
M = np.matrix(coocc_pivot.fillna(0))
C = np.dot(M, M.T)
coocc_features = pd.DataFrame(data=C, index=labels, columns=labels)
return coocc_features
def get_coocc_features(cacheddatapath, rawdatapath):
try:
with bz2.open(os.path.join(cacheddatapath, "coocc_features.pklz2"), "r") as infile:
coocc_features = pickle.load(infile)
except:
df = get_preprocessed_df(cacheddatapath, rawdatapath)
coocc_features = count_cooccurrences(df)
with bz2.BZ2File(os.path.join(cacheddatapath, "coocc_features.pklz2"), "w") as outfile:
pickle.dump(coocc_features, outfile, protocol=4)
return coocc_features
def make_subset(coocc_features, x_axis, y_axis):
logsource = np.log(coocc_features.ix[x_axis][y_axis]+1)
x_sorted = logsource.ix[logsource.sum(axis=1).sort_values(ascending=False).index]
y_sorted = x_sorted.T.ix[x_sorted.T.sum(axis=1).sort_values(ascending=False).index]
logsource = y_sorted.T.ix[:25, :25]
n_cols = len(logsource.columns)
n_rows = len(logsource.index)
df = pd.DataFrame()
df["x"] = list(itertools.chain.from_iterable(list(itertools.repeat(i, times=n_cols)) for i in logsource.index))
df["y"] = list(itertools.chain.from_iterable(list(itertools.repeat(logsource.stack().index.levels[1].values, times=n_rows))))
df["counts"] = logsource.stack().values
df["raw"] = df["counts"].map(np.exp)-1
df.sort_values("counts", ascending=False, inplace=True)
new_axis_factors = logsource.index.values.tolist()
return df, new_axis_factors, new_axis_factors
def prepare_facts(cacheddatapath, rawdatapath):
coocc_features = get_coocc_features(cacheddatapath, rawdatapath)
dictionaries = sorted(coocc_features.index.levels[0])
factsets = {}
for dictionary in dictionaries:
subset = make_subset(coocc_features, dictionary, dictionary)
factsets[(dictionary, dictionary)] = subset
return factsets
def get_coocc_factsets(cacheddatapath, rawdatapath):
try:
with gzip.open(os.path.join(cacheddatapath, "coocc_factsets.pklz"), "rb") as infile:
coocc_factsets = pickle.load(infile)
except:
coocc_factsets = prepare_facts(cacheddatapath, rawdatapath)
with gzip.open(os.path.join(cacheddatapath, "coocc_factsets.pklz"), "wb") as outfile:
pickle.dump(coocc_factsets, outfile, protocol=4)
return coocc_factsets
def get_timeseries_pivot(df):
ts_raw = df[["firstPublicationDate", "term", "sourcedict"]]
ts_pivot = ts_raw.pivot_table(index='firstPublicationDate', columns=["sourcedict", "term"], aggfunc=len)
return ts_pivot
def make_timeseries(df):
ts = get_timeseries_pivot(df)
ts.index = pd.to_datetime(ts.index)
return ts
def get_timeseries_features(cacheddatapath, rawdatapath):
try:
with gzip.open(os.path.join(cacheddatapath, "timeseries_features.pklz"), "rb") as infile:
ts_features = pickle.load(infile)
except:
df = get_preprocessed_df(cacheddatapath, rawdatapath)
ts_features = make_timeseries(df)
with gzip.open(os.path.join(cacheddatapath, "timeseries_features.pklz"), "wb") as outfile:
pickle.dump(ts_features, outfile, protocol=4)
return ts_features
def make_journal_features(df):
journ_raw = df[["firstPublicationDate", "journalTitle", "pmcid", "term"]]
#journ_features = journ_raw.pivot_table(index='firstPublicationDate', columns=["journalTitle"], aggfunc=len)
return journ_raw
def get_journal_features(cacheddatapath, rawdatapath):
try:
with gzip.open(os.path.join(cacheddatapath, "journal_features.pklz"), "rb") as infile:
journ_raw = pickle.load(infile)
except:
df = get_preprocessed_df(cacheddatapath, rawdatapath)
journ_raw = make_journal_features(df)
with gzip.open(os.path.join(cacheddatapath, "journal_features.pklz"), "wb") as outfile:
pickle.dump(journ_raw, outfile, protocol=4)
return journ_raw
def make_distribution_features(df):
dist_raw = df[["firstPublicationDate", "sourcedict"]]
dist_features = dist_raw.pivot_table(index="firstPublicationDate", columns=["sourcedict"], aggfunc=len)
return dist_features
def get_distribution_features(cacheddatapath, rawdatapath):
try:
with gzip.open(os.path.join(cacheddatapath, "dist_features.pklz"), "rb") as infile:
dist_features = pickle.load(infile)
except:
df = get_preprocessed_df(cacheddatapath, rawdatapath)
dist_features = make_distribution_features(df)
with gzip.open(os.path.join(cacheddatapath, "dist_features.pklz"), "wb") as outfile:
pickle.dump(dist_features, outfile, protocol=4)
return dist_features
def get_single_fact(df, fact):
fact_df = df[df["term"] == fact]
return fact_df
def get_facts_from_list(df, factlist):
return pd.concat((get_single_fact(df, f) for f in factlist))
####
def ingest_elasticdump(path):
pass
def ingest_cproject(path):
pass
#####
def main(args):
if args.raw:
rawdatapath = args.raw
else:
rawdatapath = config.rawdatapath
if args.cache:
cacheddatapath = args.cache
else:
cacheddatapath = config.cacheddatapath
if args.results:
resultspath = args.results
else:
resultspath = config.resultspath
get_preprocessed_df(cacheddatapath, rawdatapath)
get_series(cacheddatapath, rawdatapath, "term")
get_coocc_features(cacheddatapath, rawdatapath)
get_distribution_features(cacheddatapath, rawdatapath)
get_timeseries_features(cacheddatapath, rawdatapath)
get_coocc_factsets(cacheddatapath, rawdatapath)
get_wikidata_dict(cacheddatapath, rawdatapath)
get_journal_features(cacheddatapath, rawdatapath)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='ingest and preprocess contentmine facts from elasticsearch dumps and CProjects')
parser.add_argument('--raw', dest='raw', help='relative or absolute path of the raw data folder', required=True)
parser.add_argument('--cache', dest='cache', help='relative or absolute path of the cached data folder', required=True)
parser.add_argument('--results', dest='results', help='relative or absolute path of the results folder')
parser.add_argument('--elastic', dest='elastic', help='flag if input is elastic-dump', action="store_true")
parser.add_argument('--cproject', dest='cproject', help='flag if input is cproject', action="store_true")
args = parser.parse_args()
main(args)