errorbar_base.py 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 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 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 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 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 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 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 324 325 326 327 328
from numpy import zeros, int32, unique, genfromtxt, sort, argsort, arange, \
        append, array
from ase import Atom
from ase.db import connect
from ase.atoms import string2symbols

def get_data(con, name_dict, Z, code, category, keys, recommended_VASP,
             name_dict_monos_gpaw, name_dict_bins_gpaw):
    """Function for obtaining the data from the databases for each code
    Parameters:

    con: The database

    name_dict: dict
        The dictionary for el. solid/binaries

    Z: array like
        atomic numbers for el. solids/binaries

    code: str
        DFT-code

    category: str
        code specific category string

    keys: code specific parameters
  """
    N_monos = len(name_dict)
    data = zeros(N_monos)
    if code == 'VASP':
        rows = con.select(selection=[('category=' + category),
                                     ('precision=' + keys[0]),
                                     ('k_point_density=' + str(keys[1])),
                                     ('functional=' + keys[2])])
        # For VASP we have to select the recommended Pseudo-Potential:
        for row in rows:
            if category.find('binaries') == 0:
                A = unique(row.numbers)[0] - 1
                B = unique(row.numbers)[1] - 1
                rec_POT = ('POTCAR' +
                           recommended_VASP[A, 1].replace('POTCAR', '') +
                           recommended_VASP[B, 1].replace('POTCAR', ''))
                data_POT = row.potcar.replace('_h', '')
                rec_POT = rec_POT.replace('_3', '')
                rec_POT = rec_POT.replace('_2', '')
            else:
                rec_POT = recommended_VASP[Z[name_dict[row.name]]-1, 1]
                data_POT = row.potcar
            if data_POT == rec_POT:
                data[name_dict[row.name]] = row.total_energy

    elif code == 'FHI-aims':
        rows = con.select(selection=[('category=' + category),
                                     ('basis_set=' + keys[0]),
                                     ('k_point_density=' + str(keys[1])),
                                     ('functional=' + keys[2]),
                                     ('tiers=' + keys[3]),
                                     ('relativistic_treatment=' + keys[4])])
        for row in rows:
            data[name_dict[row.name]] = row.total_energy

    elif code == 'exciting':
        rows = con.select(selection=[('category=' + category),
                                     ('total_precision','=',float(keys[0])),
                                     ('k_point_density','=',float(keys[1])),
                                     ('xc_functional=' + keys[2])])
        for row in rows:
            data[name_dict[row.name]] = row.total_energy

    elif code == 'GPAW':
        rows = con.select(selection=[('category=' + category),
                                     ('ecut=' + str(keys[0])),
                                     ('k_point_density=' + str(keys[1]))])
        # Mapping from formula to system name
        for row in rows:
            if category.find('binaries') == 0:
                data[name_dict[name_dict_bins_gpaw[row.formula]]] = row.energy
            else:
                data[name_dict[name_dict_monos_gpaw[row.formula]]] = row.energy
    return data

def get_rows(con, name_dict, Z, code, category, keys, recommended_VASP,
             name_dict_monos_gpaw, name_dict_bins_gpaw):
    """Function for obtaining the rows from the databases for each code
    Parameters:

    con: The database

    name_dict: dict
        The dictionary for el. solid/binaries

    Z: array like
        atomic numbers for el. solids/binaries

    code: str
        DFT-code

    category: str
        code specific category string

    keys: code specific parameters
  """
    if code == 'VASP':
        rows = con.select(selection=[('category=' + category),
                                     ('precision=' + keys[0]),
                                     ('k_point_density=' + str(keys[1])),
                                     ('functional=' + keys[2])])

    elif code == 'FHI-aims':
        rows = con.select(selection=[('category=' + category),
                                     ('basis_set=' + keys[0]),
                                     ('k_point_density=' + str(keys[1])),
                                     ('functional=' + keys[2]),
                                     ('tiers=' + keys[3]),
                                     ('relativistic_treatment=' + keys[4])])

    elif code == 'exciting':
        rows = con.select(selection=[('category=' + category),
                                     ('total_precision','=',float(keys[0])),
                                     ('k_point_density','=',float(keys[1])),
                                     ('xc_functional=' + keys[2])])

    elif code == 'GPAW':
        rows = con.select(selection=[('category=' + category),
                                     ('ecut=' + str(keys[0])),
                                     ('k_point_density=' + str(keys[1]))])
    return rows


