Statistiques
| Révision :

chimie4psmn / database / import_data.py @ 50

Historique | Voir | Annoter | Télécharger (8,19 ko)

1
# $Id: import_data.py 38 2017-09-20 13:35:58Z tjiang $
2
import os, sys, argparse
3
from ase import Atoms
4
from ase.io import read
5
from ase.db import connect
6
from ase.calculators.vasp import Vasp
7
from ase.constraints import FixAtoms
8
from numpy.linalg import norm
9
from bz2 import BZ2File
10
from gzip import GzipFile
11

    
12

    
13
def import_vasp_calculations(path,con,include_dir=[],exclude_dir=[],use_poscar=False,creator=os.environ['USER']):
14
    log = open('success.log','w')
15
    errlog = open('err.log','w')
16
    _all = os.walk(os.path.abspath(path))
17
    calculator=None
18
    xc_dict = {'8': 'PBE', '91': 'PW91', 'CA': 'LDA'}
19
    read_all_dir = 0
20
    if len(include_dir) == 0:
21
        read_all_dir = 1
22
    for files in _all:
23
        vasp_out = [i for i in range(len(files[2])) if ('OUTCAR' in files[2][i] and files[2][i][:6]=='OUTCAR')]
24
        condition1 = (read_all_dir or files[0].split('/')[-1] in include_dir)
25
        #condition2 = not files[0].split('/')[-1] in exclude_dir
26
        condition3 = [ i for i, x in enumerate(exclude_dir) if x in files[0] ] 
27
        if len(vasp_out) != 0 and condition1 and not condition3 :
28
            ncalc = 0
29
            for f in vasp_out:
30
                try:
31
                        Atoms = read(files[0]+'/'+files[2][f])
32
                    if use_poscar:
33
                        constraints = read('POSCAR').constraints
34
                        Atoms.set_constraint(constraints)
35
                        print 'get constraint from poscar'
36
                    else:
37
                        Atoms0 = read(files[0]+'/'+files[2][f], index=0)
38
                        pos0 = Atoms0.positions
39
                        pos = Atoms.positions
40
                        diff = pos - pos0
41
                        disp = norm(diff, axis=1)
42
                        if disp.sum() > 0:
43
                            print 'find constraint from outcar'
44
                            mask = [_disp == 0 for _disp in disp]
45
                            constraints = FixAtoms(mask=mask)
46
                            Atoms.set_constraint(constraints)
47
                        else:
48
                            print 'no constraint'
49
                            constraints = None
50
                    #os.system('cp '+files[0]+'/'+files[2][f]+' OUTCAR')
51
                    #calc = Vasp()
52
                    #calc.atoms = Atoms
53
                    #calc.sort = list(range(len(Atoms)))
54
                    #calc.resort = list(range(len(Atoms)))
55
                    #calc.read_outcar()
56
                    #Atoms = calc.atoms
57
                    #nbands = calc.get_number_of_bands()
58
                    ##xc = calc.get_xc_functional()
59
                    #os.system('rm -f OUTCAR')
60

    
61
                    #read version number, XC, ENCUT etc.
62
                    if files[2][f][-4:] == '.bz2':
63
                        fobj = BZ2File(files[0]+'/'+files[2][f])
64
                    elif files[2][f][-3:] == '.gz':
65
                        fobj = GzipFile(files[0]+'/'+files[2][f])
66
                    else:
67
                        fobj = open(files[0]+'/'+files[2][f])
68
                    with fobj as outcar:
69
                        version = outcar.readline()
70
                        line = outcar.readline()
71
                        read_para = 0
72
                        lsol = False
73
                        ldipol = False
74
                        while line != '':
75
                            if line.startswith(' INCAR:'):
76
                                line = outcar.readline().split()
77
                                if line[1] == 'PAW_PBE':
78
                                    pot = 'PAW'
79
                                else:
80
                                    pot = line[1]
81
                            elif line.startswith(' Dimension of arrays'):
82
                            #if line.startswith(' Dimension of arrays'):
83
                                read_para = 1
84
                            elif read_para:
85
                                if 'LEXCH' in line:
86
                                    xc_flag = line.split()[2].upper()
87
                                    if xc_flag not in xc_dict.keys():
