encyclopedia.py 44.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2018 Markus Scheidgen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an"AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
"""
16
The encyclopedia API of the nomad@FAIRDI APIs.
17
"""
18
import re
19
import math
20
from typing import List, Dict, Union, Sequence
21

22
23
from flask_restplus import Resource, abort, fields, marshal
from flask import request
24
from elasticsearch_dsl import Search, Q, A
25
from elasticsearch_dsl.utils import AttrDict
26

27
from nomad import config, files
28
from nomad.archive import ArchiveObject
29
from nomad.units import ureg
30
from nomad.metainfo import MSection
Lauri Himanen's avatar
Lauri Himanen committed
31
from nomad.atomutils import get_hill_decomposition
32
from .api import api
33

34
ns = api.namespace("encyclopedia", description="Access encyclopedia metadata.")
35
36
re_formula = re.compile(r"([A-Z][a-z]?)(\d*)")

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
material_prop_map = {
    # General
    "material_id": "encyclopedia.material.material_id",
    "formula": "encyclopedia.material.formula",
    "formula_reduced": "encyclopedia.material.formula_reduced",
    "system_type": "encyclopedia.material.material_type",
    # Bulk only
    "has_free_wyckoff_parameters": "encyclopedia.material.bulk.has_free_wyckoff_parameters",
    "strukturbericht_designation": "encyclopedia.material.bulk.strukturbericht_designation",
    "material_name": "encyclopedia.material.material_name",
    "bravais_lattice": "encyclopedia.material.bulk.bravais_lattice",
    "crystal_system": "encyclopedia.material.bulk.crystal_system",
    "point_group": "encyclopedia.material.bulk.point_group",
    "space_group_number": "encyclopedia.material.bulk.space_group_number",
    "space_group_international_short_symbol": "encyclopedia.material.bulk.space_group_international_short_symbol",
    "structure_prototype": "encyclopedia.material.bulk.structure_prototype",
    "structure_type": "encyclopedia.material.bulk.structure_type",
}
55
56


57
def get_es_doc_values(es_doc, mapping, keys=None):
58
59
    """Used to form a material definition for "materials/<material_id>" from
    the given ElasticSearch root document.
60
    """
61
62
63
    if keys is None:
        keys = mapping.keys()

64
    result = {}
65
    for key in keys:
66
        es_key = mapping[key]
67
68
69
70
71
72
73
        try:
            value = es_doc
            for part in es_key.split("."):
                value = getattr(value, part)
        except AttributeError:
            value = None
        result[key] = value
74
75
76
77
78

    return result


material_query = api.parser()
79
80
81
82
83
84
85
86
material_query.add_argument(
    "property",
    type=str,
    choices=tuple(material_prop_map.keys()),
    help="Optional single property to retrieve for the given material. If not specified, all properties will be returned.",
    location="args"
)
material_result = api.model("material_result", {
87
88
    # General
    "material_id": fields.String,
89
90
    "formula": fields.String,
    "formula_reduced": fields.String,
91
    "system_type": fields.String,
92
    "n_matches": fields.Integer,
93
    # Bulk only
94
    "has_free_wyckoff_parameters": fields.Boolean,
95
    "strukturbericht_designation": fields.String,
96
    "material_name": fields.String,
97
98
    "bravais_lattice": fields.String,
    "crystal_system": fields.String,
99
    "point_group": fields.String,
100
101
102
    "space_group_number": fields.Integer,
    "space_group_international_short_symbol": fields.String,
    "structure_prototype": fields.String,
103
104
    "structure_type": fields.String,
})
105
106


107
@ns.route("/materials/<string:material_id>")
108
class EncMaterialResource(Resource):
109
110
111
    @api.response(404, "The material does not exist")
    @api.response(200, "Metadata send", fields.Raw)
    @api.doc("material/<material_id>")
112
    @api.expect(material_query)
113
    @api.marshal_with(material_result, skip_none=True)
114
115
116
    def get(self, material_id):
        """Used to retrive basic information related to the specified material.
        """
117
118
119
120
121
122
123
124
125
126
        # Parse request arguments
        args = material_query.parse_args()
        prop = args.get("property", None)
        if prop is not None:
            keys = [prop]
            es_keys = [material_prop_map[prop]]
        else:
            keys = list(material_prop_map.keys())
            es_keys = list(material_prop_map.values())

127
128
129
130
131
132
133
134
135
        # Find the first public entry with this material id and take
        # information from there. In principle all other entries should have
        # the same information.
        s = Search(index=config.elastic.index_name)

        # Since we are looking for an exact match, we use filter context
        # together with term search for speed (instead of query context and
        # match search)
        query = Q(
136
            "bool",
137
            filter=[
138
139
140
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
141
142
143
            ]
        )
        s = s.query(query)
144

145
        # The query is collapsed already on the ES side so we don"t need to
146
147
148
        # transfer so much data.
        s = s.extra(**{
            "collapse": {"field": "encyclopedia.material.material_id"},
149
            "_source": {"includes": es_keys},
150
151
        })

152
153
        response = s.execute()

154
        # No such material
155
        if len(response) == 0:
156
            abort(404, message="There is no material {}".format(material_id))
157

158
        # Create result JSON
159
        entry = response[0]
160
        result = get_es_doc_values(entry, material_prop_map, keys)
161

162
163
164
        return result, 200


