parser2.py 9.64 KB
Newer Older
1
2
3
4
5
6
from __future__ import division
import os
from contextlib import contextmanager
import numpy as np
from ase import units
from ase.data import chemical_symbols
Mikkel Strange's avatar
Mikkel Strange committed
7
from ase.io.ulm import ulmopen
Mikkel Strange's avatar
Mikkel Strange committed
8
from ase.utils import basestring
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#from ase.io.trajectory import read_atoms
from ase.data import atomic_masses
from ase.units import Rydberg
import setup_paths
from nomadcore.unit_conversion.unit_conversion import convert_unit as cu
from nomadcore.local_meta_info import loadJsonFile, InfoKindEl
from nomadcore.parser_backend import JsonParseEventsWriterBackend
from libxc_names import get_libxc_name
from default_parameters import parameters as parms


@contextmanager
def open_section(p, name):
    gid = p.openSection(name)
    yield gid
    p.closeSection(name, gid)


def c(value, unit=None):
    """ Dummy function for unit conversion"""
    return cu(value, unit)


parser_info = {"name": "parser2_gpaw", "version": "1.0"}
path = '../../../../nomad-meta-info/meta_info/nomad_meta_info/' +\
        'gpaw.nomadmetainfo.json'
metaInfoPath = os.path.normpath(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), path))

metaInfoEnv, warns = loadJsonFile(filePath=metaInfoPath,
                                  dependencyLoader=None,
                                  extraArgsHandling=InfoKindEl.ADD_EXTRA_ARGS,
                                  uri=None)


def parse(filename):
    p = JsonParseEventsWriterBackend(metaInfoEnv)
    o = open_section
Mikkel Strange's avatar
Mikkel Strange committed
47
    r = ulmopen(filename) #  Reader(filename)
48
49
50
51
52
53
54
55
    p.startedParsingSession(filename, parser_info)
    parms.update(r.parameters.asdict())
    with o(p, 'section_run'):
        p.addValue('program_name', 'GPAW')
        p.addValue('program_version', r.gpaw_version)
        mode = parms['mode']
        if isinstance(mode, basestring):
            mode = {'name': mode}
Mikkel Strange's avatar
Mikkel Strange committed
56
        if mode['name'] == 'pw':
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
            p.addValue('program_basis_set_type', 'plane waves')
            with o(p, 'section_basis_set_cell_dependent'):
                p.addValue('basis_set_cell_dependent_name',
                           'PW_%.1f_Ry' % (mode['ecut'] / r.ha * 2))  # in Ry
                p.addRealValue('basis_set_planewave_cutoff',
                               c(mode['ecut'], 'eV'))
        elif mode['name'] == 'fd':
            p.addValue('program_basis_set_type', 'real space grid')
            with o(p, 'section_basis_set_cell_dependent'):
                cell = r.atoms.cell
                ngpts = r.density.density.shape
                h1 = np.linalg.norm(cell[0]) / ngpts[0]
                h2 = np.linalg.norm(cell[1]) / ngpts[1]
                h3 = np.linalg.norm(cell[2]) / ngpts[2]
                h = (h1 + h2 + h3) / 3.0
                p.addValue('basis_set_cell_dependent_name',
                           'GR_%.1f' % (c(h, 'angstrom') * 1.0E15))  # in fm
        elif mode['name'] == 'lcao':
            p.addValue('program_basis_set_type', 'numeric AOs')
            with o(p, 'section_basis_set_atom_centered'):
                p.addValue('basis_set_atom_centered_short_name',
                          parms['basis'])
        with o(p, 'section_system') as system_gid:
            p.addArrayValues('simulation_cell',
                             c(r.atoms.cell, 'angstrom'))
            symbols = np.array([chemical_symbols[z] for z in r.atoms.numbers])
            p.addArrayValues('atom_labels', symbols)
            p.addArrayValues('atom_positions', c(r.atoms.positions, 'angstrom'))
            p.addArrayValues('configuration_periodic_dimensions',
                             np.array(r.atoms.pbc, bool))
