-
Notifications
You must be signed in to change notification settings - Fork 22
/
__init__.py
2032 lines (1671 loc) · 75.2 KB
/
__init__.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
# -*- coding: utf-8 -*-
import io
import sys
import os
import ujson
import fido
import time
import gzip
import warnings
import pandas as pd
import plotly.io as pio
import itertools
import functools
import requests
import logging
from requests.exceptions import RequestException
from bravado_core.param import Param
from bson.objectid import ObjectId
from typing import Union, Type, List
from tqdm.auto import tqdm
from hashlib import md5
from pathlib import Path
from copy import deepcopy
from filetype import guess
from flatten_dict import flatten, unflatten
from base64 import b64encode, b64decode, urlsafe_b64encode
from urllib.parse import urlparse
from pyisemail import is_email
from collections import defaultdict
from pyisemail.diagnosis import BaseDiagnosis
from swagger_spec_validator.common import SwaggerValidationError
from jsonschema.exceptions import ValidationError
from bravado_core.formatter import SwaggerFormat
from bravado.client import SwaggerClient
from bravado.fido_client import FidoClient # async
from bravado.http_future import HttpFuture
from bravado.swagger_model import Loader
from bravado.config import bravado_config_from_config_dict
from bravado_core.spec import Spec
from bravado.exception import HTTPNotFound
from bravado_core.validate import validate_object
from json2html import Json2Html
from IPython.display import display, HTML, Image, FileLink
from boltons.iterutils import remap
from pymatgen.core import Structure as PmgStructure
from concurrent.futures import as_completed
from requests_futures.sessions import FuturesSession
from urllib3.util.retry import Retry
from filetype.types.archive import Gz
from filetype.types.image import Jpeg, Png, Gif, Tiff
from pint import UnitRegistry
from pint.unit import UnitDefinition
from pint.converters import ScaleConverter
from pint.errors import DimensionalityError
from tempfile import gettempdir
RETRIES = 3
MAX_WORKERS = 8
MAX_ELEMS = 10
MAX_NESTING = 5
MEGABYTES = 1024 * 1024
MAX_BYTES = 2.4 * MEGABYTES
MAX_PAYLOAD = 15 * MEGABYTES
MAX_COLUMNS = 160
DEFAULT_HOST = "contribs-api.materialsproject.org"
BULMA = "is-narrow is-fullwidth has-background-light"
PROVIDERS = {"github", "google", "facebook", "microsoft", "amazon"}
COMPONENTS = ["structures", "tables", "attachments"] # using list to maintain order
SUBDOMAINS = ["contribs", "lightsources", "ml", "workshop-contribs"]
PORTS = [5000, 5002, 5003, 5005, 10000, 10002, 10003, 10005, 20000]
HOSTS = ["localhost", "contribs-apis"]
HOSTS += [f"192.168.0.{i}" for i in range(36, 47)] # PrivateSubnetOne
HOSTS += [f"192.168.0.{i}" for i in range(52, 63)] # PrivateSubnetTwo
VALID_URLS = {f"http://{h}:{p}" for p in PORTS for h in HOSTS}
VALID_URLS |= {
f"https://{n}-api{m}.materialsproject.org"
for n in SUBDOMAINS for m in ["", "-preview"]
}
VALID_URLS |= {f"http://localhost.{n}-api.materialsproject.org" for n in SUBDOMAINS}
SUPPORTED_FILETYPES = (Gz, Jpeg, Png, Gif, Tiff)
SUPPORTED_MIMES = [t().mime for t in SUPPORTED_FILETYPES]
DEFAULT_DOWNLOAD_DIR = Path.home() / "mpcontribs-downloads"
j2h = Json2Html()
pd.options.plotting.backend = "plotly"
pd.set_option('mode.use_inf_as_na', True)
pio.templates.default = "simple_white"
warnings.formatwarning = lambda msg, *args, **kwargs: f"{msg}\n"
warnings.filterwarnings("default", category=DeprecationWarning, module=__name__)
ureg = UnitRegistry(
autoconvert_offset_to_baseunit=True,
preprocessors=[
lambda s: s.replace("%%", " permille "),
lambda s: s.replace("%", " percent "),
],
)
ureg.define(UnitDefinition("percent", "%", (), ScaleConverter(0.01)))
ureg.define(UnitDefinition("permille", "%%", (), ScaleConverter(0.001)))
ureg.define(UnitDefinition("ppm", "ppm", (), ScaleConverter(1e-6)))
ureg.define(UnitDefinition("ppb", "ppb", (), ScaleConverter(1e-9)))
ureg.define("atom = 1")
ureg.define("bohr_magneton = e * hbar / (2 * m_e) = µᵇ = µ_B = mu_B")
ureg.define("electron_mass = 9.1093837015e-31 kg = mₑ = m_e")
LOG_LEVEL = os.environ.get("MPCONTRIBS_CLIENT_LOG_LEVEL", "INFO")
log_level = getattr(logging, LOG_LEVEL.upper())
class LogFilter(logging.Filter):
def __init__(self, level, *args, **kwargs):
self.level = level
super(LogFilter, self).__init__(*args, **kwargs)
def filter(self, record):
return record.levelno < self.level
class CustomLoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
prefix = self.extra.get('prefix')
return f"[{prefix}] {msg}" if prefix else msg, kwargs
class TqdmToLogger(io.StringIO):
logger = None
level = None
buf = ''
def __init__(self, logger, level=None):
super(TqdmToLogger, self).__init__()
self.logger = logger
self.level = level or logging.INFO
def write(self, buf):
self.buf = buf.strip('\r\n\t ')
def flush(self):
self.logger.log(self.level, self.buf)
def get_logger(name):
logger = logging.getLogger(name)
process = os.environ.get("SUPERVISOR_PROCESS_NAME")
group = os.environ.get("SUPERVISOR_GROUP_NAME")
cfg = {"prefix": f"{group}/{process}"} if process and group else {}
info_handler = logging.StreamHandler(sys.stdout)
error_handler = logging.StreamHandler(sys.stderr)
info_handler.addFilter(LogFilter(logging.WARNING))
error_handler.setLevel(max(logging.DEBUG, logging.WARNING))
logger.handlers = [info_handler, error_handler]
logger.setLevel(log_level)
return CustomLoggerAdapter(logger, cfg)
logger = get_logger(__name__)
tqdm_out = TqdmToLogger(logger, level=log_level)
def get_md5(d):
s = ujson.dumps(d, sort_keys=True).encode("utf-8")
return md5(s).hexdigest()
def validate_email(email_string):
if email_string.count(":") != 1:
raise SwaggerValidationError(f"{email_string} not of format <provider>:<email>.")
provider, email = email_string.split(":", 1)
if provider not in PROVIDERS:
raise SwaggerValidationError(f"{provider} is not a valid provider.")
d = is_email(email, diagnose=True)
if d > BaseDiagnosis.CATEGORIES["VALID"]:
raise SwaggerValidationError(f"{email} {d.message}")
email_format = SwaggerFormat(
format="email",
to_wire=str,
to_python=str,
validate=validate_email,
description="e-mail address including provider",
)
def validate_url(url_string, qualifying=("scheme", "netloc")):
tokens = urlparse(url_string)
if not all([getattr(tokens, qual_attr) for qual_attr in qualifying]):
raise SwaggerValidationError(f"{url_string} invalid")
url_format = SwaggerFormat(
format="url", to_wire=str, to_python=str, validate=validate_url, description="URL",
)
# https://stackoverflow.com/a/8991553
def grouper(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
def get_session(max_workers=MAX_WORKERS):
# TODO add Bad Gateway 502?
adapter_kwargs = dict(max_retries=Retry(
total=RETRIES,
read=RETRIES,
connect=RETRIES,
respect_retry_after_header=True,
status_forcelist=[429], # rate limit
))
s = FuturesSession(max_workers=max_workers, adapter_kwargs=adapter_kwargs)
s.hooks['response'].append(_response_hook)
return s
def _response_hook(resp, *args, **kwargs):
content_type = resp.headers['content-type']
if content_type == "application/json":
result = resp.json()
if "data" in result and isinstance(result["data"], list):
resp.result = result
resp.count = len(result["data"])
elif "count" in result and isinstance(result["count"], int):
resp.count = result["count"]
if "warning" in result:
logger.warning(result["warning"])
elif "error" in result and isinstance(result["error"], str):
logger.error(result["error"][:10000] + "...")
elif content_type == "application/gzip":
resp.result = resp.content
resp.count = 1
else:
logger.error(f"request failed with status {resp.status_code}!")
resp.count = 0
class FidoClientGlobalHeaders(FidoClient):
def __init__(self, headers=None):
super().__init__()
self.headers = headers or {}
def request(self, request_params, operation=None, request_config=None):
request_for_twisted = self.prepare_request_for_twisted(request_params)
request_for_twisted["headers"].update(self.headers)
future_adapter = self.future_adapter_class(fido.fetch(**request_for_twisted))
return HttpFuture(
future_adapter, self.response_adapter_class, operation, request_config
)
def visit(path, key, value):
if isinstance(value, dict) and "display" in value:
return key, value["display"]
return True
def _in_ipython():
ipython = sys.modules['IPython'].get_ipython()
return ipython is not None and 'IPKernelApp' in ipython.config
class Dict(dict):
"""Custom dictionary to display itself as HTML table with Bulma CSS"""
def display(self, attrs: str = f'class="table {BULMA}"'):
"""Nice table display of dictionary
Args:
attrs (str): table attributes to forward to Json2Html.convert
"""
html = j2h.convert(json=remap(self, visit=visit), table_attributes=attrs)
if _in_ipython():
return display(HTML(html))
return html
class Table(pd.DataFrame):
"""Wrapper class around pandas.DataFrame to provide display() and info()"""
def display(self):
"""Display a plotly graph for the table if in IPython/Jupyter"""
if _in_ipython():
try:
return self.plot(**self.attrs)
except Exception as e:
logger.error(f"Can't display table: {e}")
return self
def info(self) -> Type[Dict]:
"""Show summary info for table"""
info = Dict((k, v) for k, v in self.attrs.items())
info["columns"] = ", ".join(self.columns)
info["nrows"] = len(self.total_data_rows)
return info
class Structure(PmgStructure):
"""Wrapper class around pymatgen.Structure to provide display() and info()"""
def display(self):
return self # TODO use static image from crystal toolkit?
def info(self) -> Type[Dict]:
"""Show summary info for structure"""
info = Dict((k, v) for k, v in self.attrs.items())
info["formula"] = self.composition.formula
info["reduced_formula"] = self.composition.reduced_formula
info["nsites"] = len(self)
return info
class Attachment(dict):
"""Wrapper class around dict to handle attachments"""
def decode(self) -> str:
"""Decode base64-encoded content of attachment"""
return b64decode(self["content"], validate=True)
def unpack(self) -> str:
unpacked = self.decode()
if self["mime"] == "application/gzip":
unpacked = gzip.decompress(unpacked).decode("utf-8")
return unpacked
def write(self, outdir: Union[str, Path] = None) -> Path:
"""Write attachment to file using its name
Args:
outdir (str,Path): existing directory to which to write file
"""
outdir = outdir or "."
path = Path(outdir) / self.name
content = self.decode()
path.write_bytes(content)
return path
def display(self, outdir: Union[str, Path] = None):
"""Display Image/FileLink for attachment if in IPython/Jupyter
Args:
outdir (str,Path): existing directory to which to write file
"""
if _in_ipython():
if self["mime"].startswith("image/"):
content = self.decode()
return Image(content)
self.write(outdir=outdir)
return FileLink(self.name)
return self.info().display()
def info(self) -> Dict:
"""Show summary info for attachment"""
fields = ["id", "name", "mime", "md5"]
info = Dict((k, v) for k, v in self.items() if k in fields)
info["size"] = len(self.decode())
return info
@property
def name(self) -> str:
"""name of the attachment (used in filename)"""
return self["name"]
@classmethod
def from_data(cls, name: str, data: Union[list, dict]):
"""Construct attachment from data dict or list
Args:
name (str): name for the attachment
data (list,dict): JSON-serializable data to go into the attachment
"""
filename = name + ".json.gz"
data_json = ujson.dumps(data, indent=4).encode("utf-8")
content = gzip.compress(data_json)
size = len(content)
if size > MAX_BYTES:
raise ValueError(f"{name} too large ({size} > {MAX_BYTES})!")
return cls(
name=filename,
mime="application/gzip",
content=b64encode(content).decode("utf-8")
)
def _run_futures(futures, total: int = 0, timeout: int = -1, desc=None, disable=False):
"""helper to run futures/requests"""
start = time.perf_counter()
total_set = total > 0
total = total if total_set else len(futures)
responses = {}
with tqdm(
total=total, desc=desc, file=tqdm_out, miniters=1, delay=5, disable=disable
) as pbar:
for future in as_completed(futures):
if not future.cancelled():
response = future.result()
cnt = response.count if total_set and hasattr(response, "count") else 1
pbar.update(cnt)
if hasattr(future, "track_id"):
tid = future.track_id
responses[tid] = {}
if hasattr(response, "result"):
responses[tid]["result"] = response.result
if hasattr(response, "count"):
responses[tid]["count"] = response.count
elapsed = time.perf_counter() - start
timed_out = timeout > 0 and elapsed > timeout
if timed_out or not response.ok:
for fut in futures:
fut.cancel()
return responses
@functools.lru_cache
def _load(protocol, host, headers_json, project):
headers = ujson.loads(headers_json)
http_client = FidoClientGlobalHeaders(headers=headers)
url = f"{protocol}://{host}"
origin_url = f"{url}/apispec.json"
fn = urlsafe_b64encode(origin_url.encode('utf-8')).decode('utf-8')
apispec = Path(gettempdir()) / fn
is_mock_test = 'unittest' in sys.modules and protocol == "http"
spec_dict = None
if apispec.exists():
spec_dict = ujson.loads(apispec.read_bytes())
logger.debug(f"Specs for {origin_url} re-loaded from {apispec}.")
else:
retries, max_retries = 0, 3
while retries < max_retries:
try:
if not is_mock_test:
r = requests.options(f"{url}/healthcheck")
if r.status_code != 200:
retries += 1
logger.warning(
f"Healthcheck for {url} failed (Status {r.status_code})! Waiting 60s."
)
time.sleep(60)
continue
loader = Loader(http_client)
spec_dict = loader.load_spec(origin_url)
with apispec.open("w") as f:
ujson.dump(spec_dict, f)
logger.debug(f"Specs for {origin_url} saved as {apispec}.")
break
except RequestException as ex:
retries += 1
logger.warning(f"Could not connect to {url} ({ex})! Waiting 60s ...")
time.sleep(60)
if not spec_dict:
raise ValueError(f"Could not load specs from {url}!") # not cached
spec_dict["host"] = host
spec_dict["schemes"] = [protocol]
config = {
"validate_responses": False,
"use_models": False,
"include_missing_properties": False,
"formats": [email_format, url_format],
}
bravado_config = bravado_config_from_config_dict(config)
for key in set(bravado_config._fields).intersection(set(config)):
del config[key]
config["bravado"] = bravado_config
swagger_spec = Spec.from_dict(spec_dict, origin_url, http_client, config)
if not spec_dict["paths"]:
return swagger_spec
# expand regex-based query parameters for `data` columns
session = get_session()
query = {"name": project} if project else {}
query["_fields"] = ["columns"]
kwargs = dict(headers=headers, params=query)
future = session.get(f"{url}/projects/", **kwargs)
track_id = "get_columns"
setattr(future, "track_id", track_id)
resp = _run_futures([future], timeout=3, disable=True).get(track_id, {}).get("result")
session.close()
if not resp or not resp["data"]:
raise ValueError(f"Failed to load projects for query {query}!")
if project and not resp["data"]:
raise ValueError(f"{project} doesn't exist, or access denied!")
columns = {"string": [], "number": []}
for proj in resp["data"]:
for column in proj["columns"]:
if column["path"].startswith("data."):
col = column["path"].replace(".", "__")
if column["unit"] == "NaN":
columns["string"].append(col)
else:
col = f"{col}__value"
columns["number"].append(col)
resource = swagger_spec.resources["contributions"]
for operation_id, operation in resource.operations.items():
for pn in list(operation.params.keys()):
if pn.startswith("data_"):
param = operation.params.pop(pn)
op = param.name.rsplit('$__', 1)[-1]
typ = param.param_spec.get("type")
key = "number" if typ == "number" else "string"
for column in columns[key]:
param_name = f"{column}__{op}"
param_spec = deepcopy(param.param_spec)
param_spec["name"] = param_name
param_spec.pop("description", None)
operation.params[param_name] = Param(
swagger_spec, operation, param_spec
)
return swagger_spec
class Client(SwaggerClient):
"""client to connect to MPContribs API
Typical usage:
- set environment variable MPCONTRIBS_API_KEY to the API key from your MP profile
- import and init:
>>> from mpcontribs.client import Client
>>> client = Client()
"""
# Borg: https://www.oreilly.com/library/view/python-cookbook/0596001673/ch05s23.html
# NOTE bravado future doesn't work with concurrent.futures
_shared_state = {}
def __init__(
self,
apikey: str = None,
headers: dict = None,
host: str = None,
project: str = None
):
"""Initialize the client - only reloads API spec from server as needed
Args:
apikey (str): API key (or use MPCONTRIBS_API_KEY env var) - ignored if headers set
headers (dict): custom headers for localhost connections
host (str): host address to connect to (or use MPCONTRIBS_API_HOST env var)
project (str): use this project for all operations (query, update, create, delete)
"""
# - Kong forwards consumer headers when api-key used for auth
# - forward consumer headers when connecting through localhost
self.__dict__ = self._shared_state
if not host:
host = os.environ.get("MPCONTRIBS_API_HOST", DEFAULT_HOST)
if not apikey:
apikey = os.environ.get("MPCONTRIBS_API_KEY")
if apikey and headers is not None:
apikey = None
logger.debug("headers set => ignoring apikey!")
self.apikey = apikey
self.headers = headers or {}
self.headers = {"x-api-key": apikey} if apikey else self.headers
self.headers["Content-Type"] = "application/json"
self.headers_json = ujson.dumps(self.headers, sort_keys=True)
self.host = host
ssl = host.endswith(".materialsproject.org") and not host.startswith("localhost.")
self.protocol = "https" if ssl else "http"
self.url = f"{self.protocol}://{self.host}"
self.project = project
if self.url not in VALID_URLS:
raise ValueError(f"{self.url} not a valid URL (one of {VALID_URLS})")
if "session" not in self.__dict__:
self.session = get_session()
super().__init__(self.cached_swagger_spec)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return self.session.close()
@property
def cached_swagger_spec(self):
return _load(self.protocol, self.host, self.headers_json, self.project)
def __dir__(self):
members = set(self.swagger_spec.resources.keys())
members |= set(k for k in self.__dict__.keys() if not k.startswith("_"))
members |= set(k for k in dir(self.__class__) if not k.startswith("_"))
return members
def _reinit(self):
_load.cache_clear()
super().__init__(self.cached_swagger_spec)
def _is_valid_payload(self, model: str, data: dict):
model_spec = deepcopy(self.get_model(f"{model}sSchema")._model_spec)
model_spec.pop("required")
model_spec['additionalProperties'] = False
try:
validate_object(self.swagger_spec, model_spec, data)
except ValidationError as ex:
return False, str(ex)
return True, None
def _is_serializable_dict(self, dct):
for k, v in flatten(dct, reducer="dot").items():
if v is not None and not isinstance(v, (str, int, float)):
error = f"Value {v} of {type(v)} for key {k} not supported."
return False, error
return True, None
def _get_per_page_default_max(self, op: str = "get", resource: str = "contributions") -> int:
resource = self.swagger_spec.resources[resource]
param_spec = getattr(resource, f"{op}_entries").params["per_page"].param_spec
return param_spec["default"], param_spec["maximum"]
def _get_per_page(
self, per_page: int, op: str = "get", resource: str = "contributions"
) -> int:
_, per_page_max = self._get_per_page_default_max(op=op, resource=resource)
return min(per_page_max, per_page)
def _split_query(
self,
query: dict,
op: str = "get",
resource: str = "contributions",
pages: int = -1,
) -> List[dict]:
"""Avoid URI too long errors"""
pp_default, pp_max = self._get_per_page_default_max(op=op, resource=resource)
per_page = pp_default if any(k.endswith("__in") for k in query.keys()) else pp_max
query["per_page"] = per_page
nr_params_to_split = sum(
len(v) > per_page for v in query.values() if isinstance(v, list)
)
if nr_params_to_split > 1:
raise NotImplementedError(
f"More than one list in query with length > {per_page} not supported!"
)
queries = []
for k, v in query.items():
if isinstance(v, list) and len(v) > per_page:
for chunk in grouper(per_page, v):
queries.append({k: list(chunk)})
if not queries:
queries = [query]
if len(queries) == 1 and pages and pages > 0:
queries = []
for page in range(1, pages+1):
queries.append(deepcopy(query))
queries[-1]["page"] = page
for q in queries:
# copy over missing parameters
for k, v in query.items():
if k not in q:
q[k] = v
# comma-separated lists
for k, v in q.items():
if isinstance(v, list):
q[k] = ",".join(v)
return queries
def _get_future(
self,
track_id,
params: dict,
rel_url: str = "contributions",
op: str = "get",
data: dict = None
):
if self.session and self.session.executor._shutdown:
raise ValueError("Session closed. Use `with` statement.")
rname = rel_url.split("/", 1)[0]
resource = self.swagger_spec.resources[rname]
method = getattr(resource, f"{op}_entries").http_method
kwargs = dict(headers=self.headers, params=params)
if method == "put" and data:
kwargs["data"] = ujson.dumps(data).encode("utf-8")
future = getattr(self.session, method)(
f"{self.url}/{rel_url}/", **kwargs
)
setattr(future, "track_id", track_id)
return future
def get_project(self, name: str = None) -> Type[Dict]:
"""Retrieve full project entry
Args:
name (str): name of the project
"""
name = self.project or name
if not name:
return {"error": "initialize client with project or set `name` argument!"}
return Dict(self.projects.get_entry(pk=name, _fields=["_all"]).result())
def create_project(self, name: str, title: str, authors: str, description: str, url: str):
"""Create a project
Args:
name (str): unique name matching `^[a-zA-Z0-9_]{3,31}$`
title (str): unique title with 5-30 characters
authors (str): comma-separated list of authors
description (str): brief description (max 1500 characters)
url (str): URL for primary reference (paper/website/...)
"""
queries = [{"name": name}, {"title": title}]
for query in queries:
if self.get_totals(query=query, resource="projects")[0]:
logger.error(f"Project with {query} already exists!")
return
project = {
"name": name, "title": title, "authors": authors, "description": description,
"references": [{"label": "REF", "url": url}]
}
owner = self.projects.create_entry(project=project).result().get("owner")
logger.info(f"Project `{name}` created with owner `{owner}`")
def get_contribution(self, cid: str) -> Type[Dict]:
"""Retrieve full contribution entry
Args:
cid (str): contribution ObjectID
"""
fields = list(self.get_model("ContributionsSchema")._properties.keys())
fields.remove("needs_build") # internal field
return Dict(self.contributions.get_entry(pk=cid, _fields=fields).result())
def get_table(self, tid_or_md5: str) -> Type[Table]:
"""Retrieve full Pandas DataFrame for a table
Args:
tid_or_md5 (str): ObjectId or MD5 hash digest for table
"""
str_len = len(tid_or_md5)
if str_len not in {24, 32}:
raise ValueError(f"'{tid_or_md5}' is not a valid table id or md5 hash digest!")
if str_len == 32:
tables = self.tables.get_entries(md5=tid_or_md5, _fields=["id"]).result()
if not tables:
raise ValueError(f"table for md5 '{tid_or_md5}' not found!")
tid = tables["data"][0]["id"]
else:
tid = tid_or_md5
op = self.swagger_spec.resources["tables"].get_entries
per_page = op.params["data_per_page"].param_spec["maximum"]
table = {"data": []}
page, pages = 1, None
while pages is None or page <= pages:
resp = self.tables.get_entry(
pk=tid, _fields=["_all"], data_page=page, data_per_page=per_page
).result()
table["data"].extend(resp["data"])
if pages is None:
pages = resp["total_data_pages"]
table["index"] = resp["index"]
table["columns"] = resp["columns"]
table["attrs"] = resp.get("attrs", {})
for field in ["id", "name", "md5"]:
table["attrs"][field] = resp[field]
page += 1
df = pd.DataFrame.from_records(
table["data"], columns=table["columns"], index=table["index"]
).apply(pd.to_numeric, errors="ignore")
df.index = pd.to_numeric(df.index, errors="ignore")
labels = table["attrs"].get("labels", {})
if "index" in labels:
df.index.name = labels["index"]
if "variable" in labels:
df.columns.name = labels["variable"]
ret = Table(df)
attrs_keys = self.get_model("TablesSchema")._properties["attrs"]["properties"].keys()
ret.attrs = {k: v for k, v in table["attrs"].items() if k in attrs_keys}
return ret
def get_structure(self, sid_or_md5: str) -> Type[Structure]:
"""Retrieve pymatgen structure
Args:
sid_or_md5 (str): ObjectId or MD5 hash digest for structure
"""
str_len = len(sid_or_md5)
if str_len not in {24, 32}:
raise ValueError(f"'{sid_or_md5}' is not a valid structure id or md5 hash digest!")
if str_len == 32:
structures = self.structures.get_entries(md5=sid_or_md5, _fields=["id"]).result()
if not structures:
raise ValueError(f"structure for md5 '{sid_or_md5}' not found!")
sid = structures["data"][0]["id"]
else:
sid = sid_or_md5
fields = list(self.get_model("StructuresSchema")._properties.keys())
resp = self.structures.get_entry(pk=sid, _fields=fields).result()
ret = Structure.from_dict(resp)
ret.attrs = {
field: resp[field]
for field in ["id", "name", "md5"]
}
return ret
def get_attachment(self, aid_or_md5: str) -> Type[Attachment]:
"""Retrieve an attachment
Args:
aid_or_md5 (str): ObjectId or MD5 hash digest for attachment
"""
str_len = len(aid_or_md5)
if str_len not in {24, 32}:
raise ValueError(f"'{aid_or_md5}' is not a valid attachment id or md5 hash digest!")
if str_len == 32:
attachments = self.attachments.get_entries(
md5=aid_or_md5, _fields=["id"]
).result()
if not attachments:
raise ValueError(f"attachment for md5 '{aid_or_md5}' not found!")
aid = attachments["data"][0]["id"]
else:
aid = aid_or_md5
return Attachment(self.attachments.get_entry(pk=aid, _fields=["_all"]).result())
def init_columns(self, columns: dict = None) -> dict:
"""initialize columns for a project to set their order and desired units
The `columns` field of a project tracks the minima and maxima of each `data` field
in its contributions. If columns are not initialized before submission using this
function, `submit_contributions` will respect the order of columns as they are
submitted and will try to auto-determine suitable units.
`init_columns` can be used at any point to reset the order of columns. Omitting
the `columns` argument will re-initialize columns based on the `data` fields of
all submitted contributions.
The `columns` argument is a dictionary which maps the data field names to its
units. Use `None` to indicate that a field is not a quantity (plain string). The
unit for a dimensionless quantity is an empty string (""). Percent (`%`) and
permille (`%%`) are considered units. Nested fields are indicated using a dot
(".") in the data field name.
Example:
>>> client.init_columns({"a": None, "b.c": "eV", "b.d": "mm", "e": ""})
This example will result in column headers on the project landing page of the form
| | data | |
| data | b | data |
| a | c [eV] | d [mm] | e [] |
Args:
columns (dict): dictionary mapping data column to its unit
"""
if not self.project:
return {"error": "initialize client with project argument!"}
columns = flatten(columns or {}, reducer="dot")
if len(columns) > MAX_COLUMNS:
return {"error": f"Number of columns larger than {MAX_COLUMNS}!"}
if not all(isinstance(v, str) for v in columns.values() if v is not None):
return {"error": "All values in `columns` need to be None or of type str!"}
new_columns = []
if columns:
# check columns input
scanned_columns = set()
for k, v in columns.items():
if k in COMPONENTS:
scanned_columns.add(k)
continue
nesting = k.count(".")
if nesting > MAX_NESTING:
return {"error": f"Nesting depth larger than {MAX_NESTING} for {k}!"}
for col in scanned_columns:
if nesting and col.startswith(k):
return {"error": f"Duplicate definition of {k} in {col}!"}
for n in range(1, nesting+1):
if k.rsplit(".", n)[0] == col:
return {"error": f"Ancestor of {k} already defined in {col}!"}
is_valid_string = isinstance(v, str) and v.lower() != "nan"
if not is_valid_string and v is not None:
return {
"error": f"Unit '{v}' for {k} invalid (use `None` or a non-NaN string)!"
}
if v != "" and v is not None and v not in ureg:
return {"error": f"Unit '{v}' for {k} invalid!"}
scanned_columns.add(k)
# sort to avoid "overlapping columns" error in handsontable's NestedHeaders
sorted_columns = flatten(unflatten(columns, splitter="dot"), reducer="dot")
# reconcile with existing columns
resp = self.projects.get_entry(pk=self.project, _fields=["columns"]).result()
existing_columns = {}
for col in resp["columns"]:
path = col.pop("path")
existing_columns[path] = col
for path, unit in sorted_columns.items():
if path in COMPONENTS:
new_columns.append({"path": path})
continue
full_path = f"data.{path}"
new_column = {"path": full_path}
existing_column = existing_columns.get(full_path)
if unit is not None:
new_column["unit"] = unit
if existing_column:
# NOTE if existing_unit == "NaN":
# it was set by omitting "unit" in new_column
new_unit = new_column.get("unit", "NaN")
existing_unit = existing_column.get("unit")
if existing_unit != new_unit:
try:
ureg.Quantity(existing_unit).to(new_unit)
except DimensionalityError:
return {
"error": f"Can't convert {existing_unit} to {new_unit} for {path}"
}
# TODO scale contributions to new unit
return {"error": "Changing units not supported yet. Please resubmit"
" contributions or update accordingly."}
new_columns.append(new_column)
payload = {"columns": new_columns}
valid, error = self._is_valid_payload("Project", payload)
if not valid: