encyclopedia.py 12.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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.

'''
The encyclopedia API of the nomad@FAIRDI APIs.
'''
18
import re
Lauri Himanen's avatar
Lauri Himanen committed
19
20
from math import gcd
from functools import reduce
21

Lauri Himanen's avatar
Lauri Himanen committed
22
import numpy as np
23
24
25
from flask_restplus import Resource, abort, fields, marshal
from flask import request
from elasticsearch_dsl import Search, Q
26
27

from nomad import config
28
from nomad.units import ureg
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
re_formula = re.compile(r"([A-Z][a-z]?)(\d*)")


def add_result(result, key, function, default=""):
    """Convenience function that attempts to add a value from the ElasticSearch
    result into the given result object. Upon failing returns the specified
    default value.
    """
    try:
        value = function()
    except Exception:
        value = default
    result[key] = value


def get_material(es_doc):
    """Used to form a material definition from the given ElasticSearch root
    document.
    """
    result = {}
    add_result(result, "material_id", lambda: es_doc.encyclopedia.material.material_id, ""),
    add_result(result, "bravais_lattice", lambda: es_doc.encyclopedia.material.bulk.bravais_lattice, ""),
    add_result(result, "crystal_system", lambda: es_doc.encyclopedia.material.bulk.crystal_system, "")
    add_result(result, "formula", lambda: es_doc.encyclopedia.material.formula, "")
    add_result(result, "formula_reduced", lambda: es_doc.encyclopedia.material.formula_reduced, "")
    add_result(result, "material_name", lambda: es_doc.encyclopedia.material.material_name, "")
    add_result(result, "point_group", lambda: es_doc.encyclopedia.material.bulk.point_group, "")
    add_result(result, "space_group", lambda: es_doc.encyclopedia.material.bulk.space_group_number, "")
    add_result(result, "structure_type", lambda: es_doc.encyclopedia.material.bulk.structure_type, "")
    add_result(result, "system_type", lambda: es_doc.encyclopedia.material.material_type, "")

    return result


material_query = api.parser()
material_query.add_argument('material_id', type=str, help='Identifier for the searched material.', location='args')
material_result = api.model('material_result', {
    "bravais_lattice": fields.String,
    "crystal_system": fields.String,
    "formula": fields.String,
    "formula_reduced": fields.String,
    "material_name": fields.String,
    "point_group": fields.String,
    "space_group": fields.Integer(),
    "structure_type": fields.String,
    "system_type": fields.String,
})
80
81
82
83
84
85


@ns.route('/materials/<string:material_id>')
class EncMaterialResource(Resource):
    @api.response(404, 'The material does not exist')
    @api.response(200, 'Metadata send', fields.Raw)
86
87
88
    @api.doc('material/<material_id>')
    @api.expect(material_query)
    @api.marshal_with(material_result)
89
90
91
    def get(self, material_id):
        """Used to retrive basic information related to the specified material.
        """
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

        # 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(
            'bool',
            filter=[
                Q('term', published=True),
                Q('term', with_embargo=False),
                Q('term', encyclopedia__material__material_id=material_id),
            ]
        )
        s = s.query(query)
110
111
        response = s.execute()

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

116
        # Create result JSON
117
        entry = response[0]
118
        result = get_material(entry)
119

120
121
122
123
124
125
126
127
128
129
130
        return result, 200


range_query = api.model('range_query', {
    "max": fields.Float,
    "min": fields.Float,
})
materials_query = api.model('materials_input', {
    'search_by': fields.Nested(api.model('search_query', {
        "exclusive": fields.Boolean(default=False),
        "formula": fields.String,
Lauri Himanen's avatar
Lauri Himanen committed
131
        "element": fields.String,
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
        "page": fields.Integer(default=1),
        "per_page": fields.Integer(default=25),
        "pagination": fields.Boolean,
    })),
    'material_name': fields.List(fields.String),
    'structure_type': fields.List(fields.String),
    'space_group': 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."),
})
materials_result = api.model('materials_result', {
    'pages': fields.Integer(required=True),
    'results': fields.List(fields.Nested(material_result)),
    'total_results': fields.Integer(allow_null=False),
})


@ns.route('/materials')
class EncMaterialsResource(Resource):
    @api.response(404, 'No materials found')
    @api.response(400, 'Bad request')
    @api.response(200, 'Metadata send', fields.Raw)
    @api.expect(materials_query, validate=False)
    @api.marshal_with(materials_result)
    @api.doc('materials')
    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))

        s = Search(index=config.elastic.index_name)
        filters = []
        must_nots = []
        musts = []

        # Add term filters
        filters.append(Q('term', published=True))
        filters.append(Q('term', with_embargo=False))

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

237
238
239
        # Create query for elements or formula
        search_by = data["search_by"]
        formula = search_by["formula"]
Lauri Himanen's avatar
Lauri Himanen committed
240
        elements = search_by["element"]
241
242
243
        exclusive = search_by["exclusive"]

        if formula is not None:
Lauri Himanen's avatar
Lauri Himanen committed
244
245
            # Here we determine a list of atom types. The types may occur
            # multiple times and at multiple places.
246
247
248
249
250
251
252
253
254
255
            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
256
257
258
259
260
                        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.
261
            names, counts = get_hill_decomposition(element_list)
Lauri Himanen's avatar
Lauri Himanen committed
262
263
264
265
266
267
268
269
270
            greatest_common_divisor = reduce(gcd, counts)
            reduced_counts = np.array(counts) / greatest_common_divisor
            query_string = []
            for name, count in zip(names, reduced_counts):
                if count == 1:
                    query_string.append(name)
                else:
                    query_string.append("{}{}".format(name, count))
            query_string = " ".join(query_string)
271
272
273

            # With exclusive search we look for exact match
            if exclusive:
Lauri Himanen's avatar
Lauri Himanen committed
274
                filters.append(Q("term", **{"encyclopedia.material.species_and_counts.keyword": query_string}))
275
276
277
278
279
            # 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
                    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"}
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
                ))

        # Prepare the final boolean query that combines the different queries
        filter_query = Q('bool', filter=filters, must_not=must_nots, must=musts)
        s = s.query(filter_query)

        # Execute query
        response = s.execute()

        # No matches
        if len(response) == 0:
            abort(404, message='No materials found for the given search criteria.')

        # Create final result dictionary
        result_list = [get_material(es_doc) for es_doc in response]
        result = {
            "total_results": len(result_list),
            "pages": None,
            "results": result_list,
        }
316
        return result, 200
317
318
319
320
321
322
323
324
325
326

# @ns.route('/esmaterials')
# class EncESMaterialsResource(Resource):
    # @api.response(404, 'No materials found')
    # @api.response(200, 'Metadata send', fields.Raw)
    # @api.doc('materials')
    # def post(self):
        # """Used to query a list of materials with the given ElasticSearch JSON
        # query.
        # """