main.py 21.1 KB
Newer Older
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
1
from __future__ import print_function
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
2
import os
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
3 4
import sys
import setup_paths
5
from glob import glob
6
import re
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
7

8 9
import numpy as np
from ase.data import chemical_symbols
10
from ase import Atoms
11

12 13
from nomadcore.simple_parser import (mainFunction, SimpleMatcher as SM,
                                     AncillaryParser)
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
14 15
from nomadcore.local_meta_info import loadJsonFile, InfoKindEl
from nomadcore.unit_conversion.unit_conversion \
16
    import register_userdefined_quantity, convert_unit
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
17

18
from util import floating, integer
19
from inputvars import varlist
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
20

Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
21 22 23 24 25 26 27 28
metaInfoPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"../../../../nomad-meta-info/meta_info/nomad_meta_info/siesta.nomadmetainfo.json"))
metaInfoEnv, warnings = loadJsonFile(filePath=metaInfoPath,
                                     dependencyLoader=None,
                                     extraArgsHandling=InfoKindEl.ADD_EXTRA_ARGS,
                                     uri=None)

parser_info = {'name':'siesta-parser', 'version': '1.0'}

29

30
def siesta_energy(title, meta, **kwargs):
31
    return SM(r'siesta:\s*%s\s*=\s*(?P<%s__eV>\S+)' % (title, meta),
32
              name=meta, **kwargs)
33

34 35 36 37 38 39 40 41 42 43 44
def line_iter(fd, linepattern = re.compile(r'\s*([^#]+)')):
    # Strip off comments and whitespace, return only non-empty strings
    for line in fd:
        match = linepattern.match(line)
        if match:
            line = match.group().rstrip()
            if line:
                yield line


def get_input_metadata(inputvars_file, use_new_format):
45
    inputvars = {}
46 47 48 49 50 51 52 53 54 55 56 57
    blocks = {}

    varset = set(varlist)

    def addvar(tokens):
        name = tokens[0]
        val = ' '.join(tokens[1:])
        if name in varset:
            inputvars[name] = val

    currentblock = None

58
    with open(inputvars_file) as fd:
59
        lines = line_iter(fd)
60

61
        for line in lines:
62
            tokens = line.split()
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
            assert len(tokens) > 0

            if tokens[0].startswith('%'):
                if tokens[0].lower() == '%block':
                    #assert currentblock == None
                    currentblock = []
                    blocks[tokens[1]] = currentblock
                elif tokens[0].lower() == '%endblock':
                    currentblock = None
                else:
                    raise ValueError('Unknown: %s' % tokens[0])
            else:
                if use_new_format:
                    if line.startswith(' '):
                        assert currentblock is not None
                        currentblock.append(tokens)
                    else:
                        currentblock = None
                        addvar(tokens)
                else:
                    if currentblock is not None:
                        currentblock.append(tokens)
                    else:
                        addvar(tokens)

    return inputvars, blocks
89 90


91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
"""
%block PAO.Basis                 # Define Basis set
O                     2                    # Species label, number of l-shells
 n=2   0   2                         # n, l, Nzeta
   3.305      2.479   
   1.000      1.000   
 n=2   1   2 P   1                   # n, l, Nzeta, Polarization, NzetaPol
   3.937      2.542   
   1.000      1.000   
H                     1                    # Species label, number of l-shells
 n=1   0   2 P   1                   # n, l, Nzeta, Polarization, NzetaPol
   4.709      3.760   
   1.000      1.000   
%endblock PAO.Basis
"""

107

Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
108 109 110

class SiestaContext(object):
    def __init__(self):
111
        self.fname = None  # The file that we are parsing
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
112
        self.dirname = None  # Base directory of calculations
113 114 115 116 117 118 119 120 121 122 123 124 125
        #self.parser = None  # The parser object
        self.format = None  # 'old' or 'new'; when parsing version

        # label and things determined by label
        self.label = None
        self.files = None  # Dict of files
        self.blocks = None  # Dict of input blocks (coords, cell, etc.)

        self._is_last_configuration = False  # XXX
        self.data = {}
        self.special_input_vars = {}

        self.system_meta = {}
126
        self.section_refs = {}  # {name: gindex, ...}
127 128 129 130 131 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

    def multi_sm0(self, pattern, var, dtypes=None, **kwargs):
        pat = re.compile(pattern)
        ngroups = pat.groups
        if dtypes is None:
            dtypes = [float] * ngroups
        else:
            assert len(dtypes) == ngroups

        class LineBuf:
            def __init__(self, ctxt):
                self.lines = []
                self.ctxt = ctxt

            def adhoc_addrow(self, parser):
                line = parser.fIn.readline()
                print('LINE', line)
                groups = pat.match(line).groups()
                results = [dtype(group)
                           for dtype, group in zip(dtypes, groups)]
                self.lines.append(results)

            def _build_array(self, parser):
                arr = np.array(self.lines)
                self.ctxt.data[var] = arr
                print('SET', var, arr)
                ksdfjksjdf
                self.lines = []

        linebuf = LineBuf(self)
        sm = SM(r'', weak=True,
                forwardMatch=True,
                subFlags=SM.SubFlags.Sequenced,
                subMatchers=[
                    SM(pattern,
                       repeats=True,
                       forwardMatch=True,
                       required=True,
                       adHoc=linebuf.adhoc_addrow),
                    SM(r'', endReStr='', adHoc=linebuf._build_array,
                       name='endarray',
                       forwardMatch=True)
                ], **kwargs)
        return sm

    def adhoc_format_new(self, parser):
        assert self.format is None
        self.format = 'new'

    def adhoc_format_old(self, parser):
        assert self.format is None
        self.format = 'old'
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
179

Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
180
    def adhoc_set_label(self, parser):
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
181 182 183 184
        # ASSUMPTION: the parser fIn is in the 'root' of whatever was uploaded.
        # This may not be true.  Figure out how to do this in general.
        line = parser.fIn.readline()
        assert line.startswith('reinit: System Label:')
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        self.label = label = line.split()[-1]
        dirname = self.dirname

        files = {}

        for fileid in ['EIG', 'KP']:
            path = os.path.join(dirname, '%s.%s' % (label, fileid))
            if os.path.isfile(path):
                files[fileid] = path
            # Warn if files are not present?
            #
            # Also: input file
            #       input parser logfile
            #
            # what else?  We already get force/stress/positions from stdout.
        if self.format == 'new':
            inplogfiles = glob('%s/fdf-*.log' % dirname)
            if inplogfiles:
                inplogfiles.sort()
                files['inputlog'] = inplogfiles[-1]
        else:
            assert self.format == 'old', self.format
            files['inputlog'] = os.path.join(dirname, 'out.fdf')
        self.files = files
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
209 210 211 212 213

    def startedParsing(self, fname, parser):
        self.fname = fname
        path = os.path.abspath(fname)
        self.dirname, _ = os.path.split(path)
214
        #self.parser = parser
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
215

Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
216 217 218 219 220 221 222 223 224 225 226 227
    def onClose_x_siesta_section_xc_authors(self, backend, gindex, section):
        authors = section['x_siesta_xc_authors']
        if authors is None:
            raise ValueError('XC authors not found!')

        assert len(authors) == 1
        authors = authors[0]

        mapping = {'CA': ('LDA_X', 'LDA_C_PZ'),
                   'PZ': ('LDA_X', 'LDA_C_PZ'),
                   'PW92': ('LDA_X', 'LDA_C_PW'),
                   #'PW91': '',
228
                   'PBE': ('GGA_X_PBE', 'GGA_C_PBE'),
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
                   'revPBE': ('GGA_X_PBE_R', 'GGA_C_PBE'),
                   'RPBE': ('GGA_X_RPBE', 'GGA_C_PBE'),
                   #'WC': ('GGA_X_WC', ),
                   # Siesta does not mention which correlation is used with
                   # the WC functional.  Is it just the PBE one?
                   'AM05': ('GGA_X_AM05', 'GGA_C_AM05'),
                   'PBEsol': ('GGA_X_PBE_SOL', 'GGA_C_PBE_SOL'),
                   'BLYP': ('GGA_X_B88 + GGA_C_LYP')}
        xc = mapping.get(authors)

        if xc is None:
            raise ValueError('XC functional %s unsupported by parser'
                             % authors)

        for funcname in xc:
            gid = backend.openSection('section_XC_functionals')
            backend.addValue('XC_functional_name', funcname)
            backend.closeSection('section_XC_functionals', gid)
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
247 248 249 250

    def onClose_section_eigenvalues(self, backend, gindex, section):
        self.read_eigenvalues(backend)

251 252 253 254 255 256 257 258 259 260
    def onOpen_section_method(self, backend, gindex, section):
        self.section_refs['method'] = gindex

    def onOpen_section_system(self, backend, gindex, section):
        self.section_refs['system'] = gindex

    def onClose_section_system(self, backend, gindex, section):
        data = self.data
        meta = self.system_meta

261 262 263 264 265 266 267 268 269 270 271 272 273
        latvec = data.pop('block_lattice_vectors', None)
        if latvec is not None:
            latvec = latvec.astype(float)
            size = self.special_input_vars['LatticeConstant']
            size, unit = size.split()
            #assert unit == 'ang', unit
            unit = {'ang': 'angstrom',
                    'Bohr': 'bohr'}[unit]

            size = float(size)
            size = convert_unit(size, unit)
            meta['simulation_cell'] = latvec * size

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        cell = data.pop('outcell_ang', None)
        cell2 = data.pop('auto_unit_cell_ang', None)
        if cell2 is not None:
            cell = cell2

        if cell is not None:
            cell = cell.astype(float)
            cell = convert_unit(cell, 'angstrom')
            meta['simulation_cell'] = cell

        labels = data.pop('block_species_label', None)
        if labels is not None:
            assert labels.shape[1] == 1
            labels = labels[:, 0]
            self.labels = labels

        block_coords_and_species = data.pop('block_coords_and_species', None)
        coords_and_species = data.pop('coords_and_species', None)

        if coords_and_species is None:
            coords_and_species = block_coords_and_species

        if coords_and_species is not None:
            coords = coords_and_species[:, :3].astype(float)

            unit = self.special_input_vars['AtomicCoordinatesFormat']
            if unit == 'Ang':
                coords = convert_unit(coords, 'angstrom')
            elif unit in ['Fractional', 'ScaledCartesian']:
                a = Atoms('%dX' % len(coords),
                          scaled_positions=coords,
                          cell=meta['simulation_cell'])
                coords = a.positions
            else:
                raise ValueError('Unknown: %s' % unit)
            meta['atom_positions'] = coords

            species_index = coords_and_species[:, 3].astype(int)

            atom_labels = np.array([self.labels[i - 1] for i in species_index])
            meta['atom_labels'] = atom_labels

        positions = self.data.pop('outcoord_ang', None)
        if positions is not None:
            positions = convert_unit(positions.astype(float), 'angstrom')
            meta['atom_positions'] = positions

        for key, value in meta.items():
            backend.addArrayValues(key, value)

324 325 326
        backend.addArrayValues('configuration_periodic_dimensions',
                               np.ones(3, bool))

327 328
        assert len(self.data) == 0, self.data

329 330 331 332 333 334 335 336 337 338 339
    def onClose_section_run(self, backend, gindex, section):
        pass

    def onClose_section_single_configuration_calculation(self, backend,
                                                         gindex, section):
        forces = self.data.pop('forces_ev_ang', None)
        if forces is not None:
            forces = forces.astype(float)
            forces = convert_unit(forces, 'eV/angstrom')
            backend.addArrayValues('atom_forces_free_raw', forces)

340 341 342 343 344 345
        stress = self.data.pop('stress_tensor_ev_ang', None)
        if stress is not None:
            stress = stress.astype(float)
            stress = convert_unit(stress, 'eV/angstrom^3')
            backend.addArrayValues('stress_tensor', stress)

346 347 348 349 350
        backend.addValue('single_configuration_to_calculation_method_ref',
                         self.section_refs['method'])
        backend.addValue('single_configuration_calculation_to_system_ref',
                         self.section_refs['system'])

351 352 353 354 355
    def onClose_x_siesta_section_input(self, backend, gindex, section):
        inputvars_file = self.files.get('inputlog')
        if inputvars_file is None:
            return

356 357 358 359 360 361 362 363 364 365 366
        inputvars, blocks = get_input_metadata(inputvars_file,
                                               self.format == 'new')
        for varname, value in inputvars.items():
            backend.addValue('x_siesta_input_%s' % varname, value)

        for special_name in ['LatticeConstant',
                             'AtomicCoordinatesFormat',
                             'AtomicCoordinatesFormatOut']:
            self.special_input_vars[special_name] = inputvars.get(special_name)

        self.blocks = blocks
