classify4me_prototypes.py 9.46 KB
Newer Older
1
2
3
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
4
5
6
Reads calculation data and classifies their structures by prototypes 
on the basis of the space_group and normalized_wyckoff, and adds labels to the calculations
 - prototype_label (with labels in the same format as 
7
8
9
10
11
12
13
14
15
in the read_prototypes function).
"""

from __future__ import absolute_import

__author__ = "Daria M. Tomecka and Fawzi Mohamed"
__copyright__ = "Copyright 2017, The NOMAD Project"
__maintainer__ = "Daria M. Tomecka"
__email__ = "tomeckadm@gmail.com;"
16
__date__ = "12/07/17"
17
18
19

import sys
import ase.io
20
from ase.data import chemical_symbols
21
22
23
24
25
26
import json
import numpy as np
import time
import datetime
import os, os.path
import logging
27
28
import functools
import fractions
29
30

import setup_paths
31
32

### new updated location for the prototypes
Daria M. Tomecka's avatar
Daria M. Tomecka committed
33
from nomadcore.structure_types import structure_types_by_spacegroup as str_types_by_spg
34
35
36
37
38
39
40
41
42
from nomadcore.parse_streamed_dicts import ParseStreamedDicts
from nomadcore.local_meta_info import loadJsonFile, InfoKindEl
from nomadcore.parser_backend import JsonParseEventsWriterBackend


#prototypes_file = os.path.normpath("/nomad-lab-base/analysis-tools/structural-similarity/python-modules/nomad_sim/structure_types.py")

import sys
#print(sys.path)
Daria M. Tomecka's avatar
Daria M. Tomecka committed
43
#sys.path.append('/home/beaker/py3k/lib/python3.5/')
44
import spglib
45

46
47
48
49
50
51
52
import logging

#LOGGER = logging.getLogger(__name__)
#logging.basicConfig(level=logging.ERROR)


atomSpecies = None
53

54
cell = None
55
56
57
58
59
60
61
62
63
64

def get_normalized_wyckoff(atomic_number, wyckoff):
    """Returns a normalized Wyckoff sequence for the given atomic numbers and
    wyckoff symbols.
    """
    # print("at", atomic_number, wyckoff)
    atomCount = {}
    for nr in atomic_number:
        atomCount[nr] = atomCount.get(nr, 0) + 1
    wycDict = {}
65
    #logging.error("atomic_number: %s, wyckoff: %s", atomic_number, wyckoff) 
66
67
    for i, wk in enumerate(wyckoff):
        oldVal = wycDict.get(wk, {})
68
        #print("i:",i, "wyckoff", wyckoff, "wk", wk)
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
        nr = atomic_number[i]
        oldVal[nr] = oldVal.get(nr, 0) + 1
        wycDict[wk] = oldVal
    sortedWyc = list(wycDict.keys())
    sortedWyc.sort()

    def cmpp(a, b):
        return ((a < b) - (a > b))

    def compareAtNr(at1, at2):
        """Returns a normalized Wyckoff sequence for the given atomic numbers and
        wyckoff symbols.
        """
        # print("at", atomic_number, wyckoff)
        atomCount = {}
        for nr in atomic_number:
            atomCount[nr] = atomCount.get(nr, 0) + 1
        wycDict = {}
        for i, wk in enumerate(wyckoff):
            oldVal = wycDict.get(wk, {})
            nr = atomic_number[i]
            oldVal[nr] = oldVal.get(nr, 0) + 1
            wycDict[wk] = oldVal
        sortedWyc = list(wycDict.keys())
        sortedWyc.sort()

    def cmpp(a, b):
        return ((a < b) - (a > b))

    def compareAtNr(at1, at2):
        c = cmpp(atomCount[at1], atomCount[at2])
        if (c != 0):
            return c
        for wk in sortedWyc:
            p = wycDict[wk]
            c = cmpp(p.get(at1, 0), p.get(at2, 0))
            if c != 0:
                return c
        return 0
108

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    sortedAt = list(atomCount.keys())
    sortedAt.sort(key=functools.cmp_to_key(compareAtNr))
    standardAtomNames = {}
    for i, at in enumerate(sortedAt):
        standardAtomNames[at] = ("X_%d" % i)
    standardWyc = {}
    for wk, ats in wycDict.items():
        stdAts = {}
        for at, count in ats.items():
            stdAts[standardAtomNames[at]] = count
        standardWyc[wk] = stdAts
    if standardWyc:
        counts = [c for x in standardWyc.values() for c in x.values()]
        # logging.error("counts: %s", counts)
        gcd = counts[0]
        for c in counts[1:]:
            gcd = fractions.gcd(gcd,c)
        if gcd != 1:
            for wk,d in standardWyc.items():
                for at,c in d.items():
                    d[at] = c // gcd
    return standardWyc



def get_structure_type(space_group, norm_wyckoff):
    """Returns the information on the prototype.
    """
    structure_type_info = {}

    for type_description in str_types_by_spg.get((space_group), []):
140
        
141
        current_norm_wyckoffs = type_description.get("normalized_wyckoff_spg")
142
143
144
145
146
147
148
149
150
151
152
153
        if current_norm_wyckoffs and current_norm_wyckoffs == norm_wyckoff:
            structure_type_info = type_description
            break
    if structure_type_info:
        return structure_type_info
    else:
        return None



def _structure_type_info(self):
    """Known structure types"""
154
    return get_structure_type(
155
156
157
        self.space_group,
        self.normalized_wyckoff)

158

159
def toAtomNr(string):
160
    "returns the atom number of the given symbol"
161
    baseStr = string[:3].title()
162
163
164
165
166
167
168
169
170
    if baseStr.startswith("Uu") and baseStr in chemical_symbols[1:]:
        return chemical_symbols.index(baseStr)
    if baseStr[:2] in chemical_symbols[1:]:
        return chemical_symbols.index(baseStr[:2])
    elif baseStr[:1] in chemical_symbols[1:]:
        return chemical_symbols.index(baseStr[:1])
    else:
        return 0

171
def dictToNarray(dictValue):
172
    """function that gets the dictionary with flat data ans shape and give the array"""
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    v=dictValue['flatData']
    return np.reshape(np.asarray(v), dictValue['shape'])

def protoNormalizeWycoff(protoDict):
    """recalculates the normalized wyckoff values for the given prototype dictionary"""
    cell = np.asarray(protoDict['lattice_vectors'])
    atomSpecies = [toAtomNr(at) for at in protoDict['atom_labels']]
    atomPos = np.asarray(protoDict['atom_positions'])
    symm = systemToSpg(cell, atomSpecies, atomPos)
    wyckoffs = symm.get("wyckoffs")
    norm_wyckoff = get_normalized_wyckoff(atomSpecies,wyckoffs) 
    return norm_wyckoff

def updatePrototypesWyckoff(protos):
    for sp, pts in protos.items():
        for protoDict in pts:
            try:
                wy = protoNormalizeWycoff(protoDict)
                protoDict['normalized_wyckoff_spg'] = wy
            except:
Daria M. Tomecka's avatar
Daria M. Tomecka committed
193
                logging.exception("Failed to compute normalized wyckoffs for %s", json.dumps(protoDict))
194
195
196
197
198
199
200
201
202

def systemToSpg(cell, atomSpecies, atomPos):
    """uses spg to calculate the symmetry of the given system"""
    acell = cell*1.0e10
    cellInv = np.linalg.inv(cell)
    symm = spglib.get_symmetry_dataset((acell, np.dot(atomPos,cellInv), atomSpecies),
                                                 0.002, -1) # use m instead of Angstrom?

    return symm
203
204
205

def classify_by_norm_wyckoff(sectionSystem):
    try:
206
        
207
208
209
        ###
        #atomic_number = atom_species
        #as in the normalized version
210
211
        cell = None
        conf = sectionSystem
Daria M. Tomecka's avatar
Daria M. Tomecka committed
212
        
213
        lab = conf.get("atom_labels", None)
Daria M. Tomecka's avatar
Daria M. Tomecka committed
214
        if lab is None : return None
215
        ##periodicDirs = conf.get("configuration_periodic_dimensions", periodicDirs)
Daria M. Tomecka's avatar
Daria M. Tomecka committed
216
        atomSpecies = [toAtomNr(l) for l in lab['flatData']]
217
218
        #print (atomSpecies)
        newCell = conf.get("simulation_cell")
Daria M. Tomecka's avatar
Daria M. Tomecka committed
219
220
221
        
        if newCell is None : return None
        
222
223
224
225
226
        if newCell:
            cell = dictToNarray(newCell)
        symm = None
        #print("***full:",cell)
        #acell = cell.reshape(3,3)
Daria M. Tomecka's avatar
Daria M. Tomecka committed
227
228
229
230
        atomPos = dictToNarray(conf.get("atom_positions"))
        
        if atomPos is None : return None
        
231
232
233
        symm = systemToSpg(cell, atomSpecies, atomPos)
        wyckoffs = symm.get("wyckoffs")
        spg_nr = symm.get("number")
234
235
        
        ### adds recalculated wyckoff positions
236
        updatePrototypesWyckoff(str_types_by_spg)
237
238
239

        ###
        norm_wyckoff = get_normalized_wyckoff(atomSpecies,wyckoffs) 
240
        protoDict = get_structure_type(spg_nr, norm_wyckoff)
241
242
243
244
245
246
247
248
249
250
251

        if protoDict is None:
            proto = "%d-_" % spg_nr
        else:
            #if protoDict.get("Notes","") not in ["", "_", "-", "–"]:
            #    proto = '%d-%s' % (spg_nr, protoDict)
            #else:
            #proto = '%d-%s' % (spg_nr, protoDict)
            proto = '%d-%s-%s' % (spg_nr, protoDict.get("Prototype","-"),protoDict.get("Pearsons Symbol","-"))
        return proto
    except:
252
253
        #logging.exception("failure while computing for %r",json_file_name)
        logging.exception("failure while computing for that example")
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270

    return None

#classify_by_norm_wyckoff(json_list)
            

def main():
    metapath = '../../../../nomad-meta-info/meta_info/nomad_meta_info/' +\
          'common.nomadmetainfo.json'
    metaInfoPath = os.path.normpath(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), metapath))
  
    metaInfoEnv, warns = loadJsonFile(filePath=metaInfoPath,
                                      dependencyLoader=None,
                                      extraArgsHandling=InfoKindEl.ADD_EXTRA_ARGS,
                                      uri=None)
    backend = JsonParseEventsWriterBackend(metaInfoEnv)
Daria M. Tomecka's avatar
Daria M. Tomecka committed
271
272
273
274
275
276
277
278
    #Start 
    calcContext=sys.argv[1]
    backend.startedParsingSession(
      calcContext,
      parserInfo = {'name':'PrototypesNormalizer', 'version': '1.0'})

  

279
280
281
    dictReader = ParseStreamedDicts(sys.stdin)
    while True:
        sectSys = dictReader.readNextDict()
Daria M. Tomecka's avatar
Daria M. Tomecka committed
282
283
        if sectSys is None:
            break
Daria M. Tomecka's avatar
Daria M. Tomecka committed
284
        try:
Daria M. Tomecka's avatar
Daria M. Tomecka committed
285
286
287
288
289
290
            label = classify_by_norm_wyckoff(sectSys)
            if label:
                backend.openContext(sectSys['uri'])
                backend.addValue("prototype_label", label)
                backend.closeContext(sectSys['uri'])
                sys.stdout.flush()
Daria M. Tomecka's avatar
Daria M. Tomecka committed
291
292
293
294
295
296
297
        except:
            logging.exception("exception trying to calculate prototype for %s",sectSys)

    backend.finishedParsingSession("ParseSuccess", None)
    sys.stdout.flush()
 

298
299
300
301

if __name__ == '__main__':
    main()