encyclopedia.py 36 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
21

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

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

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

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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",
}
53
54


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

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

    return result


material_query = api.parser()
77
78
79
80
81
82
83
84
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", {
85
86
    # General
    "material_id": fields.String,
87
88
    "formula": fields.String,
    "formula_reduced": fields.String,
89
    "system_type": fields.String,
90
    "n_matches": fields.Integer,
91
    # Bulk only
92
    "has_free_wyckoff_parameters": fields.Boolean,
93
    "strukturbericht_designation": fields.String,
94
    "material_name": fields.String,
95
96
    "bravais_lattice": fields.String,
    "crystal_system": fields.String,
97
    "point_group": fields.String,
98
99
100
    "space_group_number": fields.Integer,
    "space_group_international_short_symbol": fields.String,
    "structure_prototype": fields.String,
101
102
    "structure_type": fields.String,
})
103
104


105
@ns.route("/materials/<string:material_id>")
106
class EncMaterialResource(Resource):
107
108
109
    @api.response(404, "The material does not exist")
    @api.response(200, "Metadata send", fields.Raw)
    @api.doc("material/<material_id>")
110
    @api.expect(material_query)
111
    @api.marshal_with(material_result, skip_none=True)
112
113
114
    def get(self, material_id):
        """Used to retrive basic information related to the specified material.
        """
115
116
117
118
119
120
121
122
123
124
        # 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())

125
126
127
128
129
130
131
132
133
        # 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(
134
            "bool",
135
            filter=[
136
137
138
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
139
140
141
            ]
        )
        s = s.query(query)
142

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

150
151
        response = s.execute()

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

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

160
161
162
        return result, 200


163
range_query = api.model("range_query", {
164
165
166
    "max": fields.Float,
    "min": fields.Float,
})
167
168
materials_query = api.model("materials_input", {
    "search_by": fields.Nested(api.model("search_query", {
169
170
        "exclusive": fields.Boolean(default=False),
        "formula": fields.String,
Lauri Himanen's avatar
Lauri Himanen committed
171
        "element": fields.String,
172
173
174
        "page": fields.Integer(default=1),
        "per_page": fields.Integer(default=25),
        "pagination": fields.Boolean,
175
        "mode": fields.String(default="aggregation"),
176
    })),
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    "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."),
192
})
193
194
195
196
197
198
199
pages_result = api.model("page_info", {
    "per_page": fields.Integer,
    "total": fields.Integer,
    "page": fields.Integer,
    "pages": fields.Integer,
})

200
201
202
materials_result = api.model("materials_result", {
    "total_results": fields.Integer(allow_null=False),
    "results": fields.List(fields.Nested(material_result)),
203
    "pages": fields.Nested(pages_result),
204
    "es_query": fields.String(allow_null=False),
205
206
207
})


208
@ns.route("/materials")
209
class EncMaterialsResource(Resource):
210
211
212
    @api.response(404, "No materials found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
213
    @api.expect(materials_query, validate=False)
214
    @api.marshal_with(materials_result, skip_none=True)
215
    @api.doc("materials")
216
217
218
219
220
221
222
223
224
225
226
227
228
229
    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
230
231
        filters.append(Q("term", published=True))
        filters.append(Q("term", with_embargo=False))
232
233
234
235
236
237
238

        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")
239
        add_terms_filter("space_group_number", "encyclopedia.material.bulk.space_group_number")
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
        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")
284

285
286
        # Create query for elements or formula
        search_by = data["search_by"]
287
        mode = search_by["mode"]
288
        formula = search_by["formula"]
Lauri Himanen's avatar
Lauri Himanen committed
289
        elements = search_by["element"]
290
291
292
        exclusive = search_by["exclusive"]

        if formula is not None:
Lauri Himanen's avatar
Lauri Himanen committed
293
294
            # Here we determine a list of atom types. The types may occur
            # multiple times and at multiple places.
295
296
297
298
299
300
301
302
303
304
            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
305
306
307
308
309
                        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.
310
            names, reduced_counts = get_hill_decomposition(element_list, reduced=True)
Lauri Himanen's avatar
Lauri Himanen committed
311
312
313
314
315
            query_string = []
            for name, count in zip(names, reduced_counts):
                if count == 1:
                    query_string.append(name)
                else:
316
                    query_string.append("{}{}".format(name, int(count)))
Lauri Himanen's avatar
Lauri Himanen committed
317
            query_string = " ".join(query_string)
318
319
320

            # With exclusive search we look for exact match
            if exclusive:
Lauri Himanen's avatar
Lauri Himanen committed
321
                filters.append(Q("term", **{"encyclopedia.material.species_and_counts.keyword": query_string}))
322
323
324
325
326
            # 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
                    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"}
343
344
                ))