367

Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    def read_eigenvalues(self, backend):
        eigfile = self.files.get('EIG')
        if eigfile is None:
            return

        with open(eigfile) as fd:
            eFermi = float(next(fd).strip())
            nbands, nspins, nkpts = [int(n) for n in next(fd).split()]

            tokens = []
            for line in fd:
                tokens.extend(line.split())

        tokens = iter(tokens)

        eps = np.empty((nspins, nkpts, nbands))
        for k in range(nkpts):
            kindex = int(next(tokens))
            assert k + 1 == kindex
            for s in range(nspins):
                eps[s, k, :] = [next(tokens) for _ in range(nbands)]
        unread = list(tokens)
        assert len(unread) == 0
        assert s == nspins - 1
        assert k == nkpts - 1

        # Where does SIESTA store the occupations?
        backend.addArrayValues('eigenvalues_values', convert_unit(eps, 'eV'))

        kpfile = self.files.get('KP')
        if kpfile is None:
            return


        with open(kpfile) as fd:
            tokens = fd.read().split()

        nkpts = int(tokens[0])
        data = np.array(tokens[1:], object).reshape(-1, 5)
        coords = data[:, 1:4].astype(float)
        weights = data[:, 4].astype(float)
        backend.addArrayValues('eigenvalues_kpoints', coords)
        # XXX metadata for Fermi level?
        # k-point weights?

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    def save_array(self, key, dtype=float, istart=0, iend=None,
                   unit=None):
        return get_array(key, dtype=dtype, istart=istart, iend=iend, unit=unit,
                         storage=self.data)

    def multi_sm(self, name, startpattern, linepattern, endmatcher=None,
                 conflict='fail',  # 'fail', 'keep', 'overwrite'
                 *args, **kwargs):

        pat = re.compile(linepattern)  # XXX how to get compiled pattern?
        ngroups = pat.groups

        allgroups = []
        def addline(parser):
            line = parser.fIn.readline()
            match = pat.match(line)
            assert match is not None
            thislinegroups = match.groups()
            assert len(thislinegroups) == ngroups
            allgroups.append(thislinegroups)

        def savearray(parser):
            arr = np.array(allgroups, dtype=object)
            del allgroups[:]
            if name in self.data:
                if conflict == 'fail':
                    raise ValueError('grrr %s %s' % (name, self.data[name]))
                elif conflict == 'keep':
                    return  # Do not save array
                elif conflict == 'overwrite':
                    pass
                else:
                    raise ValueError('Unknown keyword %s' % conflict)
            if arr.size > 0:
                self.data[name] = arr

        if endmatcher is None:
            endmatcher = r'.*'

        if hasattr(endmatcher, 'swapcase'):
            endmatcher = SM(endmatcher,
454
                            endReStr='',
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
                            forwardMatch=True,
                            name='%s-end' % name,
                            adHoc=savearray)

        sm = SM(startpattern,
                name=name,
                subMatchers=[
                    SM(linepattern,
                       name='%s-line' % name,
                       repeats=True,
                       forwardMatch=True,
                       required=True,
                       adHoc=addline),
                    endmatcher,
                ], **kwargs)
        return sm
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
471 472 473

context = SiestaContext()

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
def get_header_matcher():
    m = SM(r'',
           name='header',
           fixedStartValues={'program_name': 'Siesta',
                             'program_basis_set_type': 'numeric AOs'},
           weak=True,
           forwardMatch=True,
           subMatchers=[
               SM(r'Siesta Version: siesta-(?P<program_version>\S+)',
                  name='version',
                  adHoc=context.adhoc_format_new),
               SM(r'SIESTA\s*(?P<program_version>.+)',
                  name='alt-version', adHoc=context.adhoc_format_old),
               SM(r'Architecture\s*:\s*(?P<x_siesta_arch>.+)', name='arch'),
               SM(r'Compiler flags\s*:\s*(?P<x_siesta_compilerflags>.+)',
                  name='flags'),
           ])
    return m
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

welcome_pattern = r'\s*\*\s*WELCOME TO SIESTA\s*\*'