def get_keys(code, prec, kpt, xc, tiers, rel):
    if code == 'VASP':
        keys = [prec, str(kpt), xc, tiers]
        ref_keys = [xc]
    elif code == 'FHI-aims':
        keys = [prec, str(kpt), xc, tiers, rel]
        ref_keys = [xc, rel]
    elif code == 'exciting':
        keys = [prec, str(kpt), xc]
        ref_keys = [xc]
    elif code == 'GPAW':
        keys = [prec, str(kpt)]
        ref_keys = [xc]
    return keys, ref_keys


def get_xy(Z, N, data_ref, data):
    plot_x = sort(Z)
    plot_y = ((data_ref-data)/N)[argsort(Z)]
    nonzero=((data!=0)*(data_ref!=0))[argsort(Z)]
    plot_x = plot_x[nonzero]
    plot_y = plot_y[nonzero]
    #print(plot_x[abs(plot_y)>0.001])
    return plot_x, abs(plot_y)


def get_xy_predict(N, data_ref, data):
    plot_x = ((data) / N)
    plot_y = data_ref / N
    nonzero = (plot_y != 0) * (plot_x != 0)
    plot_x = plot_x[nonzero]
    plot_y = plot_y[nonzero]
    #print(plot_x[abs(plot_y)>0.001])
    return abs(plot_x), abs(plot_y)


def get_binary_error_from_solids(error, binaries_to_monos_min, N_bins_min,
                                 binaries_to_monos_max, N_bins_max, pred):
    error_A = error[binaries_to_monos_min]
    error_B = error[binaries_to_monos_max]
    N_A = N_bins_min
    N_B = N_bins_max
    N_AB = N_A + N_B

    if pred == '1':
        pred_error=(error_A * N_A + error_B * N_B)
        rel_pred_error = pred_error / N_AB
    elif pred == '2':
        pred_error = (error_A * N_A + error_B * N_B)
        rel_pred_error = pred_error / N_AB
    return pred_error #, rel_pred_error


def do_plot(fig, ax, Z, N, data_ref, data, lab):
    plot_x = sort(Z)
    plot_y = ((data_ref - data) / N)[argsort(Z)]
    nonzero = plot_y != 0
    plot_x = plot_x[nonzero]
    plot_y = plot_y[nonzero]
    #print(plot_x[abs(plot_y)>0.001])
    ax.semilogy(plot_x, abs(plot_y), 'o', label=lab)
    ax.legend(numpoints=1, loc=4, fontsize=8)
    fig.canvas.draw_idle()


def do_plot_predict(fig, ax, N, data_ref, data, lab):
    plot_x = ((data) / N)
    plot_y = data_ref / N
    nonzero = (plot_y != 0) * (plot_x != 0)
    plot_x = plot_x[nonzero]
    plot_y = plot_y[nonzero]
    #print(plot_x[abs(plot_y)>0.001])
    ax.loglog(abs(plot_x), abs(plot_y), 'o', label=lab)
    ax.plot(ax.get_xlim(), ax.get_xlim(), '-k')
    ax.legend(numpoints=1, loc=4, fontsize=8)
    fig.canvas.draw_idle()


def get_xy(Z, N, data_ref, data):
    plot_x = sort(Z)
    plot_y = ((data_ref-data)/N)[argsort(Z)]
    nonzero = plot_y != 0
    plot_x = plot_x#[nonzero]
    plot_y = plot_y#[nonzero]
    #print(plot_x[abs(plot_y)>0.001])
    return plot_x, abs(plot_y)


def get_xy_predict(N, data_ref, data):
    plot_x = ((data) / N)
    plot_y = data_ref / N
    nonzero = (plot_y != 0) * (plot_x != 0)
    plot_x = plot_x[nonzero]
    plot_y = plot_y[nonzero]
    #print(plot_x[abs(plot_y)>0.001])
    return abs(plot_x), abs(plot_y)

def get_xy_Ecoh(Z, data_monos,data_bins,zeroinds,binaries_to_monos_min,binaries_to_monos_max,N_bins_min,N_bins_max):
    error_A = data_monos[binaries_to_monos_min]
    error_B = data_monos[binaries_to_monos_max]
    N_A = N_bins_min
    N_B = N_bins_max
    N_AB = N_A + N_B
    plot_x=Z[zeroinds]
    plot_y=((data_bins)[zeroinds]-(error_A * N_A + error_B * N_B)[zeroinds])/N_AB[zeroinds]
    return plot_x, plot_y
  
