-
Notifications
You must be signed in to change notification settings - Fork 839
/
provenance.py
424 lines (358 loc) · 13.7 KB
/
provenance.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
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Classes and methods related to the Structure Notation Language (SNL)
"""
import datetime
import json
import re
import sys
from collections import namedtuple
from io import StringIO
from monty.json import MontyDecoder, MontyEncoder
from monty.string import remove_non_ascii
from pybtex import errors
from pybtex.database.input import bibtex
from pymatgen.core.structure import Molecule, Structure
__author__ = "Anubhav Jain, Shyue Ping Ong"
__credits__ = "Dan Gunter"
MAX_HNODE_SIZE = 64000 # maximum size (bytes) of SNL HistoryNode
MAX_DATA_SIZE = 256000 # maximum size (bytes) of SNL data field
MAX_HNODES = 100 # maximum number of HistoryNodes in SNL file
MAX_BIBTEX_CHARS = 20000 # maximum number of characters for BibTeX reference
def is_valid_bibtex(reference):
"""
Use pybtex to validate that a reference is in proper BibTeX format
Args:
reference: A String reference in BibTeX format.
Returns:
Boolean indicating if reference is valid bibtex.
"""
# str is necessary since pybtex seems to have an issue with unicode. The
# filter expression removes all non-ASCII characters.
sio = StringIO(remove_non_ascii(reference))
parser = bibtex.Parser()
errors.set_strict_mode(False)
bib_data = parser.parse_stream(sio)
return len(bib_data.entries) > 0
class HistoryNode(namedtuple("HistoryNode", ["name", "url", "description"])):
"""
A HistoryNode represents a step in the chain of events that lead to a
Structure. HistoryNodes leave 'breadcrumbs' so that you can trace back how
a Structure was created. For example, a HistoryNode might represent pulling
a Structure from an external database such as the ICSD or CSD. Or, it might
represent the application of a code (e.g. pymatgen) to the Structure, with
a custom description of how that code was applied (e.g. a site removal
Transformation was applied).
A HistoryNode contains three fields:
.. attribute:: name
The name of a code or resource that this Structure encountered in
its history (String)
.. attribute:: url
The URL of that code/resource (String)
.. attribute:: description
A free-form description of how the code/resource is related to the
Structure (dict).
"""
def as_dict(self):
"""
Returns: Dict
"""
return {"name": self.name, "url": self.url, "description": self.description}
@staticmethod
def from_dict(h_node):
"""
Args:
d (dict): Dict representation
Returns:
HistoryNode
"""
return HistoryNode(h_node["name"], h_node["url"], h_node["description"])
@staticmethod
def parse_history_node(h_node):
"""
Parses a History Node object from either a dict or a tuple.
Args:
h_node: A dict with name/url/description fields or a 3-element
tuple.
Returns:
History node.
"""
if isinstance(h_node, dict):
return HistoryNode.from_dict(h_node)
if len(h_node) != 3:
raise ValueError(
"Invalid History node, " "should be dict or (name, version, " "description) tuple: {}".format(h_node)
)
return HistoryNode(h_node[0], h_node[1], h_node[2])
class Author(namedtuple("Author", ["name", "email"])):
"""
An Author contains two fields:
.. attribute:: name
Name of author (String)
.. attribute:: email
Email of author (String)
"""
def __str__(self):
"""
String representation of an Author
"""
return "{} <{}>".format(self.name, self.email)
def as_dict(self):
"""
Returns: MSONable dict.
"""
return {"name": self.name, "email": self.email}
@staticmethod
def from_dict(d):
"""
Args:
d (dict): Dict representation
Returns:
Author
"""
return Author(d["name"], d["email"])
@staticmethod
def parse_author(author):
"""
Parses an Author object from either a String, dict, or tuple
Args:
author: A String formatted as "NAME <email@domain.com>",
(name, email) tuple, or a dict with name and email keys.
Returns:
An Author object.
"""
if isinstance(author, str):
# Regex looks for whitespace, (any name), whitespace, <, (email),
# >, whitespace
m = re.match(r"\s*(.*?)\s*<(.*?@.*?)>\s*", author)
if not m or m.start() != 0 or m.end() != len(author):
raise ValueError("Invalid author format! {}".format(author))
return Author(m.groups()[0], m.groups()[1])
if isinstance(author, dict):
return Author.from_dict(author)
if len(author) != 2:
raise ValueError("Invalid author, should be String or (name, " "email) tuple: {}".format(author))
return Author(author[0], author[1])
class StructureNL:
"""
The Structure Notation Language (SNL, pronounced 'snail') is container
for a pymatgen Structure/Molecule object with some additional fields for
enhanced provenance. It is meant to be imported/exported in a JSON file
format with the following structure:
- about
- created_at
- authors
- projects
- references
- remarks
- data
- history
- lattice (optional)
- sites
"""
def __init__(
self,
struct_or_mol,
authors,
projects=None,
references="",
remarks=None,
data=None,
history=None,
created_at=None,
):
"""
Args:
struct_or_mol: A pymatgen.core.structure Structure/Molecule object
authors: *List* of {"name":'', "email":''} dicts,
*list* of Strings as 'John Doe <johndoe@gmail.com>',
or a single String with commas separating authors
projects: List of Strings ['Project A', 'Project B']
references: A String in BibTeX format
remarks: List of Strings ['Remark A', 'Remark B']
data: A free form dict. Namespaced at the root level with an
underscore, e.g. {"_materialsproject": <custom data>}
history: List of dicts - [{'name':'', 'url':'', 'description':{}}]
created_at: A datetime object
"""
# initialize root-level structure keys
self.structure = struct_or_mol
# turn authors into list of Author objects
authors = authors.split(",") if isinstance(authors, str) else authors
self.authors = [Author.parse_author(a) for a in authors]
# turn projects into list of Strings
projects = projects if projects else []
self.projects = [projects] if isinstance(projects, str) else projects
# check that references are valid BibTeX
if not isinstance(references, str):
raise ValueError("Invalid format for SNL reference! Should be " "empty string or BibTeX string.")
if references and not is_valid_bibtex(references):
raise ValueError("Invalid format for SNL reference! Should be " "BibTeX string.")
if len(references) > MAX_BIBTEX_CHARS:
raise ValueError(
"The BibTeX string must be fewer than {} chars "
", you have {}".format(MAX_BIBTEX_CHARS, len(references))
)
self.references = references
# turn remarks into list of Strings
remarks = remarks if remarks else []
self.remarks = [remarks] if isinstance(remarks, str) else remarks
# check remarks limit
for r in self.remarks:
if len(r) > 140:
raise ValueError("The remark exceeds the maximum size of" "140 characters: {}".format(r))
# check data limit
self.data = data if data else {}
if not sys.getsizeof(self.data) < MAX_DATA_SIZE:
raise ValueError(
"The data dict exceeds the maximum size limit of"
" {} bytes (you have {})".format(MAX_DATA_SIZE, sys.getsizeof(data))
)
for k, v in self.data.items():
if not k.startswith("_"):
raise ValueError(
"data must contain properly namespaced data "
"with keys starting with an underscore. The "
"key {} does not start with an underscore.",
format(k),
)
# check for valid history nodes
history = history if history else [] # initialize null fields
if len(history) > MAX_HNODES:
raise ValueError(
"A maximum of {} History nodes are supported, " "you have {}!".format(MAX_HNODES, len(history))
)
self.history = [HistoryNode.parse_history_node(h) for h in history]
if not all(sys.getsizeof(h) < MAX_HNODE_SIZE for h in history):
raise ValueError(
"One or more history nodes exceeds the maximum " "size limit of {} bytes".format(MAX_HNODE_SIZE)
)
self.created_at = created_at if created_at else datetime.datetime.utcnow()
def as_dict(self):
"""
Returns: MSONable dict
"""
d = self.structure.as_dict()
d["@module"] = self.__class__.__module__
d["@class"] = self.__class__.__name__
d["about"] = {
"authors": [a.as_dict() for a in self.authors],
"projects": self.projects,
"references": self.references,
"remarks": self.remarks,
"history": [h.as_dict() for h in self.history],
"created_at": json.loads(json.dumps(self.created_at, cls=MontyEncoder)),
}
d["about"].update(json.loads(json.dumps(self.data, cls=MontyEncoder)))
return d
@classmethod
def from_dict(cls, d):
"""
Args:
d (dict): Dict representation
Returns:
Class
"""
a = d["about"]
dec = MontyDecoder()
created_at = dec.process_decoded(a.get("created_at"))
data = {k: v for k, v in d["about"].items() if k.startswith("_")}
data = dec.process_decoded(data)
structure = Structure.from_dict(d) if "lattice" in d else Molecule.from_dict(d)
return cls(
structure,
a["authors"],
projects=a.get("projects", None),
references=a.get("references", ""),
remarks=a.get("remarks", None),
data=data,
history=a.get("history", None),
created_at=created_at,
)
@classmethod
def from_structures(
cls,
structures,
authors,
projects=None,
references="",
remarks=None,
data=None,
histories=None,
created_at=None,
):
"""
A convenience method for getting a list of StructureNL objects by
specifying structures and metadata separately. Some of the metadata
is applied to all of the structures for ease of use.
Args:
structures: A list of Structure objects
authors: *List* of {"name":'', "email":''} dicts,
*list* of Strings as 'John Doe <johndoe@gmail.com>',
or a single String with commas separating authors
projects: List of Strings ['Project A', 'Project B']. This
applies to all structures.
references: A String in BibTeX format. Again, this applies to all
structures.
remarks: List of Strings ['Remark A', 'Remark B']
data: A list of free form dict. Namespaced at the root level
with an underscore, e.g. {"_materialsproject":<custom data>}
. The length of data should be the same as the list of
structures if not None.
histories: List of list of dicts - [[{'name':'', 'url':'',
'description':{}}], ...] The length of histories should be the
same as the list of structures if not None.
created_at: A datetime object
"""
data = [{}] * len(structures) if data is None else data
histories = [[]] * len(structures) if histories is None else histories
snl_list = []
for i, struct in enumerate(structures):
snl = StructureNL(
struct,
authors,
projects=projects,
references=references,
remarks=remarks,
data=data[i],
history=histories[i],
created_at=created_at,
)
snl_list.append(snl)
return snl_list
def __str__(self):
return "\n".join(
[
"{}\n{}".format(k, getattr(self, k))
for k in (
"structure",
"authors",
"projects",
"references",
"remarks",
"data",
"history",
"created_at",
)
]
)
def __eq__(self, other):
return all(
map(
lambda n: getattr(self, n) == getattr(other, n),
(
"structure",
"authors",
"projects",
"references",
"remarks",
"data",
"history",
"created_at",
),
)
)
def __ne__(self, other):
return not self.__eq__(other)