Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

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

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

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

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

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

# coding: utf-8 

# Copyright (c) Pymatgen Development Team. 

# Distributed under the terms of the MIT License. 

 

from __future__ import division, unicode_literals 

 

""" 

This module implements Compatibility corrections for mixing runs of different 

functionals. 

""" 

 

import six 

from six.moves import filter, map 

 

__author__ = "Shyue Ping Ong, Anubhav Jain, Stephen Dacek, Sai Jayaraman" 

__copyright__ = "Copyright 2012, The Materials Project" 

__version__ = "1.0" 

__maintainer__ = "Shyue Ping Ong" 

__email__ = "shyuep@gmail.com" 

__date__ = "Mar 19, 2012" 

 

 

import os 

 

from collections import defaultdict 

 

from monty.design_patterns import cached_class 

from monty.serialization import loadfn 

 

from pymatgen.io.vasp.sets import MITVaspInputSet, MPVaspInputSet 

from pymatgen.core.periodic_table import Element 

from pymatgen.analysis.structure_analyzer import oxide_type 

 

import abc 

 

 

class CompatibilityError(Exception): 

""" 

Exception class for Compatibility. Raised by attempting correction 

on incompatible calculation 

""" 

def __init__(self, msg): 

self.msg = msg 

 

def __str__(self): 

return self.msg 

 

 

class Correction(six.with_metaclass(abc.ABCMeta, object)): 

""" 

A Correction class is a pre-defined scheme for correction a computed 

entry based on the type and chemistry of the structure and the 

calculation parameters. All Correction classes must implement a 

correct_entry method. 

""" 

 

@abc.abstractmethod 

def get_correction(self, entry): 

""" 

Returns correction for a single entry. 

 

Args: 

entry: A ComputedEntry object. 

 

Returns: 

The energy correction to be applied. 

 

Raises: 

CompatibilityError if entry is not compatible. 

""" 

return 

 

def correct_entry(self, entry): 

""" 

Corrects a single entry. 

 

Args: 

entry: A ComputedEntry object. 

 

Returns: 

An processed entry. 

 

Raises: 

CompatibilityError if entry is not compatible. 

""" 

entry.correction += self.get_correction(entry) 

return entry 

 

 

class PotcarCorrection(Correction): 

""" 

Checks that POTCARs are valid within a pre-defined input set. This 

ensures that calculations performed using different InputSets are not 

compared against each other. 

 

Entry.parameters must contain a "potcar_symbols" key that is a list of 

all POTCARs used in the run. Again, using the example of an Fe2O3 run 

using Materials Project parameters, this would look like 

entry.parameters["potcar_symbols"] = ['PAW_PBE Fe_pv 06Sep2000', 

'PAW_PBE O 08Apr2002']. 

 

Args: 

input_set: InputSet object used to generate the runs (used to check 

for correct potcar symbols) 

 

check_hash (bool): If true, uses the potcar hash to check for valid 

potcars. If false, uses the potcar symbol (Less reliable). 

Defaults to True 

 

Raises: 

ValueError if entry do not contain "potcar_symbols" key. 

CombatibilityError if wrong potcar symbols 

""" 

 

def __init__(self, input_set, check_hash=False): 

 

if isinstance(list(input_set.potcar_settings.values())[-1], dict): 

if check_hash: 

self.valid_potcars = {k: d["hash"] for k, d in 

input_set.potcar_settings.items()} 

else: 

self.valid_potcars = {k: d["symbol"] for k, d in 

input_set.potcar_settings.items()} 

else: 

if check_hash: 

raise ValueError('Cannot check hashes of potcars,' 

' hashes are not set') 

else: 

self.valid_potcars = {k: d for k, d in 

input_set.potcar_settings.items()} 

 

self.input_set = input_set 

self.check_hash = check_hash 

 

def get_correction(self, entry): 

 

if self.check_hash: 

if entry.parameters.get("potcar_spec"): 

psp_settings = set([d.get("hash") 

for d in entry.parameters[ 

"potcar_spec"] if d]) 

else: 

raise ValueError('Cannot check hash ' 

'without potcar_spec field') 

else: 

if entry.parameters.get("potcar_spec"): 

psp_settings = set([d.get("titel").split()[1] 

for d in entry.parameters[ 

"potcar_spec"] if d]) 

else: 

psp_settings = set([sym.split()[1] 

for sym in entry.parameters[ 

"potcar_symbols"] if sym]) 

 

if {self.valid_potcars[str(el)] for el in 

entry.composition.elements} != psp_settings: 

raise CompatibilityError('Incompatible potcar') 

return 0 

 

def __str__(self): 

return "{} Potcar Correction".format(self.input_set.name) 

 

 

@cached_class 

class GasCorrection(Correction): 

""" 

Correct anion energies to obtain the right formation energies. Note that 

this depends on calculations being run within the same input set. 

 

Args: 

config_file: Path to the selected compatibility.yaml config file. 

correct_peroxide: Specify whether peroxide/superoxide/ozonide 

corrections are to be applied or not. 

""" 

def __init__(self, config_file): 

c = loadfn(config_file) 

self.name = c['Name'] 

self.cpd_energies = c['Advanced']['CompoundEnergies'] 

 

def get_correction(self, entry): 

comp = entry.composition 

 

rform = entry.composition.reduced_formula 

if rform in self.cpd_energies: 

return self.cpd_energies[rform] * comp.num_atoms \ 

- entry.uncorrected_energy 

 

return 0 

 

def __str__(self): 

return "{} Gas Correction".format(self.name) 

 

 

@cached_class 

class AnionCorrection(Correction): 

""" 

Correct gas energies to obtain the right formation energies. Note that 

this depends on calculations being run within the same input set. 

 

Args: 

config_file: Path to the selected compatibility.yaml config file. 

correct_peroxide: Specify whether peroxide/superoxide/ozonide 

corrections are to be applied or not. 

""" 

def __init__(self, config_file, correct_peroxide=True): 

c = loadfn(config_file) 

self.oxide_correction = c['OxideCorrections'] 

self.sulfide_correction = c.get('SulfideCorrections', defaultdict( 

float)) 

self.name = c['Name'] 

self.correct_peroxide = correct_peroxide 

 

def get_correction(self, entry): 

comp = entry.composition 

 

rform = entry.composition.reduced_formula 

 

if len(comp) >= 2 and sorted(comp.keys())[-1].symbol == "S": 

return self.sulfide_correction["sulfide"] * comp["S"] 

 

correction = 0 

# Check for oxide, peroxide, superoxide, and ozonide corrections. 

if self.correct_peroxide: 

if len(comp) >= 2 and Element("O") in comp: 

if entry.data.get("oxide_type"): 

if entry.data["oxide_type"] in self.oxide_correction: 

ox_corr = self.oxide_correction[ 

entry.data["oxide_type"]] 

correction += ox_corr * comp["O"] 

if entry.data["oxide_type"] == "hydroxide": 

ox_corr = self.oxide_correction["oxide"] 

correction += ox_corr * comp["O"] 

 

elif hasattr(entry, "structure"): 

ox_type, nbonds = oxide_type(entry.structure, 1.05, 

return_nbonds=True) 

if ox_type in self.oxide_correction: 

correction += self.oxide_correction[ox_type] * \ 

nbonds 

elif ox_type == "hydroxide": 

correction += self.oxide_correction["oxide"] * comp["O"] 

else: 

if rform in UCorrection.common_peroxides: 

correction += self.oxide_correction["peroxide"] * \ 

comp["O"] 

elif rform in UCorrection.common_superoxides: 

correction += self.oxide_correction["superoxide"] * \ 

comp["O"] 

elif rform in UCorrection.ozonides: 

correction += self.oxide_correction["ozonide"] * \ 

comp["O"] 

elif Element("O") in comp.elements and len(comp.elements)\ 

> 1: 

correction += self.oxide_correction['oxide'] * comp["O"] 

else: 

correction += self.oxide_correction['oxide'] * comp["O"] 

 

return correction 

 

def __str__(self): 

return "{} Anion Correction".format(self.name) 

 

 

@cached_class 

class AqueousCorrection(Correction): 

""" 

This class implements aqueous phase compound corrections for elements 

and H2O. 

 

Args: 

config_file: Path to the selected compatibility.yaml config file. 

""" 

def __init__(self, config_file): 

c = loadfn(config_file) 

self.cpd_energies = c['AqueousCompoundEnergies'] 

self.name = c["Name"] 

 

def get_correction(self, entry): 

comp = entry.composition 

rform = comp.reduced_formula 

cpdenergies = self.cpd_energies 

correction = 0 

if rform in cpdenergies: 

if rform in ["H2", "H2O"]: 

correction = cpdenergies[rform] * comp.num_atoms \ 

- entry.uncorrected_energy - entry.correction 

else: 

correction += cpdenergies[rform] * comp.num_atoms 

if not rform == "H2O": 

correction += 0.5 * 2.46 * min(comp["H"]/2.0, comp["O"]) 

return correction 

 

def __str__(self): 

return "{} Aqueous Correction".format(self.name) 

 

 

@cached_class 

class UCorrection(Correction): 

""" 

This class implements the GGA/GGA+U mixing scheme, which allows mixing of 

entries. Entry.parameters must contain a "hubbards" key which is a dict 

of all non-zero Hubbard U values used in the calculation. For example, 

if you ran a Fe2O3 calculation with Materials Project parameters, 

this would look like entry.parameters["hubbards"] = {"Fe": 5.3} 

If the "hubbards" key is missing, a GGA run is assumed. 

 

It should be noted that ComputedEntries assimilated using the 

pymatgen.apps.borg package and obtained via the MaterialsProject REST 

interface using the pymatgen.matproj.rest package will automatically have 

these fields populated. 

 

Args: 

config_file: Path to the selected compatibility.yaml config file. 

input_set: InputSet object (to check for the +U settings) 

compat_type: Two options, GGA or Advanced. GGA means all GGA+U 

entries are excluded. Advanced means mixing scheme is 

implemented to make entries compatible with each other, 

but entries which are supposed to be done in GGA+U will have the 

equivalent GGA entries excluded. For example, Fe oxides should 

have a U value under the Advanced scheme. A GGA Fe oxide run 

will therefore be excluded under the scheme. 

""" 

common_peroxides = ["Li2O2", "Na2O2", "K2O2", "Cs2O2", "Rb2O2", "BeO2", 

"MgO2", "CaO2", "SrO2", "BaO2"] 

common_superoxides = ["LiO2", "NaO2", "KO2", "RbO2", "CsO2"] 

ozonides = ["LiO3", "NaO3", "KO3", "NaO5"] 

 

def __init__(self, config_file, input_set, compat_type): 

if compat_type not in ['GGA', 'Advanced']: 

raise CompatibilityError("Invalid compat_type {}" 

.format(compat_type)) 

 

c = loadfn(config_file) 

 

self.input_set = input_set 

if compat_type == 'Advanced': 

self.u_settings = self.input_set.incar_settings["LDAUU"] 

self.u_corrections = c["Advanced"]["UCorrections"] 

else: 

self.u_settings = {} 

self.u_corrections = {} 

 

self.name = c["Name"] 

self.compat_type = compat_type 

 

def get_correction(self, entry): 

if entry.parameters.get("run_type", "GGA") == "HF": 

raise CompatibilityError('Invalid run type') 

 

calc_u = entry.parameters.get("hubbards", None) 

calc_u = defaultdict(int) if calc_u is None else calc_u 

comp = entry.composition 

 

elements = sorted([el for el in comp.elements if comp[el] > 0], 

key=lambda el: el.X) 

most_electroneg = elements[-1].symbol 

correction = 0 

ucorr = self.u_corrections.get(most_electroneg, {}) 

usettings = self.u_settings.get(most_electroneg, {}) 

 

for el in comp.elements: 

sym = el.symbol 

#Check for bad U values 

if calc_u.get(sym, 0) != usettings.get(sym, 0): 

raise CompatibilityError('Invalid U value on {}'.format(sym)) 

if sym in ucorr: 

correction += float(ucorr[sym]) * comp[el] 

 

return correction 

 

def __str__(self): 

return "{} {} Correction".format(self.name, self.compat_type) 

 

 

class Compatibility(object): 

""" 

The Compatibility class combines a list of corrections to be applied to 

an entry or a set of entries. Note that some of the Corrections have 

interdependencies. For example, PotcarCorrection must always be used 

before any other compatibility. Also, GasCorrection("MP") must be used 

with PotcarCorrection("MP") (similarly with "MIT"). Typically, 

you should use the specific MaterialsProjectCompatibility and 

MITCompatibility subclasses instead. 

 

Args: 

corrections: List of corrections to apply. 

""" 

def __init__(self, corrections): 

self.corrections = corrections 

 

def process_entry(self, entry): 

""" 

Process a single entry with the chosen Corrections. 

 

Args: 

entry: A ComputedEntry object. 

 

Returns: 

An adjusted entry if entry is compatible, otherwise None is 

returned. 

""" 

try: 

corrections = self.get_corrections_dict(entry) 

except CompatibilityError: 

return None 

entry.correction = sum(corrections.values()) 

return entry 

 

def get_corrections_dict(self, entry): 