165
range_query = api.model("range_query", {
166
167
168
    "max": fields.Float,
    "min": fields.Float,
})
169
170
171
materials_after = api.model("materials_after", {
    "materials": fields.String,
})
172
173
materials_query = api.model("materials_input", {
    "search_by": fields.Nested(api.model("search_query", {
174
175
        "exclusive": fields.Boolean(default=False),
        "formula": fields.String,
Lauri Himanen's avatar
Lauri Himanen committed
176
        "element": fields.String,
177
        "page": fields.Integer(default=1),
178
        "after": fields.Nested(materials_after, allow_null=True),
179
180
        "per_page": fields.Integer(default=25),
        "pagination": fields.Boolean,
181
        "mode": fields.String(default="aggregation"),
182
    })),
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    "material_name": fields.List(fields.String),
    "structure_type": fields.List(fields.String),
    "space_group_number": fields.List(fields.Integer),
    "system_type": fields.List(fields.String),
    "crystal_system": fields.List(fields.String),
    "band_gap": fields.Nested(range_query, description="Band gap range in eV."),
    "band_gap_direct": fields.Boolean,
    "has_band_structure": fields.Boolean,
    "has_dos": fields.Boolean,
    "has_fermi_surface": fields.Boolean,
    "has_thermal_properties": fields.Boolean,
    "functional_type": fields.List(fields.String),
    "basis_set_type": fields.List(fields.String),
    "code_name": fields.List(fields.String),
    "mass_density": fields.Nested(range_query, description="Mass density range in kg / m ** 3."),
198
})
199
200
201
202
203
pages_result = api.model("page_info", {
    "per_page": fields.Integer,
    "total": fields.Integer,
    "page": fields.Integer,
    "pages": fields.Integer,
204
    "after": fields.Nested(materials_after),
205
206
})

207
208
209
materials_result = api.model("materials_result", {
    "total_results": fields.Integer(allow_null=False),
    "results": fields.List(fields.Nested(material_result)),
210
    "pages": fields.Nested(pages_result),
211
    "es_query": fields.String(allow_null=False),
212
213
214
})