def get_mono_ind(formula,name_dict_monos):
    symbols = string2symbols(formula) 
    ind = zeros(0,dtype='int32')
    N_f = len(symbols)
    notinset=False
    for s in symbols:
      at = Atom(s)
      if at.number < 10:
	try:
	  ind = append(ind, name_dict_monos['0'+str(at.number)+'_'+s])
	except KeyError:
	  print("Element "+s+" is not in the set of elementary solids.")
	  notinset=True
	  break
      else:
	try:
	  ind = append(ind, name_dict_monos[str(at.number)+'_'+s])
	except KeyError:
	  print("Element "+s+" is not in the set of elementary solids.")
	  notinset=True
	  break
    return N_f, ind, notinset

def intermediate_delta_energy_exciting(elementname, intermediate_prec, con, name_dict_monos_exciting, keys, data_ref, N_mono):
    import numpy as np
    import sys
    import matplotlib.pyplot as mpl
    import scipy
    import scipy.stats

    available_precs=np.asarray([30,40,50,60,70,80]) # this list needs to be sorted
    natoms=N_mono[name_dict_monos_exciting[elementname]]
    total_energy_ref=data_ref['exciting','monomers',keys[2]][name_dict_monos_exciting[elementname]]
    
    if intermediate_prec < available_precs[0]:
        #sys.exit('intermediate_delta_energy_exciting: precision of one element in a binary is below '+str(available_precs[0]))
        number_of_points=2
        x__considered_precs=available_precs[0:number_of_points]
    elif intermediate_prec > available_precs[-1]:
        #print('CAUTION: extrapolation! Precision of one element in a binary is above '+str(available_precs[-1]))
        number_of_points=3
        number_of_points=-1*number_of_points
        x__considered_precs=available_precs[number_of_points:]
    else:
        for icount in range(1,len(available_precs)):
            if intermediate_prec < available_precs[icount]:
                x__considered_precs=available_precs[[icount-1,icount]]
                break
                
    y__log_error_per_atom=[]
    #for prec in x__considered_precs:
    rows = con.select(selection=[('category=monomers'),
                                        ('total_precision','<=',x__considered_precs[-1]),
                                        ('total_precision','>=',x__considered_precs[0]),
                                        ('k_point_density','=',float(keys[1])),
                                        ('xc_functional=' + keys[2]),
                                        ('element1='+elementname)])
    for row in rows:
        total_energy=row.total_energy        
        y__log_error_per_atom.append(np.log10((total_energy - total_energy_ref)/natoms))

    linregr_results = scipy.stats.linregress(x__considered_precs,y__log_error_per_atom)
    p = np.asarray([linregr_results[0], linregr_results[1]])
    delta_energy_per_atom = np.power(10,np.polyval(p,intermediate_prec))
    # want to plot results of linregress?
    if False:
        # get all monomers data
        monomers_delta_energy_per_atom=[]
        rows = con.select(selection=[('category=monomers'),
                                        ('total_precision','<=',available_precs[-1]),
                                        ('total_precision','>=',available_precs[0]),                                        
                                        ('k_point_density','=',float(keys[1])),
                                        ('xc_functional=' + keys[2]),
                                        ('element1='+elementname)])
        for row in rows:
            total_energy=row.total_energy        
            monomers_delta_energy_per_atom.append((total_energy - total_energy_ref)/natoms)
        # plot
        fig3 = figure(3,(10,10))
        rect = fig3.patch
        rect.set_facecolor('white')
        mpl.semilogy(available_precs, monomers_delta_energy_per_atom,'ko-', ms=7.0, markeredgewidth=1, linewidth=1.5, label="data")
        mpl.semilogy(x__considered_precs, np.power(10,y__log_error_per_atom),'go', ms=11.0, markeredgewidth=1, label="accounted data in linregress")
        mpl.semilogy(intermediate_prec, delta_energy_per_atom,'rx', ms=11.0, markeredgewidth=3, label="result from linregress")
        axes = mpl.gca()
        axes.grid(True)
        mpl.xlabel("Precision %", fontsize = "x-large")
        mpl.ylabel("$\Delta E$ per atom [eV]", fontsize = "x-large")
        mpl.legend(loc="lower left", frameon=True, fontsize = "x-large", numpoints=1)
        mpl.title(elementname)
        mpl.show()
    return delta_energy_per_atom