-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
1397 lines (1191 loc) · 54.6 KB
/
database.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from lxml import etree
import pandas as pd
from sqlite3 import Connection, connect
from utils import log
from datetime import datetime
import os
import ast
import re
import glob
import pathlib
if not os.path.exists("csv/db"):
os.makedirs("csv/db")
if not os.path.exists("csv/GenderAPI/unprocessed"):
os.makedirs("csv/GenderAPI/unprocessed")
DB = "gap.db"
# For preventing pandas from interpreting Namibia's country code 'NA' as NaN value
NA_VALUES = [
"''",
"#N/A",
"#N/A N/A",
"#NA",
"-1.#IND",
"-1.#QNAN",
"-NaN",
"-nan",
"1.#IND",
"1.#QNAN",
"<NA>",
"N/A",
"NULL",
"NaN",
"n/a",
"nan",
"null",
]
COUNTRY_VARIATIONS = pd.read_csv("general_data/country_name_variations.csv", keep_default_na=False, na_values=NA_VALUES)
COUNTRIES = pd.read_csv("general_data/countries_unique.csv", keep_default_na=False, na_values=NA_VALUES)
CONTINENTS = pd.read_csv("general_data/continents.csv", keep_default_na=False, na_values=NA_VALUES)
# The, Zu, De, Den, Der, Del, Ul, Al, Da, El, Des, Di, Ten, Ter, Van, Von, Zur, Du, Das, Le actually are first names
NO_MIDDLE_NAMES = [
"van",
"von",
"zur",
"aus",
"dem",
"den",
"der",
"del",
"de",
"la",
"La",
"las",
"le",
"los",
"ul",
"al",
"da",
"el",
"vom",
"Vom",
"auf",
"Auf",
"des",
"di",
"dos",
"du",
"ten",
"ter",
"van't",
"Van't",
"of",
"het",
"the",
"af",
"til",
"zu",
"do",
"das",
"Sri",
"Si",
"della",
"Della",
"degli",
"Degli",
"Mc",
"Mac",
"und",
"on",
"in't",
"i",
"ka",
"t",
]
def main():
conn = connect(DB)
drop(conn, "PublicationAuthor")
drop(conn, "Publication")
drop(conn, "Venue")
drop(conn, "AuthorName")
drop(conn, "Author")
drop(conn, "GenderAPIResults")
drop(conn, "Affiliation")
drop(conn, "Country")
drop(conn, "AllTogether")
drop(conn, "GeneralStatistics")
drop(conn, "Filters")
drop_index(conn, "all_together_index")
# Do not enable the foreign key constraint checks before dropping the tables as this would make the dropping process
# incredibly slow
enable_foreign_key_constraints(conn)
fill_countries(conn, to_csv=True)
fill_affiliations(conn, to_csv=True)
fill_gender_api_results(conn)
fill_authors(conn, to_csv=True) # Internally triggers fill_author_names()
venue = fill_venues(conn, to_csv=True)
fill_publications(conn, to_csv=True) # Internally triggers fill_publication_author_relationships()
count_publications_per_venue(conn)
fill_all_together(conn)
clean_up_venues(conn, venue)
# Generate a csv file of first names with unknown gender that can be passed to the GenderAPI
get_unknown_first_names(conn)
create_indices(conn)
insert_research_areas(conn)
fill_statistics(conn)
fill_filters(conn)
def drop(conn, table):
conn.execute(f"DROP TABLE IF EXISTS {table};")
def drop_index(conn, index):
conn.execute(f"DROP INDEX IF EXISTS {index};")
def enable_foreign_key_constraints(conn):
conn.execute("PRAGMA foreign_keys = ON;")
def fill_countries(conn: Connection, to_csv=False):
"""
Get list of countries with unique names and country codes from countries_unique.csv, add continents and save
everything to table 'Country' by using the given connection conn.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/Country.csv, too.
:return:
"""
log("Progress of filling countries started")
Country = COUNTRIES.merge(CONTINENTS, on="Code")
log("Continents to country list added")
# Save countries to database
Country.rename({"Country": "DisplayName", "Code": "CountryCode"}, axis="columns", inplace=True)
if to_csv:
Country.to_csv("csv/db/Country.csv", index=False)
conn.execute(
"""
CREATE TABLE Country(
CountryCode TEXT PRIMARY KEY NOT NULL,
DisplayName TEXT NOT NULL,
Continent TEXT NOT NULL
);
"""
)
Country.to_sql("Country", con=conn, if_exists="append", index=False)
log("Countries written to database")
def fill_affiliations(conn: Connection, to_csv=False):
"""
Parse unique affiliations from dblp.xml, extract their country (usually given at the end of an affiliation string),
identify their country code and save everything to table 'Affiliation' by using the given connection conn.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/Affiliation.csv, too.
"""
log("Progress of filling affiliations started")
context = etree.iterparse(source="dblp/dblp.xml", dtd_validation=True, load_dtd=True)
# Extract affiliations from dblp xml
raw_affiliations = set()
for action, elem in context:
if elem.tag == "note" and elem.get("type") == "affiliation" and elem.text is not None:
# Remove leading and trailing spaces
raw_affiliations.add(elem.text.strip())
elem.clear()
log("Affiliations from dblp extracted")
# Extract country from affiliations and find country code
affiliations = []
for affiliation in raw_affiliations:
affiliations.append(_assign_country_code(affiliation))
log("Countries to affiliations added")
# Save affiliations to database
Affiliation = pd.DataFrame(affiliations, columns=["FullAffiliation", "CountryCode"])
Affiliation.sort_values("FullAffiliation", inplace=True, ignore_index=True)
if to_csv:
Affiliation.to_csv("csv/db/Affiliation.csv", index=False)
conn.execute(
"""
CREATE TABLE Affiliation(
AffiliationID INT NOT NULL PRIMARY KEY,
FullAffiliation TEXT NOT NULL UNIQUE,
Type TEXT,
CountryCode TEXT,
FOREIGN KEY(CountryCode) REFERENCES Country(CountryCode) ON DELETE CASCADE
);
"""
)
Affiliation.to_sql("Affiliation", con=conn, if_exists="append", index_label="AffiliationID")
log("Affiliations written to database")
def fill_gender_api_results(
conn: Connection,
gapi_path="csv/GenderAPI/",
):
"""
Read csv file given under gapi_path or, if it's a directory, read each csv file located there, concatenate them,
drop duplicates and save everything to table 'GenderAPIResults' by using the given connection conn.
This function assumes all csv files in gapi_path to have semicolons as separators as that's the way they are
returned by the GenderAPI.
:param conn: sqlite3.Connection
:param gapi_path: relative path to csv file(s) returned by the GenderAPI
"""
log("Progress of filling GenderAPI results started")
if ".csv" in gapi_path:
GenderAPIResults = pd.read_csv(gapi_path, sep=";")
else:
glob_path = os.path.join(gapi_path, "*.csv")
GenderAPIResults = pd.DataFrame()
for csv_file in glob.glob(glob_path):
GenderAPIResults = pd.concat([GenderAPIResults, pd.read_csv(csv_file, sep=";")])
# Remove duplicates
GenderAPIResults.drop_duplicates(inplace=True)
# Rename columns to wanted sql columns
GenderAPIResults.rename(
columns={
"first_name": "FirstName",
"ga_first_name": "GaFirstName",
"ga_gender": "GaGender",
"ga_accuracy": "GaAccuracy",
"ga_samples": "GaSamples",
},
inplace=True,
)
# Some names that are now known by GenderAPI were unknown in previous requests
# These names occur several times in GenderAPIResults.FirstName and the entries with NaN values in every column but
# FirstName needs to be deleted
# Thus, we sort first such that entries with the highest power (GaSamples) are listed before their unknown
# duplicates and then drop any but the first entry for each duplicated FirstName
if not GenderAPIResults.empty:
GenderAPIResults.sort_values(by=["FirstName", "GaSamples"], ascending=[True, False], inplace=True)
GenderAPIResults.drop_duplicates(subset=["FirstName"], keep="first", inplace=True)
conn.execute(
"""
CREATE TABLE GenderAPIResults(
FirstName TEXT NOT NULL PRIMARY KEY,
GaFirstName TEXT,
GaGender TEXT,
GaAccuracy INT,
GaSamples INT
);
"""
)
GenderAPIResults.to_sql("GenderAPIResults", con=conn, if_exists="append", index=False)
log("GenderAPI results written to database")
def fill_authors(conn: Connection, to_csv=False):
"""
Extract persons from dblp's www entries with title 'Home Page' (See https://dblp.org/faq/1474690.html.)
Expect to find 'csv/www.csv', a csv file of www entries, generated by dblp_parser.py. Use first (full) name in
column author as DBLPName and triggers propagation of table AuthorName with the remaining full names in list. Pick
first affiliation only for a person in case multiple ones are listed and not specified further (See
_prepare_affiliations() for details). Extracts Orcid and GoogleScholar pages from column url and puts the remaining
ones to a separate column named Homepages. Determine the gender of each author (see _determine_genders() for
details) and also save the first name that lead to this decision. Save everything to table 'Author' by using the
given connection conn.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/AuthorName.csv, too.
"""
log("Progress of filling authors started")
www = pd.read_csv("csv/www.csv")
# Drop modification date, entries not referring to actual authors and title (turned useless)
www.drop(["mdate"], axis="columns", inplace=True)
www = www[www.title.isin(["Home Page", "Home Page ", "Home Page\nHome Page"])]
www.drop(["title"], axis="columns", inplace=True)
www = www[www.author.notnull()]
# Extract name dblp uses on a person's page and corresponding alternative names
www["DBLPName"], alternative_names = _separate_names(www.author)
# Extract a person's first affiliation that is not specified further (See _prepare_affiliations() for details)
www["affiliation"] = _prepare_affiliations(www[["key", "note"]])
www.drop(columns=["note"], inplace=True)
# Get AffiliationID from table Affiliation by mapping 'affiliation' with Affiliation.FullAffiliation
Affiliation = pd.read_sql("SELECT AffiliationID, FullAffiliation FROM Affiliation", con=conn)
Author = www.merge(Affiliation, how="left", left_on="affiliation", right_on="FullAffiliation").astype(
{"AffiliationID": "Int64"}
)
Author.drop(columns=["FullAffiliation", "affiliation"], inplace=True)
log("AffiliationIDs to authors added")
# Get a person's web pages by extracting Orcid and GoogleScholar pages from the urls and fill column Homepages with
# remaining urls separated by newlines
Author["OrcidPage"], Author["GoogleScholarPage"], Author["Homepages"] = zip(
*Author.url.apply(lambda x: _prepare_urls(x))
)
Author.drop(columns=["url"], inplace=True)
log("Web pages of authors extracted and added")
# Determine genders
log("Gender determination process started")
Author["Gender"], Author["FirstName"] = _determine_genders(Author.DBLPName, alternative_names, conn)
# Groups should not have a gender
Author.loc[Author.publtype == "group", ["Gender", "FirstName"]] = "unknown", None
log("Genders of authors determined")
# Rename columns to wanted sql columns
Author.rename(columns={"key": "AuthorID", "publtype": "Type"}, inplace=True)
Author.drop(columns=["author"], inplace=True)
# Save authors to database
if to_csv:
Author.to_csv("csv/db/Author.csv", index=False)
conn.execute(
"""
CREATE TABLE Author(
AuthorID TEXT NOT NULL PRIMARY KEY,
DBLPName TEXT NOT NULL UNIQUE,
Type TEXT,
OrcidPage TEXT,
GoogleScholarPage TEXT,
Homepages TEXT,
AffiliationID INT,
Gender TEXT,
FirstName TEXT,
FOREIGN KEY(AffiliationID) REFERENCES Affiliation(AffiliationID) ON DELETE CASCADE
);
"""
)
Author.to_sql("Author", con=conn, if_exists="append", index=False)
log("Authors written to database")
# Trigger filling the table AuthorName
fill_author_names(alternative_names, conn, to_csv=to_csv)
def fill_author_names(author_names, conn: Connection, to_csv=False):
"""
Save the given author_names to table 'AuthorName' by using the given connection conn.
:param author_names: pd.DataFrame, being the return value 'alternative_names' of function _separate_names() with
columns 'DBLPName' and 'FullName'.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/AuthorName.csv, too.
"""
log("Progress of filling author names started")
if to_csv:
author_names.to_csv("csv/db/AuthorName.csv", index=False)
conn.execute(
"""
CREATE TABLE AuthorName(
AuthorNameID INT NOT NULL PRIMARY KEY,
DBLPName TEXT NOT NULL,
FullName TEXT NOT NULL UNIQUE,
FOREIGN KEY(DBLPName) REFERENCES Author(DBLPName) ON DELETE CASCADE
);
"""
)
author_names.to_sql("AuthorName", con=conn, if_exists="append", index_label="AuthorNameID")
log("Author names written to database")
def fill_venues(conn: Connection, to_csv=False):
"""
Expect to find 'csv/articles.csv' and 'csv/inproceedings.csv', csv files of article entries and inproceedings
entries from dblp.xml, generated by dblp_parser.py. Extract the venue's (short) names from inproceedings' attribute
'booktitle' and from article's attribute 'journal'. Add the column Type either containing 'Journal' or
'Conference | Workshop' (as dblp does not distinguish between conferences and workshops). Add the column
ResearchArea to be filled later. Save everything to table 'Venue' by using the given connection conn.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/Venue.csv, too.
"""
log("Progress of filling venues started")
inproceedings = pd.read_csv("csv/inproceedings.csv", usecols=["booktitle"])
articles = pd.read_csv("csv/article.csv", usecols=["journal"])
# Extract conference's and workshop's names
conferences = pd.DataFrame()
conferences["Name"] = inproceedings.booktitle.drop_duplicates().sort_values()
conferences["Type"] = "Conference | Workshop"
log("Conference's and workshop's names extracted")
# Extract journal's names
journals = pd.DataFrame()
journals["Name"] = articles.journal.drop_duplicates().sort_values()
journals["Type"] = "Journal"
log("Journals's names extracted")
Venue = pd.concat([conferences, journals])
Venue.reset_index(drop=True, inplace=True)
Venue = Venue[~Venue.Name.isnull()]
conn.execute(
"""
CREATE TABLE Venue(
VenueID INT NOT NULL PRIMARY KEY,
Name TEXT NOT NULL,
Type TEXT NOT NULL,
ResearchArea TEXT,
NumOfPublications INT
);
"""
)
Venue.to_sql("Venue", con=conn, if_exists="append", index_label="VenueID")
log("Venues written to database")
if to_csv:
Venue.to_csv("csv/db/Venue.csv", index=False)
log("Publication counts added to Database")
return Venue
def fill_publications(conn: Connection, to_csv=False):
"""
Extract publications from dblp's inproceedings, article, proceedings, book, incollection, phdthesis and masterthesis
entries. Expect to find 'csv/article.csv', 'csv/book.csv', csv/incollection.csv', 'csv/inproceedings.csv',
'csv/mastersthesis.csv', 'csv/phdthesis.csv' and csv/proceedings.csv', csv files generated by dblp_parser.py.
Use the entries dblp keys as 'PublicationID'. Use the title, pages and year to fill the corresponding columns. Use
the entries' 'publtype' for column 'PublicationType' (empty for regular publications). Add a column 'Type'
containing the entries' name (e.g. 'Article' or 'Inproceedings'). Use proceedings' and inproceedings' booktitle and
article's journal as their venue and add a reference to the venue in column VenueID. Save everything to table
'Publication' by using the given connection conn. Trigger propagation of table PublicationAuthor containing the
m-to-n-relationship entries for the relationships between Publication and Author.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/AuthorName.csv, too.
"""
log("Progress of filling publications started")
# Read all the needed csv files and prepare for publication extraction
inproceedings = pd.read_csv(
"csv/inproceedings.csv",
dtype={"year": int, "publtype": str, "pages": str},
usecols=["key", "title", "booktitle", "pages", "year", "publtype", "author"],
)
articles = pd.read_csv(
"csv/article.csv",
usecols=["key", "title", "journal", "pages", "year", "publtype", "author"],
dtype={"year": float, "publtype": str, "pages": str},
)
# Read column year as float due to NaN values and then convert it to int
articles.year = articles.year.astype(pd.Int64Dtype())
proceedings = pd.read_csv(
"csv/proceedings.csv",
usecols=["key", "title", "booktitle", "year", "publtype", "editor"],
dtype={"year": int, "publtype": str},
)
books = pd.read_csv(
"csv/book.csv",
usecols=["key", "title", "year", "publtype", "author"],
dtype={"year": int, "publtype": str},
)
incollections = pd.read_csv(
"csv/incollection.csv",
usecols=["key", "title", "pages", "year", "publtype", "author"],
dtype={"year": int, "publtype": str, "pages": str},
)
phdtheses = pd.read_csv(
"csv/phdthesis.csv",
usecols=["key", "title", "pages", "year", "publtype", "author"],
dtype={"year": object, "publtype": str, "pages": str},
)
# Read column year as object due to multiple years separated by newlines, pick the maximum and convert to int
phdtheses.year = phdtheses.year.apply(lambda x: max(x.split("\n"))).astype(pd.Int64Dtype())
mastertheses = pd.read_csv(
"csv/mastersthesis.csv",
usecols=["key", "title", "year", "author"],
dtype={"year": int},
)
# Use different queries and request by Type as there are some journals and conferences with the same name
Venue_conf = pd.read_sql("SELECT VenueID, Name FROM Venue where Type = 'Conference | Workshop'", con=conn)
Venue_journal = pd.read_sql("SELECT VenueID, Name FROM Venue where Type = 'Journal'", con=conn)
# Prepare inproceedings
inproceedings.rename(
inplace=True,
columns={
"key": "PublicationID",
"title": "Title",
"booktitle": "Venue",
"pages": "Pages",
"year": "Year",
"publtype": "PublicationType",
},
)
inproceedings["Type"] = "Inproceedings"
inproceedings["VenueID"] = inproceedings.merge(Venue_conf, how="left", left_on="Venue", right_on="Name").astype(
{"VenueID": "Int64"}
)["VenueID"]
inproceedings.drop(columns=["Venue"], inplace=True)
# Prepare articles
articles.rename(
inplace=True,
columns={
"key": "PublicationID",
"title": "Title",
"journal": "Venue",
"pages": "Pages",
"year": "Year",
"publtype": "PublicationType",
},
)
articles["Type"] = "Article"
articles["VenueID"] = articles.merge(Venue_journal, how="left", left_on="Venue", right_on="Name").astype(
{"VenueID": "Int64"}
)["VenueID"]
articles.drop(columns=["Venue"], inplace=True)
# Prepare proceedings
proceedings.rename(
inplace=True,
columns={
"key": "PublicationID",
"title": "Title",
"booktitle": "Venue",
"year": "Year",
"publtype": "PublicationType",
"editor": "author",
},
)
proceedings["Type"] = "Proceedings"
proceedings["VenueID"] = proceedings.merge(Venue_conf, how="left", left_on="Venue", right_on="Name").astype(
{"VenueID": "Int64"}
)["VenueID"]
proceedings.drop(columns=["Venue"], inplace=True)
# Prepare books
books.rename(
inplace=True,
columns={
"key": "PublicationID",
"title": "Title",
"year": "Year",
"publtype": "PublicationType",
},
)
books["Type"] = "Book"
# Prepare incollections (chapters of books)
incollections.rename(
inplace=True,
columns={
"key": "PublicationID",
"title": "Title",
"year": "Year",
"pages": "Pages",
"publtype": "PublicationType",
},
)
incollections["Type"] = "Incollection"
# Prepare phdtheses
phdtheses.rename(
inplace=True,
columns={
"key": "PublicationID",
"title": "Title",
"year": "Year",
"pages": "Pages",
"publtype": "PublicationType",
},
)
phdtheses["Type"] = "PhD Thesis"
# Prepare mastertheses
mastertheses.rename(inplace=True, columns={"key": "PublicationID", "title": "Title", "year": "Year"})
mastertheses["Type"] = "Master Thesis"
Publication = pd.concat(
[
inproceedings,
articles,
proceedings,
books,
incollections,
phdtheses,
mastertheses,
]
)
publications_with_authors = Publication[["PublicationID", "author"]]
Publication["AuthorCount"] = Publication.author.apply(lambda x: len(x.split("\n")) if pd.notnull(x) else 0)
Publication.drop(columns=["author"], inplace=True)
# Extract actual title if additional title information like bibtex are given via dict
Publication.Title = Publication.Title.apply(lambda x: _extract(x, "text"))
if to_csv:
Publication.to_csv("csv/db/Publication.csv", index=False)
conn.execute(
"""
CREATE TABLE Publication(
PublicationID TEXT NOT NULL PRIMARY KEY,
Title TEXT NOT NULL,
VenueID INT,
Type TEXT NOT NULL,
PublicationType TEXT,
Year INT,
Pages TEXT,
AuthorCount INT
);
"""
)
Publication.to_sql("Publication", con=conn, if_exists="append", index=False)
log("Publications written to database")
fill_publication_author_relationships(publications_with_authors, conn=conn, to_csv=True)
def count_publications_per_venue(conn):
log("Progress of counting publications started")
publictation_venue_IDs = pd.read_csv("csv/db/Publication.csv", usecols=["VenueID"])
def fill_publication_author_relationships(publications: pd.DataFrame, conn: Connection, to_csv=False):
"""
Find for each author in the list of authors of a publication in publications.author the corresponding DBLPName. Add
the position the author is listed in the list of authors of publication. Save everything to table
'PublicationAuthor' by using the given connection conn.
:param publications: pd.DataFrame, with columns 'PublicationID' and 'author'
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/PublicationAuthor.csv, too.
"""
log("Progress of filling publication author relationships started")
# Read tables Author and AuthorName
Author = pd.read_sql("SELECT DBLPName FROM Author", con=conn)
AuthorName = pd.read_sql("SELECT DBLPName, FullName FROM AuthorName", con=conn)
publications = publications.copy()
# Create a row per author in column author and add their position in the author list
publications.author = publications.author.apply(lambda x: x.split("\n") if pd.notnull(x) else [])
publications["Position"] = publications.author.apply(lambda x: list(range(1, len(x) + 1)))
publications = publications.explode(["author", "Position"])
log("Positions in author lists added")
publications.author = publications.author.apply(lambda x: _extract(x, "text") if pd.notnull(x) else None)
# Find DBLPName for each author by joining with Author on DBLPName and with AuthorName on FullName
PublicationAuthor = publications.merge(Author, how="left", left_on="author", right_on="DBLPName")
PublicationAuthor = PublicationAuthor.merge(AuthorName, how="left", left_on="author", right_on="FullName")
PublicationAuthor["DBLPName"] = PublicationAuthor.DBLPName_x.fillna(PublicationAuthor.DBLPName_y)
log("DBLPNames for publications found")
PublicationAuthor.drop_duplicates(inplace=True)
# There are papers mapped to a person twice, most likely due to erroneously mapped alternative names in dblp.
# These violate our unique constraint on (PublicationID, DBLPName).
# As long as dblp does not fix these errors, we need to one of the publication author relationships.
PublicationAuthor[PublicationAuthor.duplicated(subset=["PublicationID", "DBLPName"], keep=False)].to_csv(
"dblp/publications_with_erroneously_duplicated_authors.csv", index=False
)
PublicationAuthor.drop_duplicates(subset=["PublicationID", "DBLPName"], inplace=True, keep="first")
PublicationAuthor.drop(columns=["DBLPName_x", "DBLPName_y", "FullName", "author"], inplace=True)
if to_csv:
PublicationAuthor.to_csv("csv/db/PublicationAuthor.csv", index=False)
conn.execute(
"""
CREATE TABLE PublicationAuthor(
PublicationID TEXT NOT NULL,
DBLPName TEXT,
Position TEXT,
PRIMARY KEY (PublicationID, DBLPName),
FOREIGN KEY(DBLPName) REFERENCES Author(DBLPName),
FOREIGN KEY(PublicationID) REFERENCES Publication(PublicationID)
);
"""
)
PublicationAuthor.to_sql("PublicationAuthor", con=conn, if_exists="append", index=False)
log("Publication author relationships written to database")
def get_unknown_first_names(conn: Connection):
unknown = pd.read_sql(
"""
SELECT DISTINCT FirstName AS first_name FROM Author
WHERE Gender = 'unknown' AND FirstName NOT NULL ORDER BY FirstName;
""",
con=conn,
)
# Discard 'nobiliary' particles in first names
unknown = unknown[~unknown.first_name.isin(NO_MIDDLE_NAMES)]
unknown.to_csv("csv/GenderAPI/unprocessed/first_names.csv", index=False)
def fill_all_together(conn: Connection):
"""
Prepare the table 'AllTogether' by using the given connection conn.
:param conn: sqlite3.Connection
:param to_csv: bool, whether to save the resulting table to csv/db/AllTogether.csv, too.
"""
log("Progress of filling all together started")
conn.execute(
"""
CREATE TABLE AllTogether(
PublicationID TEXT,
PublicationType TEXT,
AuthorID TEXT,
Venue TEXT,
AffiliationID INT,
Position TEXT,
Gender TEXT,
Year INT,
AuthorCount INT,
Country TEXT,
Continent TEXT);
"""
)
conn.execute(
"""
INSERT INTO AllTogether
SELECT Publication.PublicationID, Publication.Type, Author.AuthorID, Venue.Name, Author.AffiliationID, PublicationAuthor.Position, Author.Gender, Publication.Year, Publication.AuthorCount, Country.DisplayName, Country.Continent
FROM Publication
INNER JOIN PublicationAuthor ON PublicationAuthor.PublicationID = Publication.PublicationID
INNER JOIN Author ON PublicationAuthor.DBLPName = Author.DBLPName
INNER JOIN Venue ON Publication.VenueID = Venue.VenueID
LEFT JOIN Affiliation ON Author.AffiliationID = Affiliation.AffiliationID
LEFT JOIN Country ON Affiliation.CountryCode = Country.CountryCode;
"""
)
log("All together written to database")
def clean_up_venues(conn: Connection, Venue):
# counts how many publiactions were published per venue
SqlResponse = conn.execute(
"""
SELECT p.VenueID, v.Name, COUNT(PublicationID) AS COUNT
FROM Publication p, Venue v
WHERE p.VenueID = v.VenueID
GROUP BY p.VenueID
ORDER BY v.VenueID
"""
)
NumOfPublications = SqlResponse.fetchall()
NumOfPublications = list(NumOfPublications[i][2] for i in range(len(NumOfPublications)))
log("Counted the Number of Publications per Venue")
# updates database with finished counts
for i in range(len(Venue)):
conn.execute(
f"""
UPDATE Venue
SET NumOfPublications = {NumOfPublications[i]}
WHERE VenueID = {i}
"""
)
conn.commit()
# appends the counts to Venue and writes it to a csv
Venue["NumOfPubliactions"] = NumOfPublications
log("process of removing unplotable venues started")
# deletes the venues, that have publications in only one year, i.e. that can't be plotted by graph_logic.py
conn.execute(
"""
WITH venue_publications AS (
SELECT Venue, Year AS publication_year
FROM AllTogether
),
venues_to_keep AS (
SELECT Venue
FROM venue_publications
GROUP BY Venue
HAVING COUNT(DISTINCT publication_year) > 1
)
DELETE FROM Venue
WHERE Name NOT IN (SELECT Venue FROM venues_to_keep)
"""
)
log("unplotable venues removed")
def create_indices(conn: Connection):
log("Process of creating AllTogether index started")
conn.execute(
"""CREATE INDEX all_together_index ON AllTogether(PublicationID, PublicationType, AuthorID, Venue, AffiliationID, Position, Gender, Year, AuthorCount, Country, Continent);"""
)
log("Index created")
def insert_research_areas(conn: Connection):
research_areas = pd.read_csv("general_data/Research_area.csv")
conn.execute(
"""
ALTER TABLE AllTogether
ADD ResearchArea VARCHAR;"""
)
for i in range(len(research_areas)):
conference_name = (
research_areas["Research Area"][i],
research_areas["Venue"][i],
)
conference_aliases = [
(
research_areas["Research Area"][i],
research_areas["Alias(es)(; separated)"][i].split(";")[x],
)
for x in range(len(research_areas["Alias(es)(; separated)"][i].split(";")))
]
conference_aliases.insert(0, conference_name)
for y in range(len(conference_aliases)):
sql = f"""
SELECT
CASE WHEN EXISTS(
SELECT Venue
FROM AllTogether
WHERE Venue = ?
)
THEN 'True'
ELSE 'False'
END
"""
result = conn.execute(sql, (conference_aliases[y][1].lstrip(),))
if result.fetchall()[0][0] == "True":
sql = f"""
UPDATE AllTogether
SET ResearchArea = ?
WHERE Venue = ?
"""
conn.execute(
sql,
(
conference_aliases[y][0].lstrip(),
conference_aliases[y][1].lstrip(),
),
)
conn.commit()
def fill_statistics(conn: Connection):
log("Process of filling statistics started")
conn.execute("""CREATE TABLE GeneralStatistics(Name TEXT, Value TEXT);""")
# Distinct publication count
returnVal = conn.execute("""SELECT count(distinct PublicationID) as count\nFROM Publication;""")
result = returnVal.fetchall()[0][0]
conn.execute(
f"""INSERT INTO GeneralStatistics(Name, Value) VALUES('PublicationCount', ?);""",
(result,),
)
# Distinct author count
returnVal = conn.execute("""SELECT count(distinct AuthorID) as count\nFROM Author;""")
result = returnVal.fetchall()[0][0]
conn.execute("""INSERT INTO GeneralStatistics VALUES('AuthorCount', ?);""", (result,))
# Distinct affiliation count
returnVal = conn.execute("""SELECT count(distinct AffiliationID) as count\nFROM Affiliation;""")
result = returnVal.fetchall()[0][0]
conn.execute("""INSERT INTO GeneralStatistics VALUES('AffiliationCount', ?);""", (result,))
# Distinct venue count
returnVal = conn.execute("""SELECT count(distinct VenueID) as count\nFROM Venue;""")
result = returnVal.fetchall()[0][0]
conn.execute("""INSERT INTO GeneralStatistics VALUES('VenueCount', ?);""", (result,))
# Distinct publication author count
returnVal = conn.execute("""SELECT count(DBLPName) as count\nFROM PublicationAuthor;""")
result = returnVal.fetchall()[0][0]
conn.execute(
"""INSERT INTO GeneralStatistics VALUES('PublicationAuthorCount', ?);""",
(result,),
)
# Distinct publication author count where gender is woman
returnVal = conn.execute("""SELECT count(distinct AuthorID) as count\n FROM Author where Gender = \"woman\"""")
result = returnVal.fetchall()[0][0]
conn.execute("""INSERT INTO GeneralStatistics VALUES('FemaleAuthorCount', ?)""", (result,))
# Distinct publication author count where gender is man
returnVal = conn.execute("""SELECT count(distinct AuthorID) as count\n FROM Author where Gender = \"man\"""")
result = returnVal.fetchall()[0][0]
conn.execute("""INSERT INTO GeneralStatistics VALUES('MaleAuthorCount', ?)""", (result,))
# Distinct publication author count where gender is unknown
returnVal = conn.execute("""SELECT count(distinct AuthorID) as count\n FROM Author where Gender = \"unknown\"""")
result = returnVal.fetchall()[0][0]
conn.execute("""INSERT INTO GeneralStatistics VALUES('UnknownAuthorCount', ?)""", (result,))
# Distinct author count where country is known
returnVal = conn.execute(
"""SELECT count(distinct AuthorID) FROM Author INNER JOIN Affiliation ON Author.AffiliationID = Affiliation.AffiliationID WHERE Affiliation.CountryCode is not null;"""
)
result = returnVal.fetchall()[0][0]
conn.execute(
"""INSERT INTO GeneralStatistics VALUES('AuthorCountWithCountry', ?)""",
(result,),
)
# Distinct author count where country is unknown
returnVal = conn.execute(
"""SELECT count(distinct AuthorID) FROM Author INNER JOIN Affiliation ON Author.AffiliationID = Affiliation.AffiliationID WHERE Affiliation.CountryCode is null;"""
)
result = returnVal.fetchall()[0][0]
conn.execute(
"""INSERT INTO GeneralStatistics VALUES('AuthorCountWithoutCountry', ?)""",
(result,),
)
# Distinct female authors from each continent
returnVal = conn.execute(
"""SELECT Country.Continent, count(distinct Author.AuthorID) as count\n
FROM Author
INNER JOIN Affiliation ON Author.AffiliationID = Affiliation.AffiliationID
INNER JOIN Country ON Affiliation.CountryCode = Country.CountryCode
WHERE Author.Gender = "woman"
GROUP BY Country.Continent""")
result = returnVal.fetchall()
for row in result:
continent, count = row
conn.execute(
"""INSERT INTO GeneralStatistics VALUES('{}FemaleAuthorCount', ?)"""
.format(continent), (count, ))
# Distinct male authors from each continent
returnVal = conn.execute(
"""SELECT Country.Continent, count(distinct Author.AuthorID) as count\n
FROM Author
INNER JOIN Affiliation ON Author.AffiliationID = Affiliation.AffiliationID
INNER JOIN Country ON Affiliation.CountryCode = Country.CountryCode
WHERE Author.Gender = "man"
GROUP BY Country.Continent""")
result = returnVal.fetchall()
for row in result:
continent, count = row
conn.execute(
"""INSERT INTO GeneralStatistics VALUES('{}MaleAuthorCount', ?)""".
format(continent), (count, ))
# Distinct unknown gender authors from each continent
returnVal = conn.execute(
"""SELECT Country.Continent, count(distinct Author.AuthorID) as count\n
FROM Author
INNER JOIN Affiliation ON Author.AffiliationID = Affiliation.AffiliationID
INNER JOIN Country ON Affiliation.CountryCode = Country.CountryCode
WHERE Author.Gender = "unknown"
GROUP BY Country.Continent""")
result = returnVal.fetchall()
for row in result:
continent, count = row
conn.execute(
"""INSERT INTO GeneralStatistics VALUES('{}UnknownAuthorCount', ?)"""
.format(continent), (count, ))