encyclopedia.py 21.7 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

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

from nomad import config
26
from nomad.units import ureg
Lauri Himanen's avatar
Lauri Himanen committed
27
from nomad.atomutils import get_hill_decomposition
28
from .api import api
29

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

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


53
def get_material(es_doc, keys):
54
55
    """Used to form a material definition for "materials/<material_id>" from
    the given ElasticSearch root document.
56
57
    """
    result = {}
58
59
60
61
62
63
64
65
66
    for key in keys:
        es_key = material_prop_map[key]
        try:
            value = es_doc
            for part in es_key.split("."):
                value = getattr(value, part)
        except AttributeError:
            value = None
        result[key] = value
67
68
69
70
71

    return result


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


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

119
120
121
122
123
124
125
126
127
        # 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(
128
            "bool",
129
            filter=[
130
131
132
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
133
134
135
            ]
        )
        s = s.query(query)
136

137
        # The query is collapsed already on the ES side so we don"t need to
138
139
140
        # transfer so much data.
        s = s.extra(**{
            "collapse": {"field": "encyclopedia.material.material_id"},
141
            "_source": {"includes": es_keys},
142
143
        })

144
145
        response = s.execute()

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

150
        # Create result JSON
151
        entry = response[0]
152
        result = get_material(entry, keys)
153

154
155
156
        return result, 200


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


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

        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")
231
        add_terms_filter("space_group_number", "encyclopedia.material.bulk.space_group_number")
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        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")
276

277
278
        # Create query for elements or formula
        search_by = data["search_by"]
279
        mode = search_by["mode"]
280
        formula = search_by["formula"]
Lauri Himanen's avatar
Lauri Himanen committed
281
        elements = search_by["element"]
282
283
284
        exclusive = search_by["exclusive"]

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

            # With exclusive search we look for exact match
            if exclusive:
Lauri Himanen's avatar
Lauri Himanen committed
313
                filters.append(Q("term", **{"encyclopedia.material.species_and_counts.keyword": query_string}))
314
315
316
317
318
            # 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
                    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"}
335
336
                ))

337
338
339
        page = search_by["page"]
        per_page = search_by["per_page"]
        bool_query = Q(
340
            "bool",
341
342
343
344
            filter=filters,
            must_not=must_nots,
            must=musts,
        )
345

346
347
348
349
350
351
352
353
354
355
356
357
358
        # 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.
        if mode == "aggregate":
            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:
359
                # "Composite" to enable scrolling, "Terms" to enable selecting
360
361
362
                # by material_id and "Top Hits" to fetch a single
                # representative material document. Unnecessary fields are
                # filtered to reduce data transfer.
363
364
365
                terms_agg = A("terms", field="encyclopedia.material.material_id")
                composite_kwargs = {"sources": {"materials": terms_agg}, "size": per_page}
                if after is not None:
366
                    composite_kwargs["after"] = after
367
                composite_agg = A("composite", **composite_kwargs)
368
369
                composite_agg.metric("representative", A(
                    "top_hits",
370
                    size=1,
371
                    _source={"includes": list(material_prop_map.values())},
372
                ))
373
374
375
376
377
378
379
380
381
382
                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:
383
                    abort(404, message="No materials found for the given search criteria or pagination.")
384
385
386
387
388
                after = response.aggs.materials["after_key"]

            # Gather results from aggregations
            result_list = []
            materials = response.aggs.materials.buckets
389
            keys = list(material_prop_map.keys())
390
391
            for material in materials:
                representative = material["representative"][0]
392
                mat_dict = get_material(representative, keys)
393
394
395
396
397
398
399
400
401
                mat_dict["n_of_calculations"] = material.doc_count
                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
402
        # corresponding to the query, offers full pagination, doesn"t include
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
        # 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:
418
                abort(404, message="No materials found for the given search criteria or pagination.")
419
420
421

            # Loop over materials
            result_list = []
422
            keys = list(material_prop_map.keys())
423
            for material in response:
424
                mat_result = get_material(material, keys)
425
426
427
428
429
430
431
432
433
                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,
            }
434
435
436

        result = {
            "results": result_list,
437
438
439
            "total_results": len(result_list),
            "es_query": s.to_dict(),
            "pages": pages,
440
        }
441
        return result, 200
442
443


444
group_result = api.model("group_result", {
445
446
447
448
449
450
451
    "calculation_list": fields.List(fields.String),
    "energy_minimum": fields.Float,
    "group_hash": fields.String,
    "group_type": fields.String,
    "nr_of_calculations": fields.Integer,
    "representative_calculation_id": fields.String,
})
452
453
454
groups_result = api.model("groups_result", {
    "total_groups": fields.Integer(allow_null=False),
    "groups": fields.List(fields.Nested(group_result)),
455
})
456
457
458
459
460
461
group_source = {
    "includes": [
        "calc_id",
        "encyclopedia.properties.energies.energy_total",
    ]
}
462
463


464
@ns.route("/materials/<string:material_id>/groups")
Lauri Himanen's avatar
Lauri Himanen committed
465
class EncGroupsResource(Resource):
466
467
468
    @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
469
470
    @api.expect(material_query, validate=False)
    @api.marshal_with(groups_result, skip_none=True)
471
    @api.doc("enc_materials")
Lauri Himanen's avatar
Lauri Himanen committed
472
473
    def get(self, material_id):

474
475
476
        # Find entries for the given material, which have EOS or parameter
        # variation hashes set.
        bool_query = Q(
477
            "bool",
478
            filter=[
479
480
481
                Q("term", published=True),
                Q("term", with_embargo=False),
                Q("term", encyclopedia__material__material_id=material_id),
482
483
484
485
486
487
488
489
490
491
            ],
            must=[
                Q("exists", field="encyclopedia.properties.energies.energy_total"),
            ],
            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
492
493

        s = Search(index=config.elastic.index_name)
494
495
496
497
498
499
500
501
502
503
504
        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
505
        # "index.max_inner_result_window" that limits the number of results
506
507
508
509
510
511
512
513
514
515
516
        # 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)
517

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

523
524
525
526
        # No hits on the top query level
        response = s.execute()
        n_hits = response.hits.total
        if n_hits == 0:
527
            abort(404, message="The specified material could not be found.")
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

        # Collect information for each group from the aggregations
        groups = []
        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]
            group_dict = {
                "group_hash": group_hash,
                "group_type": group_type,
                "nr_of_calculations": len(calculations),
                "representative_calculation_id": hits[0].calc_id,
                "calculation_list": calculations,
                "energy_minimum": hits[0].encyclopedia.properties.energies.energy_total,
            }
            return group_dict
Lauri Himanen's avatar
Lauri Himanen committed
546

547
548
549
550
551
552
553
554
555
556
557
        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