def get_input_matcher():
    m = SM(welcome_pattern,
           name='welcome',
           sections=['section_method'],
           subFlags=SM.SubFlags.Unordered,
           subMatchers=[
               SM(r'NumberOfAtoms\s*(?P<number_of_atoms>\d+)',
                  name='natoms'),
               context.multi_sm('block_species_label',
                                r'%block ChemicalSpeciesLabel',
                                r'\s*\d+\s*\d+\s*(\S+)',
                            conflict='keep'),
               context.multi_sm('block_coords_and_species',
                                r'%block AtomicCoordinatesAndAtomicSpecies',
                                r'\s*(\S+)\s*(\S+)\s*(\S+)\s*(\d+)'),
               context.multi_sm('block_lattice_vectors',
                                r'%block LatticeVectors',
                                r'(?!%)\s*(\S+)\s*(\S+)\s*(\S+)'),
               SM(r'xc.authors\s*(?P<x_siesta_xc_authors>\S+)',
                  name='xc authors',
                  fixedStartValues={'x_siesta_xc_authors': 'CA'},
                  sections=['section_method', 'x_siesta_section_xc_authors']),
               SM(r'reinit: System Label:\s*(?P<x_siesta_system_label>\S+)',
                  name='syslabel', forwardMatch=True,
                  sections=['x_siesta_section_input'],
                  adHoc=context.adhoc_set_label),
               context.multi_sm('coords_and_species',
                                r'siesta: Atomic coordinates \(Bohr\) and species',
                                r'siesta:\s*(\S+)\s*(\S+)\s*(\S+)\s*(\d+)'),
               context.multi_sm('auto_unit_cell_ang',
                                r'siesta: Automatic unit cell vectors \(Ang\):',
                                r'siesta:\s*(\S+)\s*(\S+)\s*(\S+)'),
               SM(r'Total number of electrons:\s*(?P<number_of_electrons>\S+)',
                  name='nelectrons'),
       ])
    return m


step_pattern = r'\s*(Single-point calculation|Begin[^=]+=\s*\d+)'

def get_step_matcher():
    m = SM(step_pattern,
           name='step',
           sections=['section_single_configuration_calculation'],
540
           subFlags=SM.SubFlags.Unordered,
541 542 543 544 545 546 547 548
           subMatchers=[
               SM(r'\s*=============+', name='====='),
               context.multi_sm('outcoord_ang',
                                r'outcoor: Atomic coordinates \(Ang\):',
                                r'\s*(\S+)\s*(\S+)\s*(\S+)'),
               context.multi_sm('outcell_ang',
                                r'outcell: Unit cell vectors \(Ang\):',
                                r'\s*(\S+)\s*(\S+)\s*(\S+)'),
549 550
               SM(r'siesta: E_KS\(eV\)\s*=\s*(?P<energy_total__eV>\S+)',
                  name='etotal'),
551 552
               context.multi_sm('forces_ev_ang',
                                r'siesta: Atomic forces \(eV/Ang\):',
553 554 555 556
                                r'\s+\d+\s*(\S+)\s*(\S+)\s*(\S+)'),
               context.multi_sm('stress_tensor_ev_ang',
                                r'siesta: Stress tensor \(static\) \(eV/Ang\*\*3\):',
                                r'siesta:\s*(\S+)\s*(\S+)\s*(\S+)'),
557 558 559 560 561 562
           ])
    return m


mainFileDescription = SM(
    r'',
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
563
    name='root',
564
    #weak=True,
565
    sections=['section_run'],
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
566
    subMatchers=[
567 568 569 570 571
        get_header_matcher(),
        SM(r'(%s|%s)' % (welcome_pattern, step_pattern),
           name='system-section',
           #weak=True,
           forwardMatch=True,
572
           repeats=True,
573 574
           required=True,
           sections=['section_system'],
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
575
           subMatchers=[
576 577 578 579 580
               get_input_matcher(),
               get_step_matcher(),
           ]),
        SM(r'x^',  # Make sure whole file is parsed
           name='end')
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
581 582
    ])

583 584


585
def main(**kwargs):
586
    mainFunction(mainFileDescription=mainFileDescription,
587 588 589 590 591 592 593 594
                 metaInfoEnv=metaInfoEnv,
                 parserInfo=parser_info,
                 cachingLevelForMetaName={},
                 superContext=context,
                 **kwargs)

if __name__ == '__main__':
    main()
Ask Hjorth Larsen's avatar
Ask Hjorth Larsen committed
595