-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathatlas.py
174 lines (140 loc) · 5.7 KB
/
atlas.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
"""Main container object for a large library of publications.
"""
import os
import warnings
import numpy as np
import pandas as pd
from typing import Any
from .publication import Publication
from ..vectorization.projection import Projection
from ..misc.utils import read_pickle, write_pickle, get_verbose, custom_formatwarning
warnings.formatwarning = custom_formatwarning
class Atlas:
"""Data structure for storing publications.
`self.projection`: the Projection object containing the embeddings of all publications and their mapping to str identifiers.
`self.bad_ids`: a list of identifiers that have failed for some reason or other during an expansion, and will be excluded from subsequent expansions.
`self.history`: dict of the form {'pubs_per_update': list[list[str]], 'kernel_size': np.ndarray of ints of shape `(num_pubs, last_update)` where last_update <= the total number of expansions performed.}
`self.center`: the core, central Publication identifier repeatedly passed to `cartography.Cartographer.expand`. Default is None, which means the Atlas has no internal record of the central publication.
"""
def __init__(
self,
publications: list[Publication],
projection: Projection = None,
bad_ids: set[str] = set(),
history: dict[str, Any] = None,
center: str = None,
) -> None:
if not isinstance(publications, list):
raise ValueError
self.publications: dict[str, Publication] = {
str(pub): pub for pub in publications
}
self.projection = projection
self.bad_ids = bad_ids
self.history = history
self.center = center
######################################################################
# Lookup ######################################################################
def __getitem__(self, identifier: str) -> Publication:
"""Get a publication given its identifier.
Raises:
ValueError: the identifier is not in the Atlas.
"""
if identifier in self.publications:
return self.publications[identifier]
raise ValueError(f"Identifier {identifier} not in Atlas.")
@property
def ids(self) -> list[str]:
"""Get a list of all the publication identifiers in the Atlas."""
return list(self.publications.keys())
######################################################################
# File I/O
######################################################################
def save(
self,
atlas_dirpath: str,
overwrite: bool = True,
) -> None:
"""Write the Atlas to a directory containing a .pkl binary for each attribute.
Warnings cannot be silenced.
Args:
atlas_dirpath: path of directory to save files to.
"""
# Create directory as needed, or overwrite existing files
if os.path.isdir(atlas_dirpath):
if not overwrite:
warnings.warn(
f"Skipping overwrite of atlas data found at {atlas_dirpath}."
)
return
else:
warnings.warn(
f"Recursively creating atlas data directory at {atlas_dirpath}."
)
os.makedirs(atlas_dirpath)
attributes = {
k: getattr(self, k)
for k in [
"publications",
"projection",
"bad_ids",
"history",
"center",
]
}
for attribute in attributes:
if getattr(self, attribute) is not None:
# write the list version to be consistent with load and constructor
if attribute == "publications":
attributes[attribute] = list(self.publications.values())
fn = f"{attribute}.pkl"
fp = os.path.join(atlas_dirpath, fn)
if os.path.isfile(fp):
warnings.warn(f"Overwriting existing file at {fp}.")
else:
warnings.warn(f"Writing to {fp}.")
write_pickle(fp, attributes[attribute])
else:
warnings.warn(f"No {attribute} to save, skipping.")
@classmethod
def load(
cls,
atlas_dirpath: str,
):
"""Load an Atlas object from a directory containing the .pkl binary for each attribute.
Warnings cannot be silenced.
Args:
atlas_dirpath: directory where .pkl binaries will be read from
"""
attributes = {
k: None
for k in [
"publications",
"projection",
"bad_ids",
"history",
"center",
]
}
for attribute in attributes:
fn = f"{attribute}.pkl"
fp = os.path.join(atlas_dirpath, fn)
if os.path.isfile(fp):
attributes[attribute] = read_pickle(fp)
else:
warnings.warn(f"No {attribute} to read, skipping.")
if attributes["publications"] is None:
warnings.warn("Loading empty atlas.")
attributes["publications"] = list()
return cls(**{k: v for k, v in attributes.items() if v is not None})
######################################################################
# Other
######################################################################
def __len__(self) -> int:
"""Get length of the Atlas."""
return len(self.publications)
def __eq__(self, __value: object) -> bool:
return (
self.publications == __value.publications
and self.projection == __value.projection
)