Mikkel Strange's avatar
Mikkel Strange committed
87
            if 'momenta' in r.atoms:
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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
                masses = atomic_masses[r.atoms.numbers]
                velocities = r.atoms.momenta / masses.reshape(-1, 1)
                p.addArrayValues('atom_velocities',
                                c(velocities * units.fs / units.Angstrom,
                                  'angstrom/femtosecond'))
        with o(p, 'section_sampling_method'):
            p.addValue('ensemble_type', 'NVE')
        with o(p, 'section_frame_sequence'):
            pass
        with o(p, 'section_method') as method_gid:
            p.addValue('relativity_method', 'pseudo_scalar_relativistic')
            p.addValue('electronic_structure_method', 'DFT')
            p.addValue('scf_threshold_energy_change',
                       c(parms['convergence']['energy'], 'eV')) # eV / electron
            #if r.FixMagneticMoment:
            #    p.addValue('x_gpaw_fixed_spin_Sz',
            #               r.MagneticMoments.sum() / 2.)
            if parms['occupations'] is None:  # use default values
                if tuple(parms['kpts']) == (1, 1, 1):
                    width = 0.0
                else:
                    width = 0.1
                parms['occupations'] = {'width': width, 'name': 'fermi-dirac'}

            p.addValue('smearing_kind', parms['occupations']['name'])
            p.addRealValue('smearing_width',
                               c(parms['occupations']['width'], 'eV'))
            p.addRealValue('total_charge', parms['charge'])
            with o(p, 'section_XC_functionals'):
                p.addValue('XC_functional_name',
                           get_libxc_name(parms['xc']))
        with o(p, 'section_single_configuration_calculation'):
            p.addValue('single_configuration_calculation_to_system_ref',
                       system_gid)
            p.addValue('single_configuration_to_calculation_method_ref',
                       method_gid)
            p.addValue('single_configuration_calculation_converged',
                      r.scf.converged)
            p.addRealValue('energy_total',
                           c(r.hamiltonian.e_total_extrapolated, 'eV'))
            p.addRealValue('energy_free',
                           c(r.hamiltonian.e_total_free, 'eV'))
            p.addRealValue('energy_XC', c(r.hamiltonian.e_xc, 'eV'))
            p.addRealValue('electronic_kinetic_energy',
                           c(r.hamiltonian.e_kinetic, 'eV'))
            p.addRealValue('energy_correction_entropy',
                           c(r.hamiltonian.e_entropy, 'eV'))
            p.addRealValue('energy_reference_fermi',
                          c(r.occupations.fermilevel, 'eV'))
            p.addRealValue('energy_reference_fermi',
                          c(r.occupations.fermilevel, 'eV'))
139
140
141
142
143
144
145
146
147
148
149
150
151

            # Load 3D arrays ("volumetric data")
            origin = -0.5 * r.atoms.cell
            npoints = np.array(r.density.density.shape[1:])
            npoints[~r.atoms.pbc] += 1
            displacements = r.atoms.cell / npoints

            def add_3d_array(values, kind, unit):
                with o(p, 'section_volumetric_data'):
                    p.addArrayValues('volumetric_data_origin',
                                     origin, 'angstrom')
                    p.addArrayValues('volumetric_data_displacements',
                                     displacements, 'angstrom')
152
153
                    p.addArrayValues('volumetric_data_values',
                                     cu(values, unit))
154
155
156
157
158
159
160
161
162
163
164
165
                    p.addValue('volumetric_data_kind', kind)

            # H.atom.ulm.gpw test can be used to verify that pseudodensity
            # integrates to 0.98, corresponding closely to the norm of the
            # H 1s pseudowavefunction (see output of "gpaw-setup H").
            # It has mixed BCs so this should show that npoints is taken
            # care of correctly, hopefully.
            add_3d_array(r.density.density, kind='density',
                         unit='angstrom**(-3)')
            add_3d_array(r.hamiltonian.potential, kind='potential_effective',
                         unit='eV*angstrom**(-3)')

Mikkel Strange's avatar
Mikkel Strange committed
166
            if 'forces' in r.results:
167
                p.addArrayValues('atom_forces_free_raw',
168
                                 c(r.results.forces, 'eV/angstrom'))
Mikkel Strange's avatar
Mikkel Strange committed
169
            if 'magmons' in r.results:
170
171
172
173
174
175
176
177
178
179
180
181
182
183
                p.addArrayValues('x_gpaw_magnetic_moments',
                                 r.results.magmoms)
                p.addRealValue('x_gpaw_spin_Sz', r.results.magmoms.sum() / 2.0)
            #p.addArrayValues('x_gpaw_atomic_density_matrices',
            #                 r.AtomicDensityMatrices)
            #p.addArrayValues('x_gpaw_projections_real', r.Projections.real)
            #p.addArrayValues('x_gpaw_projections_imag', r.Projections.imag)
            with o(p, 'section_eigenvalues'):
                p.addValue('eigenvalues_kind', 'normal')
                p.addArrayValues('eigenvalues_values',
                                 c(r.wave_functions.eigenvalues, 'eV'))
                p.addArrayValues('eigenvalues_occupation',
                                 r.wave_functions.occupations)
                #p.addArrayValues('eigenvalues_kpoints', r.IBZKPoints)
Mikkel Strange's avatar
Mikkel Strange committed
184
            if 'band_paths' in r.wave_functions: # could change
185
186
187
188
189
190
191
192
193
194
195
196
                with o(p, 'section_k_band'):
                    for band_path in r.wave_functions.band_paths:
                        with o(p, 'section_k_band_segment'):
                            p.addArrayValues('band_energies',
                                            c(band_path.eigenvalues, 'eV'))
                            p.addArrayValues('band_k_points', 'eV',
                                             band_path.kpoints)
                            p.addArrayValues('band_segm_labels',
                                            band_path.labels)
                            p.addArrayValues('band_segm_start_end',
                                             np.asarray(
                                                 [band_path.kpoints[0],
Mikkel Strange's avatar
Mikkel Strange committed
197
                                                  band_path.kpoints[-1]]))
198
199


200
201
202
203
204
205
    p.finishedParsingSession("ParseSuccess", None)

if __name__ == '__main__':
    import sys
    filename = sys.argv[1]
    parse(filename)