215
@ns.route("/materials")
216
class EncMaterialsResource(Resource):
217
218
219
    @api.response(404, "No materials found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
220
    @api.expect(materials_query, validate=False)
221
    @api.marshal_with(materials_result, skip_none=True)
222
    @api.doc("materials")
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    def post(self):
        """Used to query a list of materials with the given search options.
        """
        # Get query parameters as json
        try:
            data = marshal(request.get_json(), materials_query)
        except Exception as e:
            abort(400, message=str(e))

        filters = []
        must_nots = []
        musts = []

        # Add term filters
237
238
        filters.append(Q("term", published=True))
        filters.append(Q("term", with_embargo=False))
239
240
241
242
243
244
245

        def add_terms_filter(source, target, query_type="terms"):
            if data[source]:
                filters.append(Q(query_type, **{target: data[source]}))

        add_terms_filter("material_name", "encyclopedia.material.material_name")
        add_terms_filter("structure_type", "encyclopedia.material.bulk.structure_type")
246
        add_terms_filter("space_group_number", "encyclopedia.material.bulk.space_group_number")
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
        add_terms_filter("system_type", "encyclopedia.material.material_type")
        add_terms_filter("crystal_system", "encyclopedia.material.bulk.crystal_system")
        add_terms_filter("band_gap_direct", "encyclopedia.properties.band_gap_direct", query_type="term")
        add_terms_filter("functional_type", "encyclopedia.method.functional_type")
        add_terms_filter("basis_set_type", "dft.basis_set")
        add_terms_filter("code_name", "dft.code_name")

        # Add exists filters
        def add_exists_filter(source, target):
            param = data[source]
            if param is not None:
                query = Q("exists", field=target)
                if param is True:
                    filters.append(query)
                elif param is False:
                    must_nots.append(query)

        add_exists_filter("has_thermal_properties", "encyclopedia.properties.thermodynamical_properties")
        add_exists_filter("has_band_structure", "encyclopedia.properties.electronic_band_structure")
        add_exists_filter("has_dos", "encyclopedia.properties.electronic_dos")
        add_exists_filter("has_fermi_surface", "encyclopedia.properties.fermi_surface")

        # Add range filters
        def add_range_filter(source, target, source_unit=None, target_unit=None):
            param = data[source]
            query_dict = {}
            if param["min"] is not None:
                if source_unit is None and target_unit is None:
                    gte = param["min"]
                else:
                    gte = (param["min"] * source_unit).to(target_unit).magnitude
                query_dict["gte"] = gte
            if param["max"] is not None:
                if source_unit is None and target_unit is None:
                    lte = param["max"]
                else:
                    lte = (param["max"] * source_unit).to(target_unit).magnitude
                query_dict["lte"] = lte
            if len(query_dict) != 0:
                query = Q("range", **{target: query_dict})
                filters.append(query)

        add_range_filter("band_gap", "encyclopedia.properties.band_gap", ureg.eV, ureg.J)
        add_range_filter("mass_density", "encyclopedia.properties.mass_density")
291

292
293
        # Create query for elements or formula
        search_by = data["search_by"]
294
        mode = search_by["mode"]
295
        formula = search_by["formula"]
Lauri Himanen's avatar
Lauri Himanen committed
296
        elements = search_by["element"]
297
298
299
        exclusive = search_by["exclusive"]

        if formula is not None:
Lauri Himanen's avatar
Lauri Himanen committed
300
301
            # Here we determine a list of atom types. The types may occur
            # multiple times and at multiple places.
302
303
304
305
306
307
308
309
310
311
            element_list = []
            matches = re_formula.finditer(formula)
            for match in matches:
                groups = match.groups()
                symbol = groups[0]
                count = groups[1]
                if symbol != "":
                    if count == "":
                        element_list.append(symbol)
                    else:
Lauri Himanen's avatar
Lauri Himanen committed
312
313
314
315
316
                        element_list += [symbol] * int(count)

            # The given list of species is reformatted with the Hill system
            # into a query string. The counts are reduced by the greatest
            # common divisor.
317
            names, reduced_counts = get_hill_decomposition(element_list, reduced=True)
Lauri Himanen's avatar
Lauri Himanen committed
318
319
320
321
322
            query_string = []
            for name, count in zip(names, reduced_counts):
                if count == 1:
                    query_string.append(name)
                else:
323
                    query_string.append("{}{}".format(name, int(count)))
Lauri Himanen's avatar
Lauri Himanen committed
324
            query_string = " ".join(query_string)
325
326
327

            # With exclusive search we look for exact match
            if exclusive:
Lauri Himanen's avatar
Lauri Himanen committed
328
                filters.append(Q("term", **{"encyclopedia.material.species_and_counts.keyword": query_string}))
329
330
331
332
333
            # With non-exclusive search we look for match that includes at
            # least all parts of the formula, possibly even more.
            else:
                musts.append(Q(
                    "match",
Lauri Himanen's avatar
Lauri Himanen committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
                    encyclopedia__material__species_and_counts={"query": query_string, "operator": "and"}
                ))
        elif elements is not None:
            # The given list of species is reformatted with the Hill system into a query string
            species, _ = get_hill_decomposition(elements.split(","))
            query_string = " ".join(species)

            # With exclusive search we look for exact match
            if exclusive:
                filters.append(Q("term", **{"encyclopedia.material.species.keyword": query_string}))
            # With non-exclusive search we look for match that includes at
            # least all species, possibly even more.
            else:
                musts.append(Q(
                    "match",
                    encyclopedia__material__species={"query": query_string, "operator": "and"}
350
351
                ))

352
353
        page = search_by["page"]
        per_page = search_by["per_page"]
354
        after = search_by["after"]
355
        bool_query = Q(
356
            "bool",
357
358
359
360
            filter=filters,
            must_not=must_nots,
            must=musts,
        )
361

362
363
364
        # 1: The paginated approach: No way to know the amount of matches,
        # but can return aggregation results in a quick fashion including
        # the number of matches entries per material.
365
        if mode == "aggregation":
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
            # The top query filters out entries based on the user query
            s = Search(index=config.elastic.index_name)
            s = s.query(bool_query)

            # The materials are grouped by using three aggregations:
            # "Composite" to enable scrolling, "Terms" to enable selecting
            # by material_id and "Top Hits" to fetch a single
            # representative material document. Unnecessary fields are
            # filtered to reduce data transfer.
            terms_agg = A("terms", field="encyclopedia.material.material_id")
            composite_kwargs = {"sources": {"materials": terms_agg}, "size": per_page}
            if after is not None:
                composite_kwargs["after"] = after
            composite_agg = A("composite", **composite_kwargs)
            composite_agg.metric("representative", A(
                "top_hits",
                size=1,
                _source={"includes": list(material_prop_map.values())},
            ))
            s.aggs.bucket("materials", composite_agg)

            # We ignore the top level hits
            s = s.extra(**{
                "size": 0,
            })
392

393
394
395
396
397
            response = s.execute()
            materials = response.aggs.materials.buckets
            if len(materials) == 0:
                abort(404, message="No materials found for the given search criteria or pagination.")
            after = response.aggs.materials["after_key"]
398
399
400
401

            # Gather results from aggregations
            result_list = []
            materials = response.aggs.materials.buckets
402
            keys = list(material_prop_map.keys())
403
404
            for material in materials:
                representative = material["representative"][0]
405
406
                mat_dict = get_es_doc_values(representative, material_prop_map, keys)
                mat_dict["n_matches"] = material.doc_count
407
408
409
410
411
412
                result_list.append(mat_dict)

            # Page information is incomplete for aggregations
            pages = {
                "page": page,
                "per_page": per_page,
413
                "after": after,
414
415
            }
        # 2. Collapse approach. Quickly provides a list of materials
416
        # corresponding to the query, offers full pagination, doesn"t include
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        # the number of matches per material.
        elif mode == "collapse":
            s = Search(index=config.elastic.index_name)
            s = s.query(bool_query)
            s = s.extra(**{
                "collapse": {"field": "encyclopedia.material.material_id"},
                "size": per_page,
                "from": (page - 1) * per_page,
            })

            # Execute query
            response = s.execute()

            # No matches
            if len(response) == 0:
432
                abort(404, message="No materials found for the given search criteria or pagination.")
433
434
435

            # Loop over materials
            result_list = []
436
            keys = list(material_prop_map.keys())
437
            for material in response:
438
                mat_result = get_es_doc_values(material, material_prop_map, keys)
439
440
441
442
443
444
445
446
447
                result_list.append(mat_result)

            # Full page information available for collapse
            pages = {
                "page": page,
                "per_page": per_page,
                "pages": math.ceil(response.hits.total / per_page),
                "total": response.hits.total,
            }
448
449
450

        result = {
            "results": result_list,
451
            "pages": pages,
452
        }
453
        return result, 200
454
455


456
groups_result = api.model("groups_result", {
457
458
    "groups_eos": fields.Raw,
    "groups_par": fields.Raw,
459
460
461
})


462
@ns.route("/materials/<string:material_id>/groups")
Lauri Himanen's avatar
Lauri Himanen committed
463
class EncGroupsResource(Resource):
464
465
466
    @api.response(404, "Material not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
467
    @api.marshal_with(groups_result)
468
    @api.doc("enc_materials")
Lauri Himanen's avatar
Lauri Himanen committed
469
    def get(self, material_id):
470
471
472
        """Returns a summary of the calculation groups that were identified for
        this material.
        """
473
474
475
        # Find entries for the given material, which have EOS or parameter
        # variation hashes set.
        bool_query = Q(
476
            "bool",
477
            filter=[
478
479
480
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
481
482
483
            ],
            must=[
                Q("exists", field="encyclopedia.properties.energies.energy_total"),
484
                Q("exists", field="encyclopedia.material.idealized_structure.cell_volume"),
485
486
            ],
            should=[
487
488
                Q("exists", field="encyclopedia.method.group_eos_id"),
                Q("exists", field="encyclopedia.method.group_parametervariation_id"),
489
490
491
            ],
            minimum_should_match=1,  # At least one of the should query must match
        )
Lauri Himanen's avatar
Lauri Himanen committed
492
493

        s = Search(index=config.elastic.index_name)
494
495
496
497
        s = s.query(bool_query)

        # Bucket the calculations by the group hashes. Only create a bucket if an
        # above-minimum number of documents are found.
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
        group_eos_bucket = A("terms", field="encyclopedia.method.group_eos_id", min_doc_count=4)
        group_param_bucket = A("terms", field="encyclopedia.method.group_parametervariation_id", min_doc_count=2)
        calc_aggregation = A(
            "top_hits",
            _source={"includes": ["calc_id"]},
            sort=[{"encyclopedia.properties.energies.energy_total": {"order": "asc"}}],
            size=100,
        )
        group_eos_bucket.bucket("calculations", calc_aggregation)
        group_param_bucket.bucket("calculations", calc_aggregation)
        s.aggs.bucket("groups_eos", group_eos_bucket)
        s.aggs.bucket("groups_param", group_param_bucket)

        # We ignore the top level hits
        s = s.extra(**{
            "size": 0,
        })

        # Collect information for each group from the aggregations
        response = s.execute()
        groups_eos = {group.key: [calc.calc_id for calc in group.calculations.hits] for group in response.aggs.groups_eos.buckets}
        groups_param = {group.key: [calc.calc_id for calc in group.calculations.hits] for group in response.aggs.groups_param.buckets}

        # Return results
        result = {
            "groups_eos": groups_eos,
            "groups_par": groups_param,
        }

        return result, 200


group_result = api.model("group_result", {
    "calculations": fields.List(fields.String),
    "energies": fields.List(fields.Float),
    "volumes": fields.List(fields.Float),
})
group_source = {
    "includes": [
        "calc_id",
        "encyclopedia.properties.energies.energy_total",
        "encyclopedia.material.idealized_structure.cell_volume",
    ]
}


@ns.route("/materials/<string:material_id>/groups/<string:group_type>/<string:group_id>")
class EncGroupResource(Resource):
    @api.response(404, "Group not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
    @api.marshal_with(group_result)
    @api.doc("enc_group")
    def get(self, material_id, group_type, group_id):
        """Used to query detailed information for a specific calculation group.
        """
        # Find entries for the given material, which have EOS or parameter
        # variation hashes set.
        if group_type == "eos":
            group_id_source = "encyclopedia.method.group_eos_id"
        elif group_type == "par":
            group_id_source = "encyclopedia.method.group_parametervariation_id"
        else:
            abort(400, message="Unsupported group type.")

        bool_query = Q(
            "bool",
            filter=[
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
                Q("term", **{group_id_source: group_id}),
            ],
        )

        s = Search(index=config.elastic.index_name)
        s = s.query(bool_query)
575
576
577
578
579

        # calc_id and energy should be extracted for each matched document. The
        # documents are sorted by energy so that the minimum energy one can be
        # easily extracted. A maximum request size is set in order to limit the
        # result size. ES also has an index-level property
580
        # "index.max_inner_result_window" that limits the number of results
581
582
583
584
585
586
587
        # that an inner result can contain.
        energy_aggregation = A(
            "top_hits",
            _source=group_source,
            sort=[{"encyclopedia.properties.energies.energy_total": {"order": "asc"}}],
            size=100,
        )
588
        s.aggs.bucket("groups_eos", energy_aggregation)
589

590
591
592
593
        # We ignore the top level hits
        s = s.extra(**{
            "size": 0,
        })
594

595
        # Collect information for each group from the aggregations
596
        response = s.execute()
597

598
599
600
601
602
603
604
605
        hits = response.aggs.groups_eos.hits
        calculations = [doc.calc_id for doc in hits]
        energies = [doc.encyclopedia.properties.energies.energy_total for doc in hits]
        volumes = [doc.encyclopedia.material.idealized_structure.cell_volume for doc in hits]
        group_dict = {
            "calculations": calculations,
            "energies": energies,
            "volumes": volumes,
606
        }
607
608

        return group_dict, 200
609
610


611
612
613
614
suggestions_map = {
    "code_name": "dft.code_name",
    "structure_type": "encyclopedia.material.bulk.structure_type",
}
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
suggestions_query = api.parser()
suggestions_query.add_argument(
    "property",
    type=str,
    choices=("code_name", "structure_type"),
    help="The property name for which suggestions are returned.",
    location="args"
)
suggestions_result = api.model("suggestions_result", {
    "code_name": fields.List(fields.String),
    "structure_type": fields.List(fields.String),
})


@ns.route("/suggestions")
class EncSuggestionsResource(Resource):
    @api.response(404, "Suggestion not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
    @api.expect(suggestions_query, validate=False)
    @api.marshal_with(suggestions_result, skip_none=True)
    @api.doc("enc_suggestions")
    def get(self):

        # Parse request arguments
        args = suggestions_query.parse_args()
        prop = args.get("property", None)

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
        # Use aggregation to return all unique terms for the requested field.
        # Without using composite aggregations there is a size limit for the
        # number of aggregation buckets. This should, however, not be a problem
        # since the number of unique values is low for all supported properties.
        s = Search(index=config.elastic.index_name)
        query = Q(
            "bool",
            filter=[
                Q("term", published=True),
                Q("term", with_embargo=False),
            ]
        )
        s = s.query(query)
        s = s.extra(**{
            "size": 0,
        })

        terms_agg = A("terms", field=suggestions_map[prop])
        s.aggs.bucket("suggestions", terms_agg)

        # Gather unique values into a list
        response = s.execute()
        suggestions = [x.key for x in response.aggs.suggestions.buckets]

        return {prop: suggestions}, 200
668
669


670
671
calcs_query = api.parser()
calcs_query.add_argument(
672
673
674
675
676
677
    "page",
    default=0,
    type=int,
    help="The page number to return.",
    location="args"
)
678
calcs_query.add_argument(
679
680
681
682
683
684
685
686
687
688
689
690
    "per_page",
    default=25,
    type=int,
    help="The number of results per page",
    location="args"
)
calc_prop_map = {
    "calc_id": "calc_id",
    "code_name": "dft.code_name",
    "code_version": "dft.code_version",
    "functional_type": "encyclopedia.method.functional_type",
    "basis_set_type": "dft.basis_set",
691
    "core_electron_treatment": "encyclopedia.method.core_electron_treatment",
692
693
694
695
696
697
698
699
700
701
702
    "run_type": "encyclopedia.calculation.calculation_type",
    "has_dos": "encyclopedia.properties.electronic_dos",
    "has_band_structure": "encyclopedia.properties.electronic_band_structure",
    "has_thermal_properties": "encyclopedia.properties.thermodynamical_properties",
}
calculation_result = api.model("calculation_result", {
    "calc_id": fields.String,
    "code_name": fields.String,
    "code_version": fields.String,
    "functional_type": fields.String,
    "basis_set_type": fields.String,
703
    "core_electron_treatment": fields.String,
704
705
706
707
708
709
710
711
712
713
714
715
716
    "run_type": fields.String,
    "has_dos": fields.Boolean,
    "has_band_structure": fields.Boolean,
    "has_thermal_properties": fields.Boolean,
})
calculations_result = api.model("calculations_result", {
    "total_results": fields.Integer,
    "pages": fields.Nested(pages_result),
    "results": fields.List(fields.Nested(calculation_result)),
})


@ns.route("/materials/<string:material_id>/calculations")
717
class EncCalculationsResource(Resource):
718
719
720
    @api.response(404, "Suggestion not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
721
    @api.expect(calcs_query, validate=False)
722
723
724
725
    @api.doc("enc_calculations")
    def get(self, material_id):
        """Used to return all calculations related to the given material.
        """
726
        args = calcs_query.parse_args()
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
        page = args["page"]
        per_page = args["per_page"]

        s = Search(index=config.elastic.index_name)
        query = Q(
            "bool",
            filter=[
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
            ]
        )
        s = s.query(query)

        # The query is filtered already on the ES side so we don"t need to
        # transfer so much data.
        s = s.extra(**{
            "_source": {"includes": list(calc_prop_map.values())},
            "size": per_page,
            "from": page,
        })

        response = s.execute()

        # No such material
        if len(response) == 0:
            abort(404, message="There is no material {}".format(material_id))

        # Create result JSON
        results = []
        for entry in response:
            calc_dict = get_es_doc_values(entry, calc_prop_map)
            calc_dict["has_dos"] = calc_dict["has_dos"] is not None
760
            calc_dict["has_band_structure"] = calc_dict["has_band_structure"] is not None
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
            calc_dict["has_thermal_properties"] = calc_dict["has_thermal_properties"] is not None
            results.append(calc_dict)

        result = {
            "total_results": len(results),
            "results": results,
            "pages": {
                "per_page": per_page,
                "page": page,
            }
        }

        return result, 200


776
777
778
779
histogram = api.model("histogram", {
    "occurrences": fields.List(fields.Integer),
    "values": fields.List(fields.Float),
})
780
781
statistics_query = api.model("statistics_query", {
    "calculations": fields.List(fields.String),
782
    "properties": fields.List(fields.String),
783
    "n_histogram_bins": fields.Integer,
784
785
786
787
788
})
statistics = api.model("statistics", {
    "min": fields.Float,
    "max": fields.Float,
    "avg": fields.Float,
789
    "histogram": fields.Nested(histogram)
790
791
792
})
statistics_result = api.model("statistics_result", {
    "cell_volume": fields.Nested(statistics),
793
794
795
796
797
798
799
800
    "atomic_density": fields.Nested(statistics),
    "mass_density": fields.Nested(statistics),
    "lattice_a": fields.Nested(statistics),
    "lattice_b": fields.Nested(statistics),
    "lattice_c": fields.Nested(statistics),
    "alpha": fields.Nested(statistics),
    "beta": fields.Nested(statistics),
    "gamma": fields.Nested(statistics),
Lauri Himanen's avatar
Lauri Himanen committed
801
    "band_gap": fields.Nested(statistics),
802
})
803
804
805
806
807
808
809
810
811
812
property_map = {
    "cell_volume": "encyclopedia.material.idealized_structure.cell_volume",
    "atomic_density": "encyclopedia.properties.atomic_density",
    "mass_density": "encyclopedia.properties.mass_density",
    "lattice_a": "encyclopedia.material.idealized_structure.lattice_parameters.a",
    "lattice_b": "encyclopedia.material.idealized_structure.lattice_parameters.b",
    "lattice_c": "encyclopedia.material.idealized_structure.lattice_parameters.c",
    "alpha": "encyclopedia.material.idealized_structure.lattice_parameters.alpha",
    "beta": "encyclopedia.material.idealized_structure.lattice_parameters.beta",
    "gamma": "encyclopedia.material.idealized_structure.lattice_parameters.gamma",
Lauri Himanen's avatar
Lauri Himanen committed
813
    "band_gap": "encyclopedia.properties.band_gap",
814
}
815
816
817


@ns.route("/materials/<string:material_id>/statistics")
818
class EncStatisticsResource(Resource):
819
820
821
    @api.response(404, "Suggestion not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
822
823
    @api.expect(statistics_query, validate=False)
    @api.marshal_with(statistics_result, skip_none=True)
824
825
    @api.doc("enc_statistics")
    def post(self, material_id):
826
827
        """Used to return statistics related to the specified material and
        calculations.
828
        """
829
        # Get query parameters as json
Lauri Himanen's avatar
Lauri Himanen committed
830
        print(request.get_json())
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
        try:
            data = marshal(request.get_json(), statistics_query)
        except Exception as e:
            abort(400, message=str(e))

        # Find entries for the given material.
        bool_query = Q(
            "bool",
            filter=[
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
                Q("terms", calc_id=data["calculations"]),
            ]
        )

        s = Search(index=config.elastic.index_name)
        s = s.query(bool_query)
        s = s.extra(**{
            "size": 0,
        })

853
854
855
856
857
858
        # Add statistics aggregations for each requested property
        properties = data["properties"]
        for prop in properties:
            stats_agg = A("stats", field=property_map[prop])
            s.aggs.bucket("{}_stats".format(prop), stats_agg)

859
860
861
862
863
        # No hits on the top query level
        response = s.execute()
        if response.hits.total == 0:
            abort(404, message="Could not find matching calculations.")

864
865
866
867
868
869
870
871
        # Run a second query that creates histograms with fixed size buckets
        # based on the min and max from previous query. Might make more sense
        # to use the mean and sigma to define the range?
        s = Search(index=config.elastic.index_name)
        s = s.query(bool_query)
        s = s.extra(**{
            "size": 0,
        })
872
        n_bins = data["n_histogram_bins"]
873
874
        for prop in properties:
            stats = getattr(response.aggs, "{}_stats".format(prop))
875
            interval = (stats.max * 1.001 - stats.min) / n_bins
876
877
            if interval == 0:
                interval = 1
878
            hist_agg = A("histogram", field=property_map[prop], interval=interval, offset=stats.min, min_doc_count=0)
879
880
881
            s.aggs.bucket("{}_hist".format(prop), hist_agg)
        response_hist = s.execute()

882
        # Return results
883
884
885
886
887
888
889
890
891
892
        result = {}
        for prop in properties:
            stats = getattr(response.aggs, "{}_stats".format(prop))
            hist = getattr(response_hist.aggs, "{}_hist".format(prop))
            occurrences = [x.doc_count for x in hist.buckets]
            values = [x.key for x in hist.buckets]
            result[prop] = {
                "min": stats.min,
                "max": stats.max,
                "avg": stats.avg,
893
                "histogram": {
894
895
896
                    "occurrences": occurrences,
                    "values": values,
                }
897
            }
898

899
        return result, 200
900
901
902
903
904
905
906
907
908
909
910
911
912


wyckoff_variables_result = api.model("wyckoff_variables_result", {
    "x": fields.Float,
    "y": fields.Float,
    "z": fields.Float,
})
wyckoff_set_result = api.model("wyckoff_set_result", {
    "wyckoff_letter": fields.String,
    "indices": fields.List(fields.Integer),
    "element": fields.String,
    "variables": fields.List(fields.Nested(wyckoff_variables_result)),
})
913
914
915
916
917
918
919
920
lattice_parameters = api.model("lattice_parameters", {
    "a": fields.Float,
    "b": fields.Float,
    "c": fields.Float,
    "alpha": fields.Float,
    "beta": fields.Float,
    "gamma": fields.Float,
})
921
922
923
924
925
926

idealized_structure_result = api.model("idealized_structure_result", {
    "atom_labels": fields.List(fields.String),
    "atom_positions": fields.List(fields.List(fields.Float)),
    "lattice_vectors": fields.List(fields.List(fields.Float)),
    "lattice_vectors_primitive": fields.List(fields.List(fields.Float)),
927
    "lattice_parameters": fields.Nested(lattice_parameters),
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
    "periodicity": fields.List(fields.Boolean),
    "number_of_atoms": fields.Integer,
    "cell_volume": fields.Float,
    "wyckoff_sets": fields.List(fields.Nested(wyckoff_set_result)),
})


@ns.route("/materials/<string:material_id>/idealized_structure")
class EncIdealizedStructureResource(Resource):
    @api.response(404, "Suggestion not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
    @api.marshal_with(idealized_structure_result, skip_none=True)
    @api.doc("enc_material_idealized_structure")
    def get(self, material_id):
        """Specialized path for returning a representative idealized structure
        that is displayed in the gui for this material.
        """
        # The representative idealized structure simply comes from the first
        # calculation when the calculations are alphabetically sorted by their
        # calc_id. Coming up with a good way to select the representative one
        # is pretty tricky in general, there are several options:
        # - Lowest energy: This would be most intuitive, but the energy scales
        #   between codes do not match, and the energy may not have been
        #   reported.
        # - Volume that is closest to mean volume: how to calculate volume for
        #   molecules, surfaces, etc...
        # - Random: We would want the representative visualization to be
        #   relatively stable.
        s = Search(index=config.elastic.index_name)
        query = Q(
            "bool",
            filter=[
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
            ]
        )
        s = s.query(query)

        # The query is filtered already on the ES side so we don"t need to
        # transfer so much data.
        s = s.extra(**{
            "sort": [{"calc_id": {"order": "asc"}}],
            "_source": {"includes": ["upload_id", "calc_id"]},
            "size": 1,
        })

        response = s.execute()

        # No such material
        if len(response) == 0:
            abort(404, message="There is no material {}".format(material_id))

        # Read the idealized_structure from the Archive. The structure can be
        # quite large and no direct search queries are performed against it, so
        # it is not in the ES index.
        entry = response[0]
        upload_id = entry.upload_id
        calc_id = entry.calc_id
988
989
        ideal_struct_path = "section_metadata/encyclopedia/material/idealized_structure"
        idealized_structure = read_archive(upload_id, calc_id, ideal_struct_path)[ideal_struct_path]
990
991
992
993

        return idealized_structure, 200


994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
calculation_property_map = {
    "lattice_parameters": {
        "es_source": "encyclopedia.material.idealized_structure.lattice_parameters"
    },
    "energies": {
        "es_source": "encyclopedia.properties.energies",
    },
    "mass_density": {
        "es_source": "encyclopedia.properties.mass_density",
    },
    "atomic_density": {
        "es_source": "encyclopedia.properties.atomic_density",
    },
    "cell_volume": {
        "es_source": "encyclopedia.material.idealized_structure.cell_volume"
    },
Lauri Himanen's avatar
Lauri Himanen committed
1010
1011
1012
    "band_gap": {
        "es_source": "encyclopedia.properties.band_gap"
    },
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
    "electronic_band_structure": {
        "es_source": "encyclopedia.properties.electronic_band_structure"
    },
    "electronic_dos": {
        "es_source": "encyclopedia.properties.electronic_dos"
    },
    "wyckoff_sets": {
        "arch_source": "section_metadata/encyclopedia/material/idealized_structure/wyckoff_sets"
    },
}

calculation_property_query = api.model("calculation_query", {
    "properties": fields.List(fields.String),
})
energies = api.model("energies", {
    "energy_total": fields.Float,
    "energy_total_T0": fields.Float,
    "energy_free": fields.Float,
})
Lauri Himanen's avatar
Lauri Himanen committed
1032
1033
1034
1035
1036
1037
1038
1039
1040
electronic_band_structure = api.model("electronic_band_structure", {
    "reciprocal_cell": fields.List(fields.List(fields.Float)),
    "brillouin_zone": fields.Raw,
    "section_k_band_segment": fields.Raw,
})
electronic_dos = api.model("electronic_dos", {
    "dos_energies": fields.List(fields.Float),
    "dos_values": fields.List(fields.Float),
})
1041
1042
1043
1044
1045
1046
1047
calculation_property_result = api.model("calculation_query", {
    "lattice_parameters": fields.Nested(lattice_parameters),
    "energies": fields.Nested(energies),
    "mass_density": fields.Float,
    "atomic_density": fields.Float,
    "cell_volume": fields.Float,
    "wyckoff_sets": fields.Nested(wyckoff_set_result),
Lauri Himanen's avatar
Lauri Himanen committed
1048
1049
1050
    "band_gap": fields.Float(wyckoff_set_result),
    "electronic_band_structure": fields.Nested(electronic_band_structure),
    "electronic_dos": fields.Nested(electronic_dos),
1051
1052
1053
})


1054
1055
1056
1057
1058
@ns.route("/materials/<string:material_id>/calculations/<string:calc_id>")
class EncCalculationResource(Resource):
    @api.response(404, "Material or calculation not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
1059
    @api.expect(calculation_property_query, validate=False)
1060
    # @api.marshal_with(calculation_property_result, skip_none=True)
1061
    @api.doc("enc_calculation")
1062
1063
1064
1065
    def post(self, material_id, calc_id):
        """Used to return calculation details. Some properties are not
        available in the ES index and are instead read from the Archive
        directly.
1066
        """
1067
1068
1069
1070
1071
1072
        # Get query parameters as json
        try:
            data = marshal(request.get_json(), calculation_property_query)
        except Exception as e:
            abort(400, message=str(e))

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
        s = Search(index=config.elastic.index_name)
        query = Q(
            "bool",
            filter=[
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
                Q("term", calc_id=calc_id),
            ]
        )
        s = s.query(query)

1085
        # Create dictionaries for requested properties
1086
        references = []
1087
1088
1089
1090
1091
1092
1093
        properties = data["properties"]
        arch_properties = {}
        es_properties = {}
        for prop in properties:
            es_source = calculation_property_map[prop].get("es_source")
            if es_source is not None:
                es_properties[prop] = es_source
1094
1095
                if prop in set(("electronic_dos", "electronic_band_structure")):
                    references.append(prop)
1096
1097
1098
1099
            arch_source = calculation_property_map[prop].get("arch_source")
            if arch_source is not None:
                arch_properties[prop] = arch_source

1100
        # The query is filtered already on the ES side so we don't need to
1101
        # transfer so much data.
1102
1103
1104
        sources = [
            "upload_id",
            "calc_id",
1105
            "encyclopedia",
1106
1107
1108
        ]
        sources += list(es_properties.values())

1109
        s = s.extra(**{
1110
            "_source": {"includes": sources},
1111
1112
1113
1114
1115
1116
1117
1118
1119
            "size": 1,
        })

        response = s.execute()

        # No such material
        if len(response) == 0:
            abort(404, message="There is no material {} with calculation {}".format(material_id, calc_id))

1120
1121
1122
        # Add references that are to be read from the archive
        for ref in references:
            arch_path = response[0]
Lauri Himanen's avatar
Lauri Himanen committed
1123
1124
1125
1126
1127
1128
1129
            try:
                for attr in es_properties[ref].split("."):
                    arch_path = arch_path[attr]
            except KeyError:
                pass
            else:
                arch_properties[ref] = arch_path
1130
1131
            del es_properties[ref]

1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        # If any of the requested properties require data from the Archive, the
        # file is opened and read.
        result = {}
        if len(arch_properties) != 0:
            arch_paths = set(arch_properties.values())
            entry = response[0]
            upload_id = entry.upload_id
            calc_id = entry.calc_id
            data = read_archive(
                upload_id,
                calc_id,
                arch_paths,
            )

            # Add results from archive
            for key, value in arch_properties.items():
                value = data[value]
1149
1150
1151

                # DOS results are simplified
                if key == "electronic_dos":
Lauri Himanen's avatar
Lauri Himanen committed
1152
1153
1154
1155
1156
1157
                    if "dos_energies_normalized" in value:
                        value["dos_energies"] = value["dos_energies_normalized"]
                        del value["dos_energies_normalized"]
                    if "dos_values_normalized" in value:
                        value["dos_values"] = value["dos_values_normalized"]
                        del value["dos_values_normalized"]
1158
1159
1160
                    del value["dos_integrated_values"]
                    del value["dos_fermi_energy"]

1161
1162
1163
                result[key] = value

        # Add results from ES
1164
1165
        for prop, es_source in es_properties.items():
            value = response[0]
Lauri Himanen's avatar
Lauri Himanen committed
1166
1167
1168
1169
1170
1171
1172
1173
1174
            try:
                for attr in es_source.split("."):
                    value = value[attr]
            except KeyError:
                pass
            else:
                if isinstance(value, AttrDict):
                    value = value.to_dict()
                result[prop] = value
1175
1176
1177
1178
1179

        return result, 200


def read_archive(upload_id: str, calc_id: str, paths: List[str]) -> Dict[str, MSection]:
1180
    """Used to read data from the archive.
1181
1182
1183
1184
1185
1186
1187
1188
1189

    Args:
        upload_id: Upload id.
        calc_id: Calculation id.
        paths: List of metainfo paths to read and return.

    Returns:
        For each path, a dictionary containing the path as key and the returned
        section as value.
1190
    """
1191
1192
1193
1194
    if isinstance(paths, str):
        paths = [paths]

    result = {}
1195
1196
1197
    upload_files = files.UploadFiles.get(upload_id)
    with upload_files.read_archive(calc_id) as archive:
        data = archive[calc_id]
1198
        for path in paths:
1199
1200
1201
1202
            i_path = path
            if i_path .startswith("/"):
                i_path = i_path[1:]
            parts: Sequence[Union[str, int]] = i_path.split("/")
1203
            for part in parts:
1204
1205
1206
1207
                try:
                    part = int(part)
                except Exception:
                    pass
1208
                data = data[part]
1209
            if isinstance(data, ArchiveObject):
1210
1211
                data = data.to_dict()
            result[path] = data
1212

1213
    return result