345
346
347
        page = search_by["page"]
        per_page = search_by["per_page"]
        bool_query = Q(
348
            "bool",
349
350
351
352
            filter=filters,
            must_not=must_nots,
            must=musts,
        )
353

354
355
356
        # 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.
357
        if mode == "aggregation":
358
359
360
361
362
363
364
365
366
            after = None
            # The loop is awkward, but emulates the old behaviour until the GUI is adapted.
            for _ in range(page):

                # 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:
367
                # "Composite" to enable scrolling, "Terms" to enable selecting
368
369
370
                # by material_id and "Top Hits" to fetch a single
                # representative material document. Unnecessary fields are
                # filtered to reduce data transfer.
371
372
373
                terms_agg = A("terms", field="encyclopedia.material.material_id")
                composite_kwargs = {"sources": {"materials": terms_agg}, "size": per_page}
                if after is not None:
374
                    composite_kwargs["after"] = after
375
                composite_agg = A("composite", **composite_kwargs)
376
377
                composite_agg.metric("representative", A(
                    "top_hits",
378
                    size=1,
379
                    _source={"includes": list(material_prop_map.values())},
380
                ))
381
382
383
384
385
386
387
388
389
390
                s.aggs.bucket("materials", composite_agg)

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

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

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

            # Page information is incomplete for aggregations
            pages = {
                "page": page,
                "per_page": per_page,
            }
        # 2. Collapse approach. Quickly provides a list of materials
410
        # corresponding to the query, offers full pagination, doesn"t include
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
        # 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:
426
                abort(404, message="No materials found for the given search criteria or pagination.")
427
428
429

            # Loop over materials
            result_list = []
430
            keys = list(material_prop_map.keys())
431
            for material in response:
432
                mat_result = get_es_doc_values(material, material_prop_map, keys)
433
434
435
436
437
438
439
440
441
                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,
            }
442
443
444

        result = {
            "results": result_list,
445
446
447
            "total_results": len(result_list),
            "es_query": s.to_dict(),
            "pages": pages,
448
        }
449
        return result, 200
450
451


452
group_result = api.model("group_result", {
453
454
455
    "calculations": fields.List(fields.String),
    "energies": fields.List(fields.Float),
    "volumes": fields.List(fields.Float),
456
457
458
459
    "energy_minimum": fields.Float,
    "group_hash": fields.String,
    "group_type": fields.String,
    "nr_of_calculations": fields.Integer,
460
    "representative_calc_id": fields.String,
461
})
462
463
464
groups_result = api.model("groups_result", {
    "total_groups": fields.Integer(allow_null=False),
    "groups": fields.List(fields.Nested(group_result)),
465
})
466
467
468
469
group_source = {
    "includes": [
        "calc_id",
        "encyclopedia.properties.energies.energy_total",
470
        "encyclopedia.material.idealized_structure.cell_volume",
471
472
    ]
}
473
474