""" 

Returns the corrections applied to a particular entry. 

 

Args: 

entry: A ComputedEntry object. 

 

Returns: 

({correction_name: value}) 

""" 

corrections = {} 

for c in self.corrections: 

val = c.get_correction(entry) 

if val != 0: 

corrections[str(c)] = val 

return corrections 

 

def process_entries(self, entries): 

""" 

Process a sequence of entries with the chosen Compatibility scheme. 

 

Args: 

entries: A sequence of entries. 

 

Returns: 

An list of adjusted entries. Entries in the original list which 

are not compatible are excluded. 

""" 

return list(filter(None, map(self.process_entry, entries))) 

 

def get_explanation_dict(self, entry): 

""" 

Provides an explanation dict of the corrections that are being applied 

for a given compatibility scheme. Inspired by the "explain" methods 

in many database methodologies. 

 

Args: 

entry: A ComputedEntry. 

 

Returns: 

(dict) of the form 

{"Compatibility": "string", 

"Uncorrected_energy": float, 

"Corrected_energy": float, 

"Corrections": [{"Name of Correction": { 

"Value": float, "Explanation": "string"}]} 

""" 

centry = self.process_entry(entry) 

if centry is None: 

uncorrected_energy = entry.uncorrected_energy 

corrected_energy = None 

else: 

uncorrected_energy = centry.uncorrected_energy 

corrected_energy = centry.energy 

d = {"compatibility": self.__class__.__name__, 

"uncorrected_energy": uncorrected_energy, 

"corrected_energy": corrected_energy} 

corrections = [] 

corr_dict = self.get_corrections_dict(entry) 

for c in self.corrections: 

cd = {"name": str(c)} 

cd["description"] = c.__doc__.split("Args")[0].strip() 

cd["value"] = corr_dict.get(str(c), 0) 

corrections.append(cd) 

d["corrections"] = corrections 

return d 

 

def explain(self, entry): 

""" 

Prints an explanation of the corrections that are being applied for a 

given compatibility scheme. Inspired by the "explain" methods in many 

database methodologies. 

 

Args: 

entry: A ComputedEntry. 

""" 

d = self.get_explanation_dict(entry) 

print("The uncorrected value of the energy of %s is %f eV" % ( 

entry.composition, d["uncorrected_energy"])) 

print("The following corrections / screening are applied for %s:\n" %\ 

d["compatibility"]) 

for c in d["corrections"]: 

print("%s correction: %s\n" % (c["name"], 

c["description"])) 

print("For the entry, this correction has the value %f eV." % c[ 

"value"]) 

print("-" * 30) 

 

print("The final energy after corrections is %f" % d[ 

"corrected_energy"]) 

 

 

class MaterialsProjectCompatibility(Compatibility): 

""" 

This class implements the GGA/GGA+U mixing scheme, which allows mixing of 

entries. Note that this should only be used for VASP calculations using the 

MaterialsProject parameters (see pymatgen.io.vaspio_set.MPVaspInputSet). 

Using this compatibility scheme on runs with different parameters is not 

valid. 

 

Args: 

compat_type: Two options, GGA or Advanced. GGA means all GGA+U 

entries are excluded. Advanced means mixing scheme is 

implemented to make entries compatible with each other, 

but entries which are supposed to be done in GGA+U will have the 

equivalent GGA entries excluded. For example, Fe oxides should 

have a U value under the Advanced scheme. A GGA Fe oxide run 

will therefore be excluded under the scheme. 

correct_peroxide: Specify whether peroxide/superoxide/ozonide 

corrections are to be applied or not. 

check_potcar_hash (bool): Use potcar hash to verify potcars are correct. 

""" 

 

def __init__(self, compat_type="Advanced", correct_peroxide=True, 

check_potcar_hash=False): 

module_dir = os.path.dirname(os.path.abspath(__file__)) 

fp = os.path.join(module_dir, "MPCompatibility.yaml") 

i_s = MPVaspInputSet() 

super(MaterialsProjectCompatibility, self).__init__( 

[PotcarCorrection(i_s, check_hash=check_potcar_hash), 

GasCorrection(fp), 

AnionCorrection(fp, correct_peroxide=correct_peroxide), 

UCorrection(fp, i_s, compat_type)]) 

 

 

class MITCompatibility(Compatibility): 

""" 

This class implements the GGA/GGA+U mixing scheme, which allows mixing of 

entries. Note that this should only be used for VASP calculations using the 

MIT parameters (see pymatgen.io.vaspio_set MITVaspInputSet). Using 

this compatibility scheme on runs with different parameters is not valid. 

 

Args: 

compat_type: Two options, GGA or Advanced. GGA means all GGA+U 

entries are excluded. Advanced means mixing scheme is 

implemented to make entries compatible with each other, 

but entries which are supposed to be done in GGA+U will have the 

equivalent GGA entries excluded. For example, Fe oxides should 

have a U value under the Advanced scheme. A GGA Fe oxide run 

will therefore be excluded under the scheme. 

correct_peroxide: Specify whether peroxide/superoxide/ozonide 

corrections are to be applied or not. 

check_potcar_hash (bool): Use potcar hash to verify potcars are correct. 

""" 

 

def __init__(self, compat_type="Advanced", correct_peroxide=True, 

check_potcar_hash=False): 

module_dir = os.path.dirname(os.path.abspath(__file__)) 

fp = os.path.join(module_dir, "MITCompatibility.yaml") 

i_s = MITVaspInputSet() 

super(MITCompatibility, self).__init__( 

[PotcarCorrection(i_s, check_hash=check_potcar_hash), 

GasCorrection(fp), 

AnionCorrection(fp, correct_peroxide=correct_peroxide), 

UCorrection(fp, i_s, compat_type)]) 

 

 

class MITAqueousCompatibility(Compatibility): 

""" 

This class implements the GGA/GGA+U mixing scheme, which allows mixing of 

entries. Note that this should only be used for VASP calculations using the 

MIT parameters (see pymatgen.io.vaspio_set MITVaspInputSet). Using 

this compatibility scheme on runs with different parameters is not valid. 

 

Args: 

compat_type: Two options, GGA or Advanced. GGA means all GGA+U 

entries are excluded. Advanced means mixing scheme is 

implemented to make entries compatible with each other, 

but entries which are supposed to be done in GGA+U will have the 

equivalent GGA entries excluded. For example, Fe oxides should 

have a U value under the Advanced scheme. A GGA Fe oxide run 

will therefore be excluded under the scheme. 

correct_peroxide: Specify whether peroxide/superoxide/ozonide 

corrections are to be applied or not. 

check_potcar_hash (bool): Use potcar hash to verify potcars are correct. 

""" 

 

def __init__(self, compat_type="Advanced", correct_peroxide=True, 

check_potcar_hash=False): 

module_dir = os.path.dirname(os.path.abspath(__file__)) 

fp = os.path.join(module_dir, "MITCompatibility.yaml") 

i_s = MITVaspInputSet() 

super(MITAqueousCompatibility, self).__init__( 

[PotcarCorrection(i_s, check_hash=check_potcar_hash), 

GasCorrection(fp), 

AnionCorrection(fp, correct_peroxide=correct_peroxide), 

UCorrection(fp, i_s, compat_type), AqueousCorrection(fp)]) 

 

 

class MaterialsProjectAqueousCompatibility(Compatibility): 

""" 

This class implements the GGA/GGA+U mixing scheme, which allows mixing of 

entries. Note that this should only be used for VASP calculations using the 

MaterialsProject parameters (see pymatgen.io.vaspio_set.MPVaspInputSet). 

Using this compatibility scheme on runs with different parameters is not 

valid. 

 

Args: 

compat_type: Two options, GGA or Advanced. GGA means all GGA+U 

entries are excluded. Advanced means mixing scheme is 

implemented to make entries compatible with each other, 

but entries which are supposed to be done in GGA+U will have the 

equivalent GGA entries excluded. For example, Fe oxides should 

have a U value under the Advanced scheme. A GGA Fe oxide run 

will therefore be excluded under the scheme. 

correct_peroxide: Specify whether peroxide/superoxide/ozonide 

corrections are to be applied or not. 

check_potcar_hash (bool): Use potcar hash to verify potcars are correct. 

""" 

 

def __init__(self, compat_type="Advanced", correct_peroxide=True, 

check_potcar_hash=False): 

module_dir = os.path.dirname(os.path.abspath(__file__)) 

fp = os.path.join(module_dir, "MPCompatibility.yaml") 

i_s = MPVaspInputSet() 

super(MaterialsProjectAqueousCompatibility, self).__init__( 

[PotcarCorrection(i_s, check_hash=check_potcar_hash), 

GasCorrection(fp), 

AnionCorrection(fp, correct_peroxide=correct_peroxide), 

UCorrection(fp, i_s, compat_type), AqueousCorrection(fp)])