88
                                        raise ValueError('Unknown xc-functional flag found in POTCAR,'
89
                                                         ' LEXCH=%s' % xc_flag)
90
                                    xc = xc_dict[xc_flag]
91
                                elif 'NKPTS' in line:
92
                                #if 'NKPTS' in line:
93
                                    nkpts = int(line.split()[3])
94
                                elif 'ENCUT' in line:
95
                                    encut = float(line.split()[2])
96
                                elif 'ENAUG' in line:
97
                                    enaug = float(line.split()[2])
98
                                elif 'NBANDS' in line:
99
                                    nbands = int(line.split()[-1])
100
                                elif 'EDIFFG' in line:
101
                                    f_limit = -float(line.split()[2])
102
                                elif 'LSOL' in line:
103
                                    if line.split()[2] == 'T':
104
                                        lsol = True
105
                                elif 'LDIPOL' in line:
106
                                    if line.split()[2] == 'T':
107
                                        ldipol = True
108
                                elif '-'*104 in line:
109
                                    break
110
                            line = outcar.readline()
111
                    if constraints is not None:
112
                        fmax = ((Atoms.get_forces()) ** 2).sum(1).max()**0.5
113
                        if fmax < f_limit:
114
                            print 'updating the database with minimized calculation from file: ', fmax, files[2][f]
115
                            if use_poscar:
116
                                    con.write(Atoms,functional = xc,path=files[0],code='VASP',filename=files[2][f], version=version, potential=pot, encut=encut, enaug=enaug, lsol=lsol, ldipol=ldipol, nkpts=nkpts, constraint=True)
117
                            else:
118
                                    con.write(Atoms,functional = xc,creator=creator,path=files[0],code='VASP',filename=files[2][f], version=version, potential=pot, encut=encut, enaug=enaug, lsol=lsol, ldipol=ldipol, nkpts=nkpts, constraint=True)
119
                        else:
120
                            print 'not updating the database as fmax is too big for file: ', fmax, files[2][f]
121
                    else:
122
                            print 'updating the database with calculation', files[2][f]
123
                                con.write(Atoms,functional = xc,creator=creator,path=files[0],code='VASP',filename=files[2][f], version=version, potential=pot, encut=encut, enaug=enaug, lsol=lsol, ldipol=ldipol, nkpts=nkpts, constraint=False)
124
                    print >> log, files[0], files[2][f]
125
                except (IndexError, ValueError):
126
                    print >> errlog, files[0], files[2][f]
127
                
128
        log.flush()
129
        errlog.flush()
130
                 
131
#def import_adf_calculations(path,con):
132
#    log = open('success.log','w')
133
#    errlog = open('err.log','w')
134
#    _all = os.walk(path)
135
#    calculator=None
136
#    for files in _all:
137
#        vasp_out = [i for i in range(len(files[2])) if ('OUTCAR' in files[2][i] and files[2][i][:6]=='OUTCAR')]
138
#        if len(vasp_out) != 0:
139
#            print files[0]
140
#            ncalc = 0
141
#            for f in vasp_out:
142
#                    calculator = 'vasp'
143
#                try:
144
#                        Atoms = read(files[0]+'/'+files[2][f])
145
#                        con.write(Atoms,creator='rkerber',path=files[0],code='vasp',filename=files[2][f])
146
#                    print >> log, files[0]
147
#                except (IndexError, ValueError):
148
#                    print >> errlog, files[0]
149
#                
150
#        log.flush()
151
#        errlog.flush()
152

    
153

    
154
if __name__ == '__main__':
155
    parser = argparse.ArgumentParser()
156
    parser.add_argument("-p", help="Use POSCAR in the same directory to determine the constraint", action="store_true")
157
    args = parser.parse_args()
158
    if args.p:
159
        use_poscar = True
160
    else:
161
        use_poscar = False
162

    
163
    con = connect('test.db')
164
    #import_vasp_calculations('/data/users/tjiang/rkerber', con)
165
    #import_vasp_calculations('.', con, include_dir=['<opt_dir>'], exclude_dir=['<to_exclude_dir1>', '<to_exclude_dir2>'])
166
    import_vasp_calculations('.', con, use_poscar=use_poscar)