475
@ns.route("/materials/<string:material_id>/groups")
Lauri Himanen's avatar
Lauri Himanen committed
476
class EncGroupsResource(Resource):
477
478
479
    @api.response(404, "Material not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
Lauri Himanen's avatar
Lauri Himanen committed
480
    @api.expect(material_query, validate=False)
481
    @api.marshal_with(groups_result)
482
    @api.doc("enc_materials")
Lauri Himanen's avatar
Lauri Himanen committed
483
484
    def get(self, material_id):

485
486
487
        # Find entries for the given material, which have EOS or parameter
        # variation hashes set.
        bool_query = Q(
488
            "bool",
489
            filter=[
490
491
492
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
493
494
495
            ],
            must=[
                Q("exists", field="encyclopedia.properties.energies.energy_total"),
496
                Q("exists", field="encyclopedia.material.idealized_structure.cell_volume"),
497
498
499
500
501
502
503
            ],
            should=[
                Q("exists", field="encyclopedia.method.group_eos_hash"),
                Q("exists", field="encyclopedia.method.group_parametervariation_hash"),
            ],
            minimum_should_match=1,  # At least one of the should query must match
        )
Lauri Himanen's avatar
Lauri Himanen committed
504
505

        s = Search(index=config.elastic.index_name)
506
507
508
509
510
511
512
513
514
515
516
        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.
        group_eos_bucket = A("terms", field="encyclopedia.method.group_eos_hash", min_doc_count=4)
        group_param_bucket = A("terms", field="encyclopedia.method.group_parametervariation_hash", min_doc_count=2)

        # 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
517
        # "index.max_inner_result_window" that limits the number of results
518
519
520
521
522
523
524
525
526
527
528
        # that an inner result can contain.
        energy_aggregation = A(
            "top_hits",
            _source=group_source,
            sort=[{"encyclopedia.properties.energies.energy_total": {"order": "asc"}}],
            size=100,
        )
        group_eos_bucket.bucket("energies", energy_aggregation)
        group_param_bucket.bucket("energies", energy_aggregation)
        s.aggs.bucket("groups_eos", group_eos_bucket)
        s.aggs.bucket("groups_param", group_param_bucket)
529

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

535
536
        # No hits on the top query level
        response = s.execute()
537
        groups = []
538
539
540
541
542
543
544
545

        # Collect information for each group from the aggregations
        groups_eos = response.aggs.groups_eos.buckets
        groups_param = response.aggs.groups_param.buckets

        def get_group(group, group_type, group_hash):
            hits = group.energies.hits
            calculations = [doc.calc_id for doc in hits]
546
547
            energies = [doc.encyclopedia.properties.energies.energy_total for doc in hits]
            volumes = [doc.encyclopedia.material.idealized_structure.cell_volume for doc in hits]
548
549
550
551
            group_dict = {
                "group_hash": group_hash,
                "group_type": group_type,
                "nr_of_calculations": len(calculations),
552
553
554
555
                "representative_calc_id": hits[0].calc_id,
                "calculations": calculations,
                "energies": energies,
                "volumes": volumes,
556
557
558
                "energy_minimum": hits[0].encyclopedia.properties.energies.energy_total,
            }
            return group_dict
Lauri Himanen's avatar
Lauri Himanen committed
559

560
561
562
563
564
565
566
567
568
569
570
        for group in groups_eos:
            groups.append(get_group(group, "equation of state", group.key))
        for group in groups_param:
            groups.append(get_group(group, "parameter variation", group.key))

        # Return results
        result = {
            "groups": groups,
            "total_groups": len(groups),
        }
        return result, 200
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


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)

        return {prop: []}, 200


604
605
calcs_query = api.parser()
calcs_query.add_argument(
606
607
608
609
610
611
    "page",
    default=0,
    type=int,
    help="The page number to return.",
    location="args"
)
612
calcs_query.add_argument(
613
614
615
616
617
618
619
620
621
622
623
624
    "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",
625
    "core_electron_treatment": "encyclopedia.method.core_electron_treatment",
626
627
628
629
630
631
632
633
634
635
636
    "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,
637
    "core_electron_treatment": fields.String,
638
639
640
641
642
643
644
645
646
647
648
649
650
    "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")
651
class EncCalculationsResource(Resource):
652
653
654
    @api.response(404, "Suggestion not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
655
    @api.expect(calcs_query, validate=False)
656
657
658
659
    @api.doc("enc_calculations")
    def get(self, material_id):
        """Used to return all calculations related to the given material.
        """
660
        args = calcs_query.parse_args()
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
        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
            calc_dict["has_band_structure"] = calc_dict["has_dos"] is not None
            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


710
711
712
713
714
715
716
717
718
719
720
721
722
723
statistics_query = api.model("statistics_query", {
    "calculations": fields.List(fields.String),
})
statistics = api.model("statistics", {
    "min": fields.Float,
    "max": fields.Float,
    "avg": fields.Float,
})
statistics_result = api.model("statistics_result", {
    "cell_volume": fields.Nested(statistics),
})


@ns.route("/materials/<string:material_id>/statistics")
724
725
726
727
class EncCellsResource(Resource):
    @api.response(404, "Suggestion not found")
    @api.response(400, "Bad request")
    @api.response(200, "Metadata send", fields.Raw)
728
729
    @api.expect(statistics_query, validate=False)
    @api.marshal_with(statistics_result, skip_none=True)
730
731
    @api.doc("enc_cells")
    def get(self, material_id):
732
733
        """Used to return statistics related to the specified material and
        calculations.
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
        # Get query parameters as json
        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)

        # Add statistics aggregations
        cell_volume_agg = A(
            "stats",
            field="encyclopedia.material.idealized_structure.cell_volume",
        )
        s.aggs.bucket("cell_volume_stats", cell_volume_agg)

        # Don't return individual documents
        s = s.extra(**{
            "size": 0,
        })

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

        # Return results
        cell_volume_stats = response.aggs.cell_volume_stats
        result = {
            "cell_volume": {
                "min": cell_volume_stats.min,
                "max": cell_volume_stats.max,
                "avg": cell_volume_stats.avg
            }
        }
        return result, 200
782
783
784
785
786
787
788
789
790
791
792
793
794


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)),
})
795
796
797
798
799
800
801
802
lattice_parameters = api.model("lattice_parameters", {
    "a": fields.Float,
    "b": fields.Float,
    "c": fields.Float,
    "alpha": fields.Float,
    "beta": fields.Float,
    "gamma": fields.Float,
})
803
804
805
806
807
808

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)),
809
    "lattice_parameters": fields.Nested(lattice_parameters),
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
    "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
870
871
        ideal_struct_path = "section_metadata/encyclopedia/material/idealized_structure"
        idealized_structure = read_archive(upload_id, calc_id, ideal_struct_path)[ideal_struct_path]
872
873
874
875

        return idealized_structure, 200


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
@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)
    @api.doc("enc_calculation")
    def get(self, material_id, calc_id):
        """Used to return calculation details that are not available in the ES
        index and are instead read from the Archive directly.
        """
        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)

        # The query is filtered already on the ES side so we don"t need to
        # transfer so much data.
        s = s.extra(**{
            "_source": {"includes": [
                "upload_id",
                "calc_id",
                "encyclopedia.properties",
                "encyclopedia.material.material_type",
                "encyclopedia.material.bulk.has_free_wyckoff_parameters"
            ]},
            "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))

        # 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
        paths = ['section_metadata/encyclopedia/material/idealized_structure']
        data = read_archive(
            upload_id,
            calc_id,
            paths,
        )

        # Read the lattice parameters
        ideal_struct = data['section_metadata/encyclopedia/material/idealized_structure']

        # Final result
        result = {
            "lattice_parameters": ideal_struct["lattice_parameters"],
            "energies": entry.encyclopedia.properties.energies.to_dict(),
            "mass_density": entry.encyclopedia.properties.mass_density,
            "atomic_density": entry.encyclopedia.properties.atomic_density,
            "cell_volume": ideal_struct["cell_volume"],
        }

        # Return full Wyckoff position information for bulk structures with
        # free Wyckoff parameters
        if entry.encyclopedia.material.material_type == "bulk":
            if entry.encyclopedia.material.bulk.has_free_wyckoff_parameters:
                result["wyckoff_sets"] = ideal_struct["wyckoff_sets"]

        return result, 200


def read_archive(upload_id: str, calc_id: str, paths: List[str]) -> Dict[str, MSection]:
952
    """Used to read data from the archive.
953
954
955
956
957
958
959
960
961

    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.
962
    """
963
964
965
966
    if isinstance(paths, str):
        paths = [paths]

    result = {}
967
968
969
    upload_files = files.UploadFiles.get(upload_id)
    with upload_files.read_archive(calc_id) as archive:
        data = archive[calc_id]
970
971
972
973
974
975
976
        for path in paths:
            parts = path.split("/")
            for part in parts:
                data = data[part]
            if not isinstance(data, dict):
                data = data.to_dict()
            result[path] = data
977

978
    return result