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

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

# coding: utf-8 

# Copyright (c) Pymatgen Development Team. 

# Distributed under the terms of the MIT License. 

 

from __future__ import division, unicode_literals, print_function 

 

import os 

import abc 

 

import re 

import traceback 

import shutil 

from functools import partial 

from glob import glob 

import warnings 

 

import six 

import numpy as np 

 

from monty.serialization import loadfn 

from monty.dev import deprecated 

 

from pymatgen.io.vasp.inputs import Incar, Poscar, Potcar, Kpoints 

from pymatgen.io.vasp.outputs import Vasprun, Outcar, Chgcar 

from monty.json import MSONable, MontyDecoder 

from pymatgen.symmetry.analyzer import SpacegroupAnalyzer 

from pymatgen.symmetry.bandstructure import HighSymmKpath 

from pymatgen.analysis.structure_matcher import StructureMatcher 

 

""" 

This module defines the VaspInputSet abstract base class and a concrete 

implementation for the parameters used by the Materials Project and the MIT 

high throughput project. The basic concept behind an input set is to specify 

a scheme to generate a consistent set of VASP inputs from a structure 

without further user intervention. This ensures comparability across 

runs. 

""" 

 

__author__ = "Shyue Ping Ong, Wei Chen, Will Richards, Geoffroy Hautier" 

__copyright__ = "Copyright 2011, The Materials Project" 

__version__ = "1.0" 

__maintainer__ = "Shyue Ping Ong" 

__email__ = "shyuep@gmail.com" 

__date__ = "Nov 16, 2011" 

 

 

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

 

 

class AbstractVaspInputSet(six.with_metaclass(abc.ABCMeta, MSONable)): 

""" 

Abstract base class representing a set of Vasp input parameters. 

The idea is that using a VaspInputSet, a complete set of input files 

(INPUT, KPOINTS, POSCAR and POTCAR) can be generated in an automated 

fashion for any structure. 

""" 

 

@abc.abstractmethod 

def get_poscar(self, structure): 

""" 

Returns Poscar from a structure. 

""" 

return 

 

@abc.abstractmethod 

def get_kpoints(self, structure): 

""" 

Returns Kpoints from a structure. 

 

Args: 

structure (Structure/IStructure): Structure to generate kpoints 

for. 

 

Returns: 

Kpoints object 

""" 

return 

 

@abc.abstractmethod 

def get_incar(self, structure): 

""" 

Returns Incar from a structure. 

 

Args: 

structure (Structure/IStructure): Structure to generate Incar for. 

 

Returns: 

Incar object 

""" 

return 

 

@abc.abstractmethod 

def get_potcar(self, structure): 

""" 

Returns Potcar from a structure. 

 

Args: 

structure (Structure/IStructure): Structure to generate potcar 

for. 

 

Returns: 

Potcar object 

""" 

return 

 

@abc.abstractmethod 

def get_potcar_symbols(self, structure): 

""" 

Returns list of POTCAR symbols from a structure. 

 

Args: 

structure (Structure/IStructure): Structure to generate potcar 

symbols for. 

 

Returns: 

List of POTCAR symbols 

""" 

return 

 

def get_all_vasp_input(self, structure, generate_potcar=True): 

""" 

Returns all input files as a dict of {filename: vasp object} 

 

Args: 

structure (Structure/IStructure): Structure to generate vasp 

input for. 

generate_potcar (bool): Set to False to generate a POTCAR.spec 

file instead of a POTCAR, which contains the POTCAR labels 

but not the actual POTCAR. Defaults to True. 

 

Returns: 

dict of {filename: file_as_string}, e.g., {'INCAR':'EDIFF=1e-4...'} 

""" 

kpoints = self.get_kpoints(structure) 

incar = self.get_incar(structure) 

if np.product(kpoints.kpts) < 4 and incar.get("ISMEAR", 0) == -5: 

incar["ISMEAR"] = 0 

 

d = {'INCAR': incar, 

'KPOINTS': kpoints, 

'POSCAR': self.get_poscar(structure)} 

 

if generate_potcar: 

d['POTCAR'] = self.get_potcar(structure) 

else: 

d['POTCAR.spec'] = "\n".join(self.get_potcar_symbols(structure)) 

return d 

 

def write_input(self, structure, output_dir, 

make_dir_if_not_present=True, include_cif=False): 

""" 

Writes a set of VASP input to a directory. 

 

Args: 

structure (Structure/IStructure): Structure to write VASP input 

files for. 

output_dir (str): Directory to output the VASP input files 

make_dir_if_not_present (bool): Set to True if you want the 

directory (and the whole path) to be created if it is not 

present. 

include_cif (bool): Whether to write a CIF file in the output 

directory for easier opening by VESTA. 

""" 

if make_dir_if_not_present and not os.path.exists(output_dir): 

os.makedirs(output_dir) 

for k, v in self.get_all_vasp_input(structure).items(): 

v.write_file(os.path.join(output_dir, k)) 

if k == "POSCAR" and include_cif: 

v.structure.to( 

filename=os.path.join(output_dir, 

"%s.cif" % v.structure.formula)) 

 

 

class DictVaspInputSet(AbstractVaspInputSet): 

""" 

Concrete implementation of VaspInputSet that is initialized from a dict 

settings. This allows arbitrary settings to be input. In general, 

this is rarely used directly unless there is a source of settings in yaml 

format (e.g., from a REST interface). It is typically used by other 

VaspInputSets for initialization. 

 

Special consideration should be paid to the way the MAGMOM initialization 

for the INCAR is done. The initialization differs depending on the type of 

structure and the configuration settings. The order in which the magmom is 

determined is as follows: 

 

1. If the site itself has a magmom setting, that is used. 

2. If the species on the site has a spin setting, that is used. 

3. If the species itself has a particular setting in the config file, that 

is used, e.g., Mn3+ may have a different magmom than Mn4+. 

4. Lastly, the element symbol itself is checked in the config file. If 

there are no settings, VASP's default of 0.6 is used. 

 

Args: 

name (str): A name fo the input set. 

config_dict (dict): The config dictionary to use. 

hubbard_off (bool): Whether to turn off Hubbard U if it is specified in 

config_dict. Defaults to False, i.e., follow settings in 

config_dict. 

user_incar_settings (dict): User INCAR settings. This allows a user 

to override INCAR settings, e.g., setting a different MAGMOM for 

various elements or species. 

constrain_total_magmom (bool): Whether to constrain the total magmom 

(NUPDOWN in INCAR) to be the sum of the expected MAGMOM for all 

species. Defaults to False. 

sort_structure (bool): Whether to sort the structure (using the 

default sort order of electronegativity) before generating input 

files. Defaults to True, the behavior you would want most of the 

time. This ensures that similar atomic species are grouped 

together. 

ediff_per_atom (bool): Whether the EDIFF is specified on a per atom 

basis. This is generally desired, though for some calculations ( 

e.g. NEB) this should be turned off (and an appropriate EDIFF 

supplied in user_incar_settings) 

potcar_functional (str): Functional to use. Default (None) is to use 

the functional in Potcar.DEFAULT_FUNCTIONAL. Valid values: 

"PBE", "LDA", "PW91", "LDA_US" 

force_gamma (bool): Force gamma centered kpoint generation. Default 

(False) is to use the Automatic Density kpoint scheme, which 

will use the Gamma centered generation scheme for hexagonal 

cells, and Monkhorst-Pack otherwise. 

reduce_structure (None/str): Before generating the input files, 

generate the reduced structure. Default (None), does not 

alter the structure. Valid values: None, "niggli", "LLL" 

""" 

 

def __init__(self, name, config_dict, hubbard_off=False, 

user_incar_settings=None, 

constrain_total_magmom=False, sort_structure=True, 

ediff_per_atom=True, potcar_functional=None, 

force_gamma=False, reduce_structure=None): 

self.name = name 

self.potcar_settings = config_dict["POTCAR"] 

self.kpoints_settings = config_dict['KPOINTS'] 

self.incar_settings = config_dict['INCAR'] 

self.set_nupdown = constrain_total_magmom 

self.sort_structure = sort_structure 

self.ediff_per_atom = ediff_per_atom 

self.hubbard_off = hubbard_off 

self.potcar_functional = potcar_functional 

self.force_gamma = force_gamma 

self.reduce_structure = reduce_structure 

if hubbard_off: 

for k in list(self.incar_settings.keys()): 

if k.startswith("LDAU"): 

del self.incar_settings[k] 

if user_incar_settings: 

self.incar_settings.update(user_incar_settings) 

 

def get_incar(self, structure): 

incar = Incar() 

if self.reduce_structure: 

structure = structure.get_reduced_structure(self.reduce_structure) 

if self.sort_structure: 

structure = structure.get_sorted_structure() 

comp = structure.composition 

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

key=lambda e: e.X) 

most_electroneg = elements[-1].symbol 

poscar = Poscar(structure) 

for key, setting in self.incar_settings.items(): 

if key == "MAGMOM": 

mag = [] 

for site in structure: 

if hasattr(site, 'magmom'): 

mag.append(site.magmom) 

elif hasattr(site.specie, 'spin'): 

mag.append(site.specie.spin) 

elif str(site.specie) in setting: 

mag.append(setting.get(str(site.specie))) 

else: 

mag.append(setting.get(site.specie.symbol, 0.6)) 

incar[key] = mag 

elif key in ('LDAUU', 'LDAUJ', 'LDAUL'): 

if hasattr(structure[0], key.lower()): 

m = dict([(site.specie.symbol, getattr(site, key.lower())) 

for site in structure]) 

incar[key] = [m[sym] for sym in poscar.site_symbols] 

elif most_electroneg in setting.keys(): 

incar[key] = [setting[most_electroneg].get(sym, 0) 

for sym in poscar.site_symbols] 

else: 

incar[key] = [0] * len(poscar.site_symbols) 

elif key == "EDIFF": 

if self.ediff_per_atom: 

incar[key] = float(setting) * structure.num_sites 

else: 

incar[key] = float(setting) 

else: 

incar[key] = setting 

 

has_u = ("LDAUU" in incar and sum(incar['LDAUU']) > 0) 

if has_u: 

# modify LMAXMIX if LSDA+U and you have d or f electrons 

# note that if the user explicitly sets LMAXMIX in settings it will 

# override this logic. 

if 'LMAXMIX' not in self.incar_settings.keys(): 

# contains f-electrons 

if any([el.Z > 56 for el in structure.composition]): 

incar['LMAXMIX'] = 6 

# contains d-electrons 

elif any([el.Z > 20 for el in structure.composition]): 

incar['LMAXMIX'] = 4 

else: 

for key in list(incar.keys()): 

if key.startswith('LDAU'): 

del incar[key] 

 

if self.set_nupdown: 

nupdown = sum([mag if abs(mag) > 0.6 else 0 

for mag in incar['MAGMOM']]) 

incar['NUPDOWN'] = nupdown 

 

return incar 

 

def get_poscar(self, structure): 

if self.reduce_structure: 

structure = structure.get_reduced_structure(self.reduce_structure) 

if self.sort_structure: 

structure = structure.get_sorted_structure() 

return Poscar(structure) 

 

def get_potcar(self, structure, check_hash=False): 

if self.reduce_structure: 

structure = structure.get_reduced_structure(self.reduce_structure) 

if self.sort_structure: 

structure = structure.get_sorted_structure() 

if self.potcar_functional: 

p = Potcar(self.get_potcar_symbols(structure), 

functional=self.potcar_functional) 

else: 

p = Potcar(self.get_potcar_symbols(structure)) 

 

if check_hash: 

hash_check = [ps.hash == self.potcar_settings[ps.element][ 

'hash'] for ps in p] 

if all(hash_check): 

return p 

else: 

wrong_hashes = [p.symbols[i] for i, tf in enumerate( 

hash_check) if not tf] 

raise ValueError("Potcars {} have different hashes " 

"than those specified in the config " 

"dictionary".format(wrong_hashes)) 

else: 

return p 

 

def get_nelect(self, structure): 

""" 

Gets the default number of electrons for a given structure. 

""" 

n = 0 

for ps in self.get_potcar(structure): 

n += structure.composition[ps.element] * ps.ZVAL 

return n 

 

def get_potcar_symbols(self, structure): 

if self.reduce_structure: 

structure = structure.get_reduced_structure(self.reduce_structure) 

if self.sort_structure: 

structure = structure.get_sorted_structure() 

p = self.get_poscar(structure) 

elements = p.site_symbols 

potcar_symbols = [] 

 

if isinstance(self.potcar_settings[elements[-1]], dict): 

for el in elements: 

potcar_symbols.append(self.potcar_settings[el]['symbol'] 

if el in self.potcar_settings else el) 

else: 

for el in elements: 

potcar_symbols.append(self.potcar_settings[el] 

if el in self.potcar_settings else el) 

 

return potcar_symbols 

 

def get_kpoints(self, structure): 

""" 

Writes out a KPOINTS file using the fully automated grid method. Uses 

Gamma centered meshes for hexagonal cells and Monk grids otherwise. 

 

Algorithm: 

Uses a simple approach scaling the number of divisions along each 

reciprocal lattice vector proportional to its length. 

""" 

if self.reduce_structure: 

structure = structure.get_reduced_structure(self.reduce_structure) 

if self.sort_structure: 

structure = structure.get_sorted_structure() 

 

# If grid_density is in the kpoints_settings use Kpoints.automatic_density 

if self.kpoints_settings.get('grid_density'): 

return Kpoints.automatic_density( 

structure, int(self.kpoints_settings['grid_density']), 

self.force_gamma) 

 

# If reciprocal_density is in the kpoints_settings use Kpoints.automatic_density_by_vol 

elif self.kpoints_settings.get('reciprocal_density'): 

return Kpoints.automatic_density_by_vol( 

structure, int(self.kpoints_settings['reciprocal_density']), 

self.force_gamma) 

 

# If length is in the kpoints_settings use Kpoints.automatic 

elif self.kpoints_settings.get('length'): 

return Kpoints.automatic(self.kpoints_settings['length']) 

 

# Raise error. Unsure of which kpoint generation to use 

else: 

raise ValueError( 

"Invalid KPoint Generation algo : Supported Keys are " 

"grid_density: for Kpoints.automatic_density generation, " 

"reciprocal_density: for KPoints.automatic_density_by_vol generation, " 

"and length : for Kpoints.automatic generation") 

 

def __str__(self): 

return self.name 

 

def __repr__(self): 

output = [self.name, ""] 

section_names = ['INCAR settings', 'KPOINTS settings', 

'POTCAR settings'] 

count = 0 

for d in [self.incar_settings, self.kpoints_settings, 

self.potcar_settings]: 

output.append(section_names[count]) 

for k, v in d.items(): 

output.append("%s = %s" % (k, str(v))) 

output.append("") 

count += 1 

return "\n".join(output) 

 

def as_dict(self): 

config_dict = { 

"INCAR": self.incar_settings, 

"KPOINTS": self.kpoints_settings, 

"POTCAR": self.potcar_settings 

} 

return { 

"name": self.name, 

"config_dict": config_dict, 

"hubbard_off": self.hubbard_off, 

"constrain_total_magmom": self.set_nupdown, 

"sort_structure": self.sort_structure, 

"potcar_functional": self.potcar_functional, 

"ediff_per_atom": self.ediff_per_atom, 

"force_gamma": self.force_gamma, 

"reduce_structure": self.reduce_structure, 

"@class": self.__class__.__name__, 

"@module": self.__class__.__module__, 

} 

 

@classmethod 

def from_dict(cls, d): 

return cls(name=d["name"], config_dict=d["config_dict"], 

hubbard_off=d.get("hubbard_off", False), 

constrain_total_magmom=d["constrain_total_magmom"], 

sort_structure=d.get("sort_structure", True), 

potcar_functional=d.get("potcar_functional", None), 

ediff_per_atom=d.get("ediff_per_atom", True), 

force_gamma=d.get("force_gamma", False), 

reduce_structure=d.get("reduce_structure", None)) 

 

@staticmethod 

def from_file(name, filename, **kwargs): 

""" 

Creates a DictVaspInputSet from a yaml/json file. 

 

Args: 

name (str): A name for the input set. 

filename (str): Path to a yaml/json file containing the settings. 

\*\*kwargs: Same kwargs as in the constructor. 

 

Returns: 

DictVaspInputSet 

""" 

return DictVaspInputSet(name, loadfn(filename), **kwargs) 

 

 

MITVaspInputSet = partial(DictVaspInputSet.from_file, "MIT", 

os.path.join(MODULE_DIR, "MITVaspInputSet.yaml")) 

""" 

Standard implementation of VaspInputSet utilizing parameters in the MIT 

High-throughput project. 

The parameters are chosen specifically for a high-throughput project, 

which means in general pseudopotentials with fewer electrons were chosen. 

 

Please refer:: 

 

A Jain, G. Hautier, C. Moore, S. P. Ong, C. Fischer, T. Mueller, 

K. A. Persson, G. Ceder. A high-throughput infrastructure for density 

functional theory calculations. Computational Materials Science, 

2011, 50(8), 2295-2310. doi:10.1016/j.commatsci.2011.02.023 

""" 

 

MITGGAVaspInputSet = partial(DictVaspInputSet.from_file, "MIT GGA", 

os.path.join(MODULE_DIR, "MITVaspInputSet.yaml"), 

hubbard_off=True) 

""" 

GGA (no U) version of MITVaspInputSet. 

""" 

 

MITHSEVaspInputSet = partial( 

DictVaspInputSet.from_file, "MIT HSE", 

os.path.join(MODULE_DIR, "MITHSEVaspInputSet.yaml")) 

""" 

Typical implementation of input set for a HSE run using MIT parameters. 

""" 

 

 

class MITNEBVaspInputSet(DictVaspInputSet): 

""" 

Class for writing NEB inputs. Note that EDIFF is not on a per atom 

basis for this input set. 

 

Args: 

nimages (int): Number of NEB images (excluding start and ending 

structures). 

write_endpoint_files (bool): Whether to write KPOINTS, POTCAR, INCAR 

in the first and last folders. 

kpoints_gamma_override (iterable of ints): Gamma centered subdivisions 

to override the kpoints density of MITVaspInputSet.yaml 

write_path_cif (bool): Whether to write a cif of all the positions along 

the path. Useful for visualization 

\*\*kwargs: Other kwargs supported by :class:`DictVaspInputSet`. 

""" 

 

def __init__(self, nimages=8, user_incar_settings=None, 

write_endpoint_inputs=False, kpoints_gamma_override=None, 

write_path_cif=False, unset_encut=False, 

sort_structure=False, **kwargs): 

super(MITNEBVaspInputSet, self).__init__( 

"MIT NEB", 

loadfn(os.path.join(MODULE_DIR, "MITVaspInputSet.yaml")), 

ediff_per_atom=False, sort_structure=False, 

**kwargs) 

self.endpoint_set = MITVaspInputSet(ediff_per_atom=False, sort_structure=False) 

if unset_encut: 

del self.incar_settings["ENCUT"] 

del self.endpoint_set.incar_settings["ENCUT"] 

 

#NEB specific defaults 

defaults = {'IMAGES': nimages, 'IBRION': 1, 'ISYM': 0, 'LCHARG': False} 

endpoint_defaults = {'ISYM': 0, 'LCHARG': False} 

if user_incar_settings: 

defaults.update(user_incar_settings) 

endpoint_defaults.update(user_incar_settings) 

 

self.incar_settings.update(defaults) 

self.endpoint_set.incar_settings.update(endpoint_defaults) 

 

self.nimages = nimages 

 

self.kpoints_gamma_override = kpoints_gamma_override 

self.write_endpoint_inputs = write_endpoint_inputs 

self.write_path_cif = write_path_cif 

 

def _process_structures(self, structures): 

""" 

Remove any atom jumps across the cell 

""" 

input_structures = structures 

structures = [input_structures[0]] 

for s in input_structures[1:]: 

prev = structures[-1] 

for i in range(len(s)): 

t = np.round(prev[i].frac_coords - s[i].frac_coords) 

if np.sum(t) > 0.5: 

s.translate_sites([i], t, to_unit_cell=False) 

structures.append(s) 

return structures 

 

def write_input(self, structures, output_dir, make_dir_if_not_present=True, 

write_cif=False): 

""" 

NEB inputs has a special directory structure where inputs are in 00, 

01, 02, .... 

 

Args: 

structures ([Structure]): nimages + 2 structures (including 

start and end structures). 

output_dir (str): Directory to output the VASP input files 

make_dir_if_not_present (bool): Set to True if you want the 

directory (and the whole path) to be created if it is not 

present. 

write_cif (bool): If true, writes a cif along with each POSCAR. 

""" 

if len(structures) != self.incar_settings['IMAGES'] + 2: 

raise ValueError('incorrect number of structures') 

 

structures = self._process_structures(structures) 

 

if make_dir_if_not_present and not os.path.exists(output_dir): 

os.makedirs(output_dir) 

s0 = structures[0] 

self.get_incar(s0).write_file(os.path.join(output_dir, 'INCAR')) 

if self.kpoints_gamma_override: 

kpoints = Kpoints.gamma_automatic(self.kpoints_gamma_override) 

else: 

kpoints = self.get_kpoints(s0) 

potcar = self.get_potcar(s0) 

kpoints.write_file(os.path.join(output_dir, 'KPOINTS')) 

potcar.write_file(os.path.join(output_dir, 'POTCAR')) 

 

for i, s in enumerate(structures): 

d = os.path.join(output_dir, str(i).zfill(2)) 

if make_dir_if_not_present and not os.path.exists(d): 

os.makedirs(d) 

self.get_poscar(s).write_file(os.path.join(d, 'POSCAR')) 

if write_cif: 

s.to(filename=os.path.join(d, '{}.cif'.format(i))) 

if self.write_endpoint_inputs: 

incar = self.endpoint_set.get_incar(s0) 

for image in ['00', str(len(structures) - 1).zfill(2)]: 

incar.write_file(os.path.join(output_dir, image, 'INCAR')) 

kpoints.write_file(os.path.join(output_dir, image, 'KPOINTS')) 

potcar.write_file(os.path.join(output_dir, image, 'POTCAR')) 

if self.write_path_cif: 

from pymatgen import Structure, PeriodicSite 

from itertools import chain 

sites = set() 

l = structures[0].lattice 

for site in chain(*(s.sites for s in structures)): 

sites.add(PeriodicSite(site.species_and_occu, site.frac_coords, l)) 

path = Structure.from_sites(sorted(sites)) 

path.to(filename=os.path.join(output_dir, 'path.cif')) 

 

def as_dict(self): 

d = super(MITNEBVaspInputSet, self).as_dict() 

d["nimages"] = self.nimages 

return d 

 

@classmethod 

def from_dict(cls, d): 

return cls(user_incar_settings=d.get("user_incar_settings", None), 

constrain_total_magmom=d["constrain_total_magmom"], 

sort_structure=d.get("sort_structure", True), 

hubbard_off=d.get("hubbard_off", False), 

nimages=d["nimages"]) 

 

 

class MITMDVaspInputSet(DictVaspInputSet): 

""" 

Class for writing a vasp md run. This DOES NOT do multiple stage 

runs. 

 

Args: 

start_temp (int): Starting temperature. 

end_temp (int): Final temperature. 

nsteps (int): Number of time steps for simulations. The NSW parameter. 

time_step (int): The time step for the simulation. The POTIM 

parameter. Defaults to 2fs. 

hubbard_off (bool): Whether to turn off Hubbard U. Defaults to 

*True* (different behavior from standard input sets) for MD runs. 

spin_polarized (bool): Whether to do spin polarized calculations. 

The ISPIN parameter. Defaults to False. 

sort_structure (bool): Whether to sort structure. Defaults to False 

(different behavior from standard input sets). 

**kwargs: 

Other kwargs supported by :class:`DictVaspInputSet`. 

""" 

 

def __init__(self, start_temp, end_temp, nsteps, time_step=2, 

hubbard_off=True, spin_polarized=False, 

sort_structure=False, user_incar_settings=None, 

**kwargs): 

 

#MD default settings 

defaults = {'TEBEG': start_temp, 'TEEND': end_temp, 'NSW': nsteps, 

'EDIFF': 0.000001, 'LSCALU': False, 'LCHARG': False, 

'LPLANE': False, 'LWAVE': True, 'ISMEAR': 0, 

'NELMIN': 4, 'LREAL': True, 'BMIX': 1, 

'MAXMIX': 20, 'NELM': 500, 'NSIM': 4, 'ISYM': 0, 

'ISIF': 0, 'IBRION': 0, 'NBLOCK': 1, 'KBLOCK': 100, 

'SMASS': 0, 'POTIM': time_step, 'PREC': 'Normal', 

'ISPIN': 2 if spin_polarized else 1} 

 

#override default settings with user supplied settings 

if user_incar_settings: 

defaults.update(user_incar_settings) 

super(MITMDVaspInputSet, self).__init__( 

"MIT MD", 

loadfn(os.path.join(MODULE_DIR, "MITVaspInputSet.yaml")), 

hubbard_off=hubbard_off, sort_structure=sort_structure, 

user_incar_settings=defaults, **kwargs) 

 

self.start_temp = start_temp 

self.end_temp = end_temp 

self.nsteps = nsteps 

self.time_step = time_step 

self.spin_polarized = spin_polarized 

self.user_incar_settings = user_incar_settings or {} 

 

#use VASP default ENCUT 

if 'ENCUT' not in self.user_incar_settings: 

del self.incar_settings['ENCUT'] 

 

if defaults['ISPIN'] == 1: 

del self.incar_settings['MAGMOM'] 

 

def get_kpoints(self, structure): 

return Kpoints.gamma_automatic() 

 

def as_dict(self): 

d = super(MITMDVaspInputSet, self).as_dict() 

d.update({ 

"start_temp": self.start_temp, 

"end_temp": self.end_temp, 

"nsteps": self.nsteps, 

"time_step": self.time_step, 

"spin_polarized": self.spin_polarized, 

"user_incar_settings": self.user_incar_settings 

}) 

return d 

 

@classmethod 

def from_dict(cls, d): 

return cls(start_temp=d["start_temp"], end_temp=d["end_temp"], 

nsteps=d["nsteps"], time_step=d["time_step"], 

hubbard_off=d.get("hubbard_off", False), 

user_incar_settings=d["user_incar_settings"], 

spin_polarized=d.get("spin_polarized", False), 

constrain_total_magmom=d["constrain_total_magmom"], 

sort_structure=d.get("sort_structure", True)) 

 

 

MPVaspInputSet = partial(DictVaspInputSet.from_file, "MP", 

os.path.join(MODULE_DIR, "MPVaspInputSet.yaml")) 

""" 

Implementation of VaspInputSet utilizing parameters in the public 

Materials Project. Typically, the pseudopotentials chosen contain more 

electrons than the MIT parameters, and the k-point grid is ~50% more dense. 

The LDAUU parameters are also different due to the different psps used, 

which result in different fitted values. 

""" 

 

MPGGAVaspInputSet = partial(DictVaspInputSet.from_file, "MP GGA", 

os.path.join(MODULE_DIR, "MPVaspInputSet.yaml"), 

hubbard_off=True) 

""" 

Same as the MPVaspInput set, but the +U is enforced to be turned off. 

""" 

 

 

MPHSEVaspInputSet = partial(DictVaspInputSet.from_file, "MP HSE", 

os.path.join(MODULE_DIR, "MPHSEVaspInputSet.yaml")) 

""" 

Same as the MPVaspInput set, but with HSE parameters. 

""" 

 

 

class MPStaticVaspInputSet(DictVaspInputSet): 

""" 

Implementation of VaspInputSet overriding MaterialsProjectVaspInputSet 

for static calculations that typically follow relaxation runs. 

It is recommended to use the static from_previous_run method to construct 

the input set to inherit most of the functions. 

 

Args: 

kpoints_density (int): kpoints density for the reciprocal cell of 

structure. Might need to increase the default value when 

calculating metallic materials. 

sym_prec (float): Tolerance for symmetry finding 

 

kwargs: 

hubbard_off (bool): Whether to turn off Hubbard U if it is specified in 

config_dict ("MP Static"). Defaults to False, i.e., follow settings 

in config_dict. 

user_incar_settings (dict): User INCAR settings. This allows a user 

to override INCAR settings, e.g., setting a different MAGMOM for 

various elements or species. 

constrain_total_magmom (bool): Whether to constrain the total magmom 

(NUPDOWN in INCAR) to be the sum of the expected MAGMOM for all 

species. Defaults to False. 

sort_structure (bool): Whether to sort the structure (using the 

default sort order of electronegativity) before generating input 

files. Defaults to True, the behavior you would want most of the 

time. This ensures that similar atomic species are grouped 

together. 

ediff_per_atom (bool): Whether the EDIFF is specified on a per atom 

basis. 

""" 

 

def __init__(self, kpoints_density=90, sym_prec=0.1, **kwargs): 

super(MPStaticVaspInputSet, self).__init__( 

"MP Static", 

loadfn(os.path.join(MODULE_DIR, "MPVaspInputSet.yaml")), 

**kwargs) 

self.incar_settings.update( 

{"IBRION": -1, "ISMEAR": -5, "LAECHG": True, "LCHARG": True, 

"LORBIT": 11, "LVHAR": True, "LWAVE": False, "NSW": 0, 

"ICHARG": 0, "EDIFF": 0.000001, "ALGO": "Normal"}) 

self.kpoints_settings.update({"kpoints_density": kpoints_density}) 

self.sym_prec = sym_prec 

 

def get_kpoints(self, structure, primitive_standard=False): 

""" 

Get a KPOINTS file using the fully automated grid method. Uses 

Gamma centered meshes for hexagonal cells and Monk grids otherwise. 

 

Args: 

structure (Structure/IStructure): structure to get kpoints 

primitive_standard (Bool): whether the input structure is 

a primitive standardized cell 

""" 

if not primitive_standard: 

structure = self.get_poscar(structure).structure 

self.kpoints_settings['grid_density'] = \ 

self.kpoints_settings["kpoints_density"] * \ 

structure.lattice.reciprocal_lattice.volume * \ 

structure.num_sites 

return super(MPStaticVaspInputSet, self).get_kpoints(structure) 

 

def get_poscar(self, structure): 

""" 

Get a POSCAR file with a primitive standardized cell of 

the giving structure. 

 

Args: 

structure (Structure/IStructure): structure to get POSCAR 

""" 

sym_finder = SpacegroupAnalyzer(structure, symprec=self.sym_prec) 

return Poscar(sym_finder.get_primitive_standard_structure(False)) 

 

@staticmethod 

def get_structure(vasp_run, outcar=None, initial_structure=False, 

additional_info=False, sym_prec=0.1): 

""" 

Process structure for static calculations from previous run. 

 

Args: 

vasp_run (Vasprun): Vasprun that contains the final structure 

from previous run. 

outcar (Outcar): Outcar that contains the magnetization info from 

previous run. 

initial_structure (bool): Whether to return the structure from 

previous run. Default is False. 

additional_info (bool): 

Whether to return additional symmetry info related to the 

structure. If True, return a list of the refined structure ( 

conventional cell), the conventional standard structure, 

the symmetry dataset and symmetry operations of the 

structure (see SpacegroupAnalyzer doc for details). 

sym_prec (float): Tolerance for symmetry finding 

 

Returns: 

Returns the magmom-decorated structure that can be passed to get 

Vasp input files, e.g. get_kpoints. 

""" 

if vasp_run.is_spin: 

if outcar and outcar.magnetization: 

magmom = {"magmom": [i['tot'] for i in outcar.magnetization]} 

else: 

magmom = { 

"magmom": vasp_run.as_dict()['input']['parameters'] 

['MAGMOM']} 

else: 

magmom = None 

structure = vasp_run.final_structure 

if magmom: 

structure = structure.copy(site_properties=magmom) 

sym_finder = SpacegroupAnalyzer(structure, symprec=sym_prec) 

if initial_structure: 

return structure 

elif additional_info: 

info = [sym_finder.get_refined_structure(), 

sym_finder.get_conventional_standard_structure(False), 

sym_finder.get_symmetry_dataset(), 

sym_finder.get_symmetry_operations()] 

return [sym_finder.get_primitive_standard_structure(False), 

info] 

else: 

return sym_finder.get_primitive_standard_structure(False) 

 

@staticmethod 

@deprecated(message="Replaced by MPStaticSet. Will be removed in pmg 4.0.") 

def from_previous_vasp_run(previous_vasp_dir, output_dir='.', 

user_incar_settings=None, 

make_dir_if_not_present=True, 

kpoints_density=90, sym_prec=0.1): 

""" 

Generate a set of Vasp input files for static calculations from a 

directory of previous Vasp run. 

 

Args: 

previous_vasp_dir (str): Directory containing the outputs( 

vasprun.xml and OUTCAR) of previous vasp run. 

output_dir (str): Directory to write the VASP input files for 

the static calculations. Defaults to current directory. 

make_dir_if_not_present (bool): Set to True if you want the 

directory (and the whole path) to be created if it is not 

present. 

kpoints_density (int): kpoints density for the reciprocal cell 

of structure. Might need to increase the default value when 

calculating metallic materials. 

sym_prec (float): Tolerance for symmetry finding 

""" 

# Read input and output from previous run 

try: 

vasp_run = Vasprun(os.path.join(previous_vasp_dir, "vasprun.xml"), 

parse_dos=False, parse_eigen=None) 

outcar = Outcar(os.path.join(previous_vasp_dir, "OUTCAR")) 

previous_incar = vasp_run.incar 

previous_kpoints = vasp_run.kpoints 

except: 

traceback.print_exc() 

raise RuntimeError("Can't get valid results from previous run. prev dir: {}".format(previous_vasp_dir)) 

 

mpsvip = MPStaticVaspInputSet(kpoints_density=kpoints_density, 

sym_prec=sym_prec) 

structure = mpsvip.get_structure(vasp_run, outcar) 

 

mpsvip.write_input(structure, output_dir, make_dir_if_not_present) 

new_incar = mpsvip.get_incar(structure) 

 

# Use previous run INCAR and override necessary parameters 

previous_incar.update({"IBRION": -1, "ISMEAR": -5, "LAECHG": True, 

"LCHARG": True, "LORBIT": 11, "LVHAR": True, 

"LWAVE": False, "NSW": 0, "ICHARG": 0, 

"ALGO": "Normal"}) 

 

for incar_key in ["MAGMOM", "NUPDOWN"]: 

if new_incar.get(incar_key, None): 

previous_incar.update({incar_key: new_incar[incar_key]}) 

else: 

previous_incar.pop(incar_key, None) 

 

# use new LDAUU when possible b/c the Poscar might have changed 

# representation 

if previous_incar.get('LDAU'): 

u = previous_incar.get('LDAUU', []) 

j = previous_incar.get('LDAUJ', []) 

if sum([u[x] - j[x] for x, y in enumerate(u)]) > 0: 

for tag in ('LDAUU', 'LDAUL', 'LDAUJ'): 

previous_incar.update({tag: new_incar[tag]}) 

# ensure to have LMAXMIX for GGA+U static run 

if "LMAXMIX" not in previous_incar: 

previous_incar.update({"LMAXMIX": new_incar["LMAXMIX"]}) 

 

# Compare ediff between previous and staticinputset values, 

# choose the tighter ediff 

previous_incar.update({"EDIFF": min(previous_incar.get("EDIFF", 1), 

new_incar["EDIFF"])}) 

 

# add user settings 

if user_incar_settings: 

previous_incar.update(user_incar_settings) 

previous_incar.write_file(os.path.join(output_dir, "INCAR")) 

 

# Perform checking on INCAR parameters 

if any([previous_incar.get("NSW", 0) != 0, 

previous_incar["IBRION"] != -1, 

previous_incar["LCHARG"] is not True, 

any([sum(previous_incar["LDAUU"]) <= 0, 

previous_incar["LMAXMIX"] < 4]) 

if previous_incar.get("LDAU") else False]): 

raise ValueError("Incompatible INCAR parameters!") 

 

# Prefer to use k-point scheme from previous run 

new_kpoints = mpsvip.get_kpoints(structure) 

if previous_kpoints.style != new_kpoints.style: 

if previous_kpoints.style == Kpoints.supported_modes.Monkhorst and \ 

SpacegroupAnalyzer(structure, 0.1).get_lattice_type() != \ 

"hexagonal": 

k_div = (kp + 1 if kp % 2 == 1 else kp 

for kp in new_kpoints.kpts[0]) 

Kpoints.monkhorst_automatic(k_div). \ 

write_file(os.path.join(output_dir, "KPOINTS")) 

else: 

Kpoints.gamma_automatic(new_kpoints.kpts[0]). \ 

write_file(os.path.join(output_dir, "KPOINTS")) 

else: 

new_kpoints.write_file(os.path.join(output_dir, "KPOINTS")) 

 

 

class MPStaticDielectricDFPTVaspInputSet(DictVaspInputSet): 

""" 

Using MP parameters to compute a static dielectric constant 

with DFPT. This includes the electronic and ionic contributions 

to the static dielectric constant. 

 

Args: 

user_incar_settings (dict): A dict specifying additional incar 

settings 

ionic: a boolean telling if we clamp the ions (False) or we 

add the ionic part to the dielectric constant (True default) 

""" 

 

def __init__(self, user_incar_settings=None, ionic=True): 

super(MPStaticDielectricDFPTVaspInputSet, self).__init__( 

"Materials Project Static Dielectric DFPT", 

loadfn(os.path.join(MODULE_DIR, "MPVaspInputSet.yaml"))) 

self.user_incar_settings = user_incar_settings if \ 

user_incar_settings is not None else {} 

self.incar_settings.update(self.user_incar_settings) 

if ionic: 

self.incar_settings.update( 

{"IBRION": 8, "LEPSILON": True, 'LREAL':False}) 

else: 

self.incar_settings.update( 

{"LEPSILON": True, 'LREAL': False}) 

if 'NPAR' in self.incar_settings: 

del self.incar_settings['NPAR'] 

if 'NSW' in self.incar_settings: 

del self.incar_settings['NSW'] 

 

 

class MPBSHSEVaspInputSet(DictVaspInputSet): 

""" 

Implementation of a VaspInputSet for HSE band structure computations 

Remember that HSE band structures cannot be non-self consistent. So, a band 

structure along syymetry lines for instance needs a uniform grid with 

appropriate weights + weight 0 path in reciprocal space 

 

Args: 

user_incar_settings(dict): A dict specifying additional incar 

settings 

added_kpoints: a list of kpoints (list of 3 number list) with weight 0 

added to the run. The k-points are in fractional coordinates 

kpoints_density: the kpoint density of the uniform grid used for the 

band structure run (By default: this is the same as in 

MPHSEVaspInputSet, i.e. 1000 / atom). Note that the uniform grid is 

always Gamma centered for now (this might be changed ?). 

mode: Line: Generate k-points along symmetry lines for 

bandstructure. Uniform: Generate uniform k-points grid 

 

""" 

 

def __init__(self, user_incar_settings=None, added_kpoints=None, mode="Line", 

kpoints_density=None, kpoints_line_density=20): 

super(MPBSHSEVaspInputSet, self).__init__( 

"Materials Project HSE Band Structure", 

loadfn(os.path.join(MODULE_DIR, "MPHSEVaspInputSet.yaml"))) 

self.user_incar_settings = user_incar_settings if \ 

user_incar_settings is not None else {} 

self.incar_settings.update( 

{"NSW": 0, "ISMEAR": 0, "SIGMA": 0.05, "ISYM": 0, "LCHARG": False}) 

self.incar_settings.update(self.user_incar_settings) 

self.added_kpoints = added_kpoints if added_kpoints is not None else [] 

self.mode = mode 

self.kpoints_density = (kpoints_density if kpoints_density is not None 

else self.kpoints_settings['grid_density']) 

self.kpoints_line_density = kpoints_line_density 

 

def get_kpoints(self, structure): 

self.kpoints_settings['grid_density'] = self.kpoints_density 

grid = super(MPBSHSEVaspInputSet, self).get_kpoints(structure).kpts 

if self.mode == "Line": 

ir_kpts = SpacegroupAnalyzer(structure, symprec=0.1)\ 

.get_ir_reciprocal_mesh(grid[0]) 

kpath = HighSymmKpath(structure) 

frac_k_points, labels = kpath.get_kpoints(line_density=self.kpoints_line_density, 

coords_are_cartesian=False) 

kpts = [] 

weights = [] 

all_labels = [] 

for k in ir_kpts: 

kpts.append(k[0]) 

weights.append(int(k[1])) 

all_labels.append(None) 

for k in range(len(frac_k_points)): 

kpts.append(frac_k_points[k]) 

weights.append(0.0) 

all_labels.append(labels[k]) 

return Kpoints(comment="HSE run along symmetry lines", 

style=Kpoints.supported_modes.Reciprocal, 

num_kpts=len(kpts), 

kpts=kpts, kpts_weights=weights, labels=all_labels) 

 

elif self.mode == "Uniform": 

ir_kpts = SpacegroupAnalyzer(structure, symprec=0.1)\ 

.get_ir_reciprocal_mesh(grid[0]) 

kpts = [] 

weights = [] 

for k in ir_kpts: 

kpts.append(k[0]) 

weights.append(int(k[1])) 

for k in self.added_kpoints: 

kpts.append(k) 

weights.append(0.0) 

return Kpoints(comment="HSE run on uniform grid", 

style=Kpoints.supported_modes.Reciprocal, 

num_kpts=len(kpts), 

kpts=kpts, kpts_weights=weights) 

 

def as_dict(self): 

d = super(MPBSHSEVaspInputSet, self).as_dict() 

d['added_kpoints'] = self.added_kpoints 

d['mode'] = self.mode 

d['kpoints_density'] = self.kpoints_density 

d['kpoints_line_density'] = self.kpoints_line_density 

return d 

 

@classmethod 

def from_dict(cls, d): 

return cls(user_incar_settings=d.get("user_incar_settings", None), 

added_kpoints=d.get("added_kpoints", []), 

mode=d.get("mode", "Line"), 

kpoints_density=d.get("kpoints_density", None), 

kpoints_line_density=d.get("kpoints_line_density", 20)) 

 

 

 

class MPNonSCFVaspInputSet(MPStaticVaspInputSet): 

""" 

Implementation of VaspInputSet overriding MaterialsProjectVaspInputSet 

for non self-consistent field (NonSCF) calculation that follows 

a static run to calculate bandstructure, density of states(DOS) and etc. 

It is recommended to use the NonSCF from_previous_run method to construct 

the input set to inherit most of the functions. 

 

Args: 

user_incar_settings (dict): A dict specify customized settings 

for INCAR. Must contain a NBANDS value, suggest to use 

1.2*(NBANDS from static run). 

mode: Line: Generate k-points along symmetry lines for 

bandstructure. Uniform: Generate uniform k-points 

grids for DOS. 

constrain_total_magmom (bool): Whether to constrain the total 

magmom (NUPDOWN in INCAR) to be the sum of the expected 

MAGMOM for all species. Defaults to False. 

kpoints_density (int): kpoints density for the reciprocal cell 

of structure. Might need to increase the default value when 

calculating metallic materials. 

kpoints_line_density (int): kpoints density to use in line-mode. 

Might need to increase the default value when calculating 

metallic materials. 

sort_structure (bool): Whether to sort structure. Defaults to 

False. 

sym_prec (float): Tolerance for symmetry finding 

""" 

 

@deprecated(message="Replaced by MPNonSCFSet. Will be removed in pmg 4.0.") 

def __init__(self, user_incar_settings, mode="Line", 

constrain_total_magmom=False, sort_structure=False, 

kpoints_density=1000, sym_prec=0.1, kpoints_line_density=20): 

self.mode = mode 

self.sym_prec = sym_prec 

self.kpoints_line_density = kpoints_line_density 

if mode not in ["Line", "Uniform"]: 

raise ValueError("Supported modes for NonSCF runs are 'Line' and " 

"'Uniform'!") 

DictVaspInputSet.__init__(self, 

"Materials Project Static", 

loadfn(os.path.join(MODULE_DIR, "MPVaspInputSet.yaml")), 

constrain_total_magmom=constrain_total_magmom, 

sort_structure=sort_structure) 

self.user_incar_settings = user_incar_settings 

self.incar_settings.update( 

{"IBRION": -1, "ISMEAR": 0, "SIGMA": 0.001, "LCHARG": False, 

"LORBIT": 11, "LWAVE": False, "NSW": 0, "ISYM": 0, "ICHARG": 11}) 

self.kpoints_settings.update({"kpoints_density": kpoints_density}) 

if mode == "Uniform": 

# Set smaller steps for DOS output 

self.incar_settings.update({"NEDOS": 601}) 

if "NBANDS" not in user_incar_settings: 

raise KeyError("For NonSCF runs, NBANDS value from SC runs is " 

"required!") 

else: 

self.incar_settings.update(user_incar_settings) 

 

def get_kpoints(self, structure): 

""" 

Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are 

generated along high symmetry lines. In "Uniform" mode, kpoints are 

Gamma-centered mesh grid. Kpoints are written explicitly in both cases. 

 

Args: 

structure (Structure/IStructure): structure to get Kpoints 

""" 

if self.mode == "Line": 

kpath = HighSymmKpath(structure) 

frac_k_points, k_points_labels = kpath.get_kpoints( 

line_density=self.kpoints_line_density, 

coords_are_cartesian=False) 

return Kpoints(comment="Non SCF run along symmetry lines", 

style=Kpoints.supported_modes.Reciprocal, 

num_kpts=len(frac_k_points), 

kpts=frac_k_points, labels=k_points_labels, 

kpts_weights=[1] * len(frac_k_points)) 

else: 

num_kpoints = self.kpoints_settings["kpoints_density"] * \ 

structure.lattice.reciprocal_lattice.volume 

kpoints = Kpoints.automatic_density( 

structure, num_kpoints * structure.num_sites) 

mesh = kpoints.kpts[0] 

ir_kpts = SpacegroupAnalyzer(structure, symprec=self.sym_prec) \ 

.get_ir_reciprocal_mesh(mesh) 

kpts = [] 

weights = [] 

for k in ir_kpts: 

kpts.append(k[0]) 

weights.append(int(k[1])) 

return Kpoints(comment="Non SCF run on uniform grid", 

style=Kpoints.supported_modes.Reciprocal, 

num_kpts=len(ir_kpts), 

kpts=kpts, kpts_weights=weights) 

 

@staticmethod 

def get_incar_settings(vasp_run, outcar=None): 

""" 

Helper method to get necessary user_incar_settings from previous run. 

 

Args: 

vasp_run (Vasprun): Vasprun that contains the final 

structure from previous run. 

outcar (Outcar): Outcar that contains the magnetization info 

from previous run. 

 

""" 

# Turn off spin when magmom for every site is smaller than 0.02. 

if outcar and outcar.magnetization: 

site_magmom = np.array([i['tot'] for i in outcar.magnetization]) 

ispin = 2 if np.any(site_magmom[np.abs(site_magmom) > 0.02]) else 1 

elif vasp_run.is_spin: 

ispin = 2 

else: 

ispin = 1 

nbands = int(np.ceil(vasp_run.as_dict()["input"]["parameters"]["NBANDS"] 

* 1.2)) 

incar_settings = {"ISPIN": ispin, "NBANDS": nbands} 

for grid in ["NGX", "NGY", "NGZ"]: 

if vasp_run.incar.get(grid): 

incar_settings.update({grid: vasp_run.incar.get(grid)}) 

return incar_settings 

 

def get_incar(self, structure): 

incar = super(MPNonSCFVaspInputSet, self).get_incar(structure) 

incar.pop("MAGMOM", None) 

return incar 

 

def get_poscar(self, structure, get_primitive_standard=False): 

""" 

Get a POSCAR file of the giving structure. 

 

Args: 

structure (Structure/IStructure): structure to get POSCAR 

get_primitive_standard (bool): if convert the input structure to a 

primitive standard structure 

""" 

if get_primitive_standard: 

sym_finder = SpacegroupAnalyzer(structure, symprec=self.sym_prec) 

return Poscar(sym_finder.get_primitive_standard_structure(False)) 

else: 

return Poscar(structure) 

 

@staticmethod 

def from_previous_vasp_run(previous_vasp_dir, output_dir='.', 

mode="Uniform", user_incar_settings=None, 

copy_chgcar=True, make_dir_if_not_present=True, 

kpoints_density=1000, kpoints_line_density=20): 

""" 

Generate a set of Vasp input files for NonSCF calculations from a 

directory of previous static Vasp run. 

 

Args: 

previous_vasp_dir (str): The directory contains the outputs( 

vasprun.xml and OUTCAR) of previous vasp run. 

output_dir (str): The directory to write the VASP input files 

for the NonSCF calculations. Default to write in the current 

directory. 

mode (str): Line: Generate k-points along symmetry lines for 

bandstructure. Uniform: Generate uniform k-points 

grids for DOS. 

user_incar_settings (dict): A dict specify customized settings 

for INCAR. Must contain a NBANDS value, suggest to use 

1.2*(NBANDS from static run). 

copy_chgcar (bool): Default to copy CHGCAR from SC run 

make_dir_if_not_present (bool): Set to True if you want the 

directory (and the whole path) to be created if it is not 

present. 

kpoints_density (int): kpoints density for the reciprocal cell 

of structure. Might need to increase the default value when 

calculating metallic materials. 

kpoints_line_density (int): kpoints density to use in line-mode. 

Might need to increase the default value when calculating 

metallic materials. 

""" 

user_incar_settings = user_incar_settings or {} 

 

try: 

vasp_run = Vasprun(os.path.join(previous_vasp_dir, "vasprun.xml"), 

parse_dos=False, parse_eigen=None) 

outcar = Outcar(os.path.join(previous_vasp_dir, "OUTCAR")) 

previous_incar = vasp_run.incar 

except: 

traceback.print_exc() 

raise RuntimeError("Can't get valid results from previous run: {}" 

.format(previous_vasp_dir)) 

 

#Get a Magmom-decorated structure 

structure = MPNonSCFVaspInputSet.get_structure(vasp_run, outcar, 

initial_structure=True) 

nscf_incar_settings = MPNonSCFVaspInputSet.get_incar_settings(vasp_run, 

outcar) 

mpnscfvip = MPNonSCFVaspInputSet(nscf_incar_settings, mode, 

kpoints_density=kpoints_density, 

kpoints_line_density=kpoints_line_density) 

mpnscfvip.write_input(structure, output_dir, make_dir_if_not_present) 

if copy_chgcar: 

try: 

shutil.copyfile(os.path.join(previous_vasp_dir, "CHGCAR"), 

os.path.join(output_dir, "CHGCAR")) 

except Exception as e: 

traceback.print_exc() 

raise RuntimeError("Can't copy CHGCAR from SC run" + '\n' 

+ str(e)) 

 

#Overwrite necessary INCAR parameters from previous runs 

previous_incar.update({"IBRION": -1, "ISMEAR": 0, "SIGMA": 0.001, 

"LCHARG": False, "LORBIT": 11, "LWAVE": False, 

"NSW": 0, "ISYM": 0, "ICHARG": 11}) 

previous_incar.update(nscf_incar_settings) 

previous_incar.update(user_incar_settings) 

previous_incar.pop("MAGMOM", None) 

previous_incar.write_file(os.path.join(output_dir, "INCAR")) 

 

# Perform checking on INCAR parameters 

if any([previous_incar.get("NSW", 0) != 0, 

previous_incar["IBRION"] != -1, 

previous_incar["ICHARG"] != 11, 

any([sum(previous_incar["LDAUU"]) <= 0, 

previous_incar["LMAXMIX"] < 4]) 

if previous_incar.get("LDAU") else False]): 

raise ValueError("Incompatible INCAR parameters!") 

 

 

class MPOpticsNonSCFVaspInputSet(MPNonSCFVaspInputSet): 

""" 

Implementation of VaspInputSet overriding MaterialsProjectVaspInputSet 

for non self-consistent field (NonSCF) calculation with the computation 

of the dielectric function that follows a static run 

It is recommended to use the NonSCF from_previous_run method to construct 

the input set to inherit most of the functions. 

 

Args: 

user_incar_settings (dict): A dict specify customized settings 

for INCAR. Must contain a NBANDS value, suggest to use 

factor*(NBANDS from static run) with factor between 5 and 10. 

mode: Line: Generate k-points along symmetry lines for 

bandstructure. Uniform: Generate uniform k-points 

grids for DOS. 

constrain_total_magmom (bool): Whether to constrain the total 

magmom (NUPDOWN in INCAR) to be the sum of the expected 

MAGMOM for all species. Defaults to False. 

kpoints_density (int): kpoints density for the reciprocal cell 

of structure. Might need to increase the default value when 

calculating metallic materials. 

sort_structure (bool): Whether to sort structure. Defaults to 

False. 

sym_prec (float): Tolerance for symmetry finding 

""" 

 

@deprecated(message="Replaced by MPNonSCFSet with optics=True. Will " 

"be removed in pmg 4.0.") 

def __init__(self, user_incar_settings, 

constrain_total_magmom=False, sort_structure=False, 

kpoints_density=1000, sym_prec=0.1, nedos=2001): 

self.sym_prec = sym_prec 

self.nedos = nedos 

DictVaspInputSet.__init__( 

user_incar_settings, mode="Uniform", 

constrain_total_magmom=constrain_total_magmom, 

sort_structure=sort_structure, 

kpoints_density=kpoints_density, sym_prec=sym_prec) 

self.incar_settings.update({"NEDOS": nedos}) 

self.incar_settings.update({"LOPTICS": True}) 

 

@staticmethod 

def from_previous_vasp_run(previous_vasp_dir, output_dir='.', 

user_incar_settings=None, 

copy_chgcar=True, make_dir_if_not_present=True, 

nbands_factor=5.0, nedos=2001): 

""" 

Generate a set of Vasp input files for NonSCF calculations from a 

directory of previous static Vasp run. 

 

Args: 

previous_vasp_dir (str): The directory contains the outputs( 

vasprun.xml and OUTCAR) of previous vasp run. 

output_dir (str): The directory to write the VASP input files 

for the NonSCF calculations. Default to write in the current 

directory. 

user_incar_settings (dict): A dict specify customized settings 

for INCAR. Must contain a NBANDS value, suggest to use 

1.2*(NBANDS from static run). 

copy_chgcar (bool): Default to copy CHGCAR from SC run 

make_dir_if_not_present (bool): Set to True if you want the 

directory (and the whole path) to be created if it is not 

present. 

nbands_factor (float): Factor by which the number of bands is to be 

multiplied. Typical calculations of dielectric functions need a 

total number of bands of 5 to 10 times the number of valence 

bands. 

""" 

user_incar_settings = user_incar_settings or {} 

 

try: 

vasp_run = Vasprun(os.path.join(previous_vasp_dir, "vasprun.xml"), 

parse_dos=False, parse_eigen=False) 

outcar = Outcar(os.path.join(previous_vasp_dir, "OUTCAR")) 

previous_incar = vasp_run.incar 

except: 

traceback.print_exc() 

raise RuntimeError("Can't get valid results from previous run. prev dir: {}".format(previous_vasp_dir)) 

 

#Get a Magmom-decorated structure 

structure = MPNonSCFVaspInputSet.get_structure(vasp_run, outcar, 

initial_structure=True) 

nscf_incar_settings = MPNonSCFVaspInputSet.get_incar_settings(vasp_run, 

outcar) 

spin_band_settings = MPOpticsNonSCFVaspInputSet.get_ispin_nbands( 

vasp_run, outcar, nbands_factor=nbands_factor) 

mpnscfvip = MPNonSCFVaspInputSet(nscf_incar_settings, "Uniform") 

mpnscfvip.incar_settings.update(spin_band_settings) 

mpnscfvip.write_input(structure, output_dir, make_dir_if_not_present) 

if copy_chgcar: 

try: 

shutil.copyfile(os.path.join(previous_vasp_dir, "CHGCAR"), 

os.path.join(output_dir, "CHGCAR")) 

except Exception as e: 

traceback.print_exc() 

raise RuntimeError("Can't copy CHGCAR from SC run" + '\n' 

+ str(e)) 

 

#Overwrite necessary INCAR parameters from previous runs 

previous_incar.update({"IBRION": -1, "ISMEAR": 0, "SIGMA": 0.001, 

"LCHARG": False, "LORBIT": 11, "LWAVE": False, 

"NSW": 0, "ISYM": 0, "ICHARG": 11, 

"LOPTICS": True, "NEDOS": nedos}) 

previous_incar.update(nscf_incar_settings) 

previous_incar.update(spin_band_settings) 

previous_incar.update(user_incar_settings) 

previous_incar.pop("MAGMOM", None) 

previous_incar.write_file(os.path.join(output_dir, "INCAR")) 

 

# Perform checking on INCAR parameters 

if any([previous_incar.get("NSW", 0) != 0, 

previous_incar["IBRION"] != -1, 

previous_incar["ICHARG"] != 11, 

any([sum(previous_incar["LDAUU"]) <= 0, 

previous_incar["LMAXMIX"] < 4]) 

if previous_incar.get("LDAU") else False]): 

raise ValueError("Incompatible INCAR parameters!") 

 

@staticmethod 

def get_ispin_nbands(vasp_run, outcar=None, nbands_factor=5.0): 

""" 

Helper method to get necessary user_incar_settings from previous run. 

 

Args: 

vasp_run (Vasprun): Vasprun that contains the final 

structure from previous run. 

outcar (Outcar): Outcar that contains the magnetization info 

from previous run. 

 

""" 

# Turn off spin when magmom for every site is smaller than 0.02. 

if outcar and outcar.magnetization: 

site_magmom = np.array([i['tot'] for i in outcar.magnetization]) 

ispin = 2 if np.any(site_magmom[np.abs(site_magmom) > 0.02]) else 1 

elif vasp_run.is_spin: 

ispin = 2 

else: 

ispin = 1 

nbands = int(np.ceil(vasp_run.as_dict()["input"]["parameters"]["NBANDS"] 

* nbands_factor)) 

incar_settings = {"ISPIN": ispin, "NBANDS": nbands} 

for grid in ["NGX", "NGY", "NGZ"]: 

if vasp_run.incar.get(grid): 

incar_settings.update({grid: vasp_run.incar.get(grid)}) 

return incar_settings 

 

 

class MVLElasticInputSet(DictVaspInputSet): 

""" 

MVL denotes VASP input sets that are implemented by the Materials Virtual 

Lab (http://www.materialsvirtuallab.org) for various research. 

 

This input set is used to calculate elastic constants in VASP. It is used 

in the following work:: 

 

Z. Deng, Z. Wang, I.-H. Chu, J. Luo, S. P. Ong. 

“Elastic Properties of Alkali Superionic Conductor Electrolytes 

from First Principles Calculations”, J. Electrochem. Soc. 

2016, 163(2), A67-A74. doi: 10.1149/2.0061602jes 

 

To read the elastic constants, you may use the Outcar class which parses the 

elastic constants. 

 

Args: 

scale (float): POTIM parameter. The default of 0.015 is usually fine, 

but some structures may require a smaller step. 

user_incar_settings (dict): A dict specifying additional incar 

settings. 

""" 

 

def __init__(self, potim=0.015, user_incar_settings=None): 

super(MVLElasticInputSet, self).__init__( 

"Materials Virtual Lab Elastic Constant Calculation", 

loadfn(os.path.join(MODULE_DIR, "MPVaspInputSet.yaml"))) 

self.user_incar_settings = user_incar_settings or {} 

self.incar_settings.update(self.user_incar_settings) 

self.incar_settings.update({"IBRION": 6, "NFREE": 2, "POTIM": potim}) 

if "NPAR" in self.incar_settings: 

del self.incar_settings["NPAR"] 

 

 

def batch_write_vasp_input(structures, vasp_input_set, output_dir, 

make_dir_if_not_present=True, subfolder=None, 

sanitize=False, include_cif=False): 

""" 

Batch write vasp input for a sequence of structures to 

output_dir, following the format output_dir/{group}/{formula}_{number}. 

 

Args: 

structures ([Structure]): Sequence of Structures. 

vasp_input_set (VaspInputSet): VaspInputSet that creates 

vasp input files from structures 

output_dir (str): Directory to output files 

make_dir_if_not_present (bool): Create the directory if not present. 

Defaults to True. 

subfolder (callable): Function to create subdirectory name from 

structure. Defaults to simply "formula_count". 

sanitize (bool): Boolean indicating whether to sanitize the 

structure before writing the VASP input files. Sanitized output 

are generally easier for viewing and certain forms of analysis. 

Defaults to False. 

include_cif (bool): Whether to output a CIF as well. CIF files are 

generally better supported in visualization programs. 

""" 

for i, s in enumerate(structures): 

formula = re.sub("\s+", "", s.formula) 

if subfolder is not None: 

subdir = subfolder(s) 

dirname = os.path.join(output_dir, subdir) 

else: 

dirname = os.path.join(output_dir, '{}_{}'.format(formula, i)) 

if sanitize: 

s = s.copy(sanitize=True) 

vasp_input_set.write_input( 

s, dirname, make_dir_if_not_present=make_dir_if_not_present, 

include_cif=include_cif 

) 

 

 

class DerivedVaspInputSet(six.with_metaclass(abc.ABCMeta, MSONable)): 

""" 

Base class representing a set of DERIVED Vasp input parameters, 

which means that a previous run, including a structure is supplied as 

init parameters. The different with AbstractVaspInputSet is that these 

are simpler because a structure is not supplied to each of the abstract 

methods but is instead already provided. See examples below. 

""" 

 

@abc.abstractproperty 

def incar(self): 

"""Incar object""" 

pass 

 

@abc.abstractproperty 

def kpoints(self): 

"""Kpoints object""" 

pass 

 

@abc.abstractproperty 

def poscar(self): 

"""Poscar object""" 

pass 

 

@abc.abstractproperty 

def potcar(self): 

"""Potcar object""" 

pass 

 

def get_all_vasp_input(self): 

""" 

Returns all input files as a dict of {filename: vasp object} 

 

Returns: 

dict of {filename: file_as_string}, e.g., {'INCAR':'EDIFF=1e-4...'} 

""" 

return {'INCAR': self.incar, 

'KPOINTS': self.kpoints, 

'POSCAR': self.poscar, 

'POTCAR': self.potcar} 

 

def write_input(self, output_dir, 

make_dir_if_not_present=True, include_cif=False): 

""" 

Writes a set of VASP input to a directory. 

 

Args: 

output_dir (str): Directory to output the VASP input files 

make_dir_if_not_present (bool): Set to True if you want the 

directory (and the whole path) to be created if it is not 

present. 

include_cif (bool): Whether to write a CIF file in the output 

directory for easier opening by VESTA. 

""" 

if make_dir_if_not_present and not os.path.exists(output_dir): 

os.makedirs(output_dir) 

for k, v in self.get_all_vasp_input().items(): 

v.write_file(os.path.join(output_dir, k)) 

if k == "POSCAR" and include_cif: 

v.structure.to( 

filename=os.path.join(output_dir, 

"%s.cif" % v.structure.formula)) 

 

def as_dict(self): 

d = MSONable.as_dict(self) 

if hasattr(self, "kwargs"): 

d.update(**self.kwargs) 

return d 

 

@classmethod 

def from_dict(cls, d): 

decoded = {k: MontyDecoder().process_decoded(v) for k, v in d.items() 

if not k.startswith("@")} 

return cls(**decoded) 

 

 

class MPStaticSet(DerivedVaspInputSet): 

 

def __init__(self, structure, prev_incar=None, prev_kpoints=None, 

lepsilon=False, reciprocal_density=100, **kwargs): 

""" 

Init a MPStaticSet. Typically, you would use the classmethod 

from_prev_calc instead. 

 

Args: 

structure (Structure): Structure from previous run. 

prev_incar (Incar): Incar file from previous run. 

prev_kpoints (Kpoints): Kpoints from previous run. 

reciprocal_density (int): density of k-mesh by reciprocal 

volume (defaults to 100) 

\*\*kwargs: kwargs supported by MPVaspInputSet. 

""" 

 

self.prev_incar = prev_incar 

self.prev_kpoints = prev_kpoints 

self.reciprocal_density = reciprocal_density 

self.structure = structure 

self.kwargs = kwargs 

self.lepsilon = lepsilon 

self.parent_vis = MPVaspInputSet(**self.kwargs) 

 

@property 

def incar(self): 

 

parent_incar = self.parent_vis.get_incar(self.structure) 

incar = Incar(self.prev_incar) if self.prev_incar is not None else \ 

Incar(parent_incar) 

 

incar.update( 

{"IBRION": -1, "ISMEAR": -5, "LAECHG": True, "LCHARG": True, 

"LORBIT": 11, "LVHAR": True, "LWAVE": False, "NSW": 0, 

"ICHARG": 0, "ALGO": "Normal"}) 

 

if self.lepsilon: 

incar["IBRION"] = 8 

incar["LEPSILON"] = True 

# Note that DFPT calculations MUST unset NSW. NSW = 0 will fail 

# to output ionic. 

incar.pop("NSW", None) 

incar.pop("NPAR", None) 

 

for k in ["MAGMOM", "NUPDOWN"] + list(self.kwargs.get( 

"user_incar_settings", {}).keys()): 

# For these parameters as well as user specified settings, override 

# the incar settings. 

if parent_incar.get(k, None) is not None: 

incar[k] = parent_incar[k] 

else: 

incar.pop(k, None) 

 

# use new LDAUU when possible b/c the Poscar might have changed 

# representation 

if incar.get('LDAU'): 

u = incar.get('LDAUU', []) 

j = incar.get('LDAUJ', []) 

if sum([u[x] - j[x] for x, y in enumerate(u)]) > 0: 

for tag in ('LDAUU', 'LDAUL', 'LDAUJ'): 

incar.update({tag: parent_incar[tag]}) 

# ensure to have LMAXMIX for GGA+U static run 

if "LMAXMIX" not in incar: 

incar.update({"LMAXMIX": parent_incar["LMAXMIX"]}) 

 

# Compare ediff between previous and staticinputset values, 

# choose the tighter ediff 

incar["EDIFF"] = min(incar.get("EDIFF", 1), parent_incar["EDIFF"]) 

return incar 

 

@property 

def kpoints(self): 

if self.parent_vis.kpoints_settings.get("grid_density"): 

del self.parent_vis.kpoints_settings["grid_density"] 

self.parent_vis.kpoints_settings["reciprocal_density"] = \ 

self.reciprocal_density 

kpoints = self.parent_vis.get_kpoints(self.structure) 

 

# Prefer to use k-point scheme from previous run 

if self.prev_kpoints and self.prev_kpoints.style != kpoints.style: 

if self.prev_kpoints.style == Kpoints.supported_modes.Monkhorst: 

k_div = [kp + 1 if kp % 2 == 1 else kp 

for kp in kpoints.kpts[0]] 

kpoints = Kpoints.monkhorst_automatic(k_div) 

else: 

kpoints = Kpoints.gamma_automatic(kpoints.kpts[0]) 

return kpoints 

 

@property 

def poscar(self): 

return Poscar(self.structure) 

 

@property 

def potcar(self): 

return self.parent_vis.get_potcar(self.structure) 

 

@classmethod 

def from_prev_calc(cls, prev_calc_dir, standardize=False, sym_prec=0.1, 

international_monoclinic=True, reciprocal_density=100, 

small_gap_multiply=None, **kwargs): 

""" 

Generate a set of Vasp input files for static calculations from a 

directory of previous Vasp run. 

 

Args: 

prev_calc_dir (str): Directory containing the outputs( 

vasprun.xml and OUTCAR) of previous vasp run. 

standardize (float): Whether to standardize to a primitive 

standard cell. Defaults to False. 

sym_prec (float): Tolerance for symmetry finding. If not 0, 

the final structure from the previous run will be symmetrized 

to get a primitive standard cell. Set to 0 if you don't want 

that. 

international_monoclinic (bool): Whether to use international 

convention (vs Curtarolo) for monoclinic. Defaults True. 

reciprocal_density (int): density of k-mesh by reciprocal 

volume (defaults to 100) 

small_gap_multiply ([float, float]) - if the gap is less than 1st index, 

multiply the default reciprocal_density by the 2nd index 

\*\*kwargs: All kwargs supported by MPStaticSet, 

other than prev_incar and prev_structure and prev_kpoints which 

are determined from the prev_calc_dir. 

""" 

vasprun, outcar = get_vasprun_outcar(prev_calc_dir) 

 

prev_incar = vasprun.incar 

prev_kpoints = vasprun.kpoints 

 

# We will make a standard structure for the given symprec. 

prev_structure = get_structure_from_prev_run( 

vasprun, outcar, sym_prec=standardize and sym_prec, 

international_monoclinic=international_monoclinic) 

 

# multiply the reciprocal density if needed: 

if small_gap_multiply: 

gap = vasprun.eigenvalue_band_properties[0] 

if gap <= small_gap_multiply[0]: 

reciprocal_density = reciprocal_density * small_gap_multiply[1] 

 

return MPStaticSet( 

structure=prev_structure, prev_incar=prev_incar, 

prev_kpoints=prev_kpoints, 

reciprocal_density=reciprocal_density, **kwargs) 

 

 

class MPNonSCFSet(DerivedVaspInputSet): 

 

def __init__(self, structure, prev_incar=None, prev_chgcar=None, 

mode="line", nedos=601, reciprocal_density=100, sym_prec=0.1, 

kpoints_line_density=20, optics=False, **kwargs): 

""" 

Init a MPNonSCFSet. Typically, you would use the classmethod 

from_prev_calc instead. 

 

Args: 

prev_incar (Incar): Incar file from previous run. 

prev_structure (Structure): Structure from previous run. 

prev_chgcar (Chgcar): Chgcar from previous run. 

mode (str): Line or Uniform mode supported. 

nedos (int): nedos parameter. Default to 601. 

reciprocal_density (int): density of k-mesh by reciprocal 

volume (defaults to 100) 

sym_prec (float): Symmetry precision (for Uniform mode). 

kpoints_line_density (int): Line density for Line mode. 

\*\*kwargs: kwargs supported by MPVaspInputSet. 

""" 

self.structure = structure 

self.prev_incar = prev_incar 

self.prev_chgcar = prev_chgcar 

self.kwargs = kwargs 

 

self.nedos = nedos 

self.reciprocal_density = reciprocal_density 

self.sym_prec = sym_prec 

self.kpoints_line_density = kpoints_line_density 

self.optics = optics 

self.mode = mode.lower() 

 

if self.mode not in ["line", "uniform"]: 

raise ValueError("Supported modes for NonSCF runs are 'Line' and " 

"'Uniform'!") 

if (self.mode != "uniform" or nedos < 2000) and optics: 

warnings.warn("It is recommended to use Uniform mode with a high " 

"NEDOS for optics calculations.") 

 

self.parent_vis = MPVaspInputSet(**kwargs) 

 

 

@property 

def incar(self): 

incar = self.parent_vis.get_incar(self.structure) 

if self.prev_incar is not None: 

incar.update({k: v for k, v in self.prev_incar.items() 

if k not in self.kwargs.get("user_incar_settings", 

{})}) 

 

# Overwrite necessary INCAR parameters from previous runs 

incar.update({"IBRION": -1, "ISMEAR": 0, "SIGMA": 0.001, 

"LCHARG": False, "LORBIT": 11, "LWAVE": False, 

"NSW": 0, "ISYM": 0, "ICHARG": 11}) 

 

if self.mode == "uniform": 

# Set smaller steps for DOS output 

incar["NEDOS"] = self.nedos 

 

if self.optics: 

incar["LOPTICS"] = True 

 

incar.pop("MAGMOM", None) 

 

return incar 

 

@property 

def kpoints(self): 

if self.mode == "line": 

kpath = HighSymmKpath(self.structure) 

frac_k_points, k_points_labels = kpath.get_kpoints( 

line_density=self.kpoints_line_density, 

coords_are_cartesian=False) 

kpoints = Kpoints( 

comment="Non SCF run along symmetry lines", 

style=Kpoints.supported_modes.Reciprocal, 

num_kpts=len(frac_k_points), 

kpts=frac_k_points, labels=k_points_labels, 

kpts_weights=[1] * len(frac_k_points)) 

else: 

kpoints = Kpoints.automatic_density_by_vol(self.structure, 

self.reciprocal_density) 

mesh = kpoints.kpts[0] 

ir_kpts = SpacegroupAnalyzer( 

self.structure, 

symprec=self.sym_prec).get_ir_reciprocal_mesh(mesh) 

kpts = [] 

weights = [] 

for k in ir_kpts: 

kpts.append(k[0]) 

weights.append(int(k[1])) 

kpoints = Kpoints(comment="Non SCF run on uniform grid", 

style=Kpoints.supported_modes.Reciprocal, 

num_kpts=len(ir_kpts), 

kpts=kpts, kpts_weights=weights) 

return kpoints 

 

@property 

def poscar(self): 

return Poscar(self.structure) 

 

@property 

def potcar(self): 

return self.parent_vis.get_potcar(self.structure) 

 

def write_input(self, output_dir, 

make_dir_if_not_present=True, include_cif=False): 

super(MPNonSCFSet, self).write_input(output_dir, 

make_dir_if_not_present=make_dir_if_not_present, 

include_cif=include_cif) 

if self.prev_chgcar: 

self.prev_chgcar.write_file(os.path.join(output_dir, "CHGCAR")) 

 

@classmethod 

def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True, 

nbands_factor=1.2, standardize=False, sym_prec=0.1, 

international_monoclinic=True, reciprocal_density=100, 

small_gap_multiply=None, **kwargs): 

""" 

Generate a set of Vasp input files for NonSCF calculations from a 

directory of previous static Vasp run. 

 

Args: 

prev_calc_dir (str): The directory contains the outputs( 

vasprun.xml and OUTCAR) of previous vasp run. 

copy_chgcar: Whether to copy the old CHGCAR. Defaults to True. 

nbands_factor (float): Multiplicative factor for NBANDS. Choose a 

higher number if you are doing an LOPTICS calculation. 

standardize (float): Whether to standardize to a primitive 

standard cell. Defaults to False. 

sym_prec (float): Tolerance for symmetry finding. If not 0, 

the final structure from the previous run will be symmetrized 

to get a primitive standard cell. Set to 0 if you don't want 

that. 

international_monoclinic (bool): Whether to use international 

convention (vs Curtarolo) for monoclinic. Defaults True. 

reciprocal_density (int): density of k-mesh by reciprocal 

volume (defaults to 100) 

small_gap_multiply ([float, float]): If the gap is less than 

1st index, multiply the default reciprocal_density by the 2nd 

index. 

\*\*kwargs: All kwargs supported by MPNonSCFSet, 

other than structure, prev_incar and prev_chgcar which 

are determined from the prev_calc_dir. 

""" 

vasprun, outcar = get_vasprun_outcar(prev_calc_dir) 

 

incar = vasprun.incar 

# Get a Magmom-decorated structure 

structure = get_structure_from_prev_run( 

vasprun, outcar, sym_prec=standardize and sym_prec, 

international_monoclinic=international_monoclinic) 

# Turn off spin when magmom for every site is smaller than 0.02. 

if outcar and outcar.magnetization: 

site_magmom = np.array([i['tot'] for i in outcar.magnetization]) 

ispin = 2 if np.any(site_magmom[np.abs(site_magmom) > 0.02]) else 1 

elif vasprun.is_spin: 

ispin = 2 

else: 

ispin = 1 

nbands = int(np.ceil(vasprun.parameters["NBANDS"] * nbands_factor)) 

incar.update({"ISPIN": ispin, "NBANDS": nbands}) 

 

chgcar = None 

if copy_chgcar: 

chgcars = glob(os.path.join(prev_calc_dir, "CHGCAR*")) 

if len(chgcars) > 0: 

chgcar = Chgcar.from_file(sorted(chgcars)[-1]) 

 

# multiply the reciprocal density if needed: 

if small_gap_multiply: 

gap = vasprun.eigenvalue_band_properties[0] 

if gap <= small_gap_multiply[0]: 

reciprocal_density = reciprocal_density * small_gap_multiply[1] 

 

return MPNonSCFSet(structure=structure, prev_incar=incar, 

prev_chgcar=chgcar, 

reciprocal_density=reciprocal_density, **kwargs) 

 

 

class MPSOCSet(MPStaticSet): 

 

def __init__(self, structure, saxis=(0, 0, 1), prev_incar=None, 

prev_chgcar=None, reciprocal_density=100, **kwargs): 

""" 

Init a MPSOCSet. Typically, you would use the classmethod 

from_prev_calc instead. 

 

Args: 

structure (Structure): the structure must have the 'magmom' site 

property and each magnetic moment value must have 3 

components. eg:- magmom = [[0,0,2], ...] 

saxis (tuple): magnetic moment orientation 

prev_incar (Incar): Incar file from previous run. 

prev_chgcar (Chgcar): Chgcar from previous run. 

reciprocal_density (int): density of k-mesh by reciprocal 

volume (defaults to 100) 

\*\*kwargs: kwargs supported by MPVaspInputSet. 

""" 

if not hasattr(structure[0], "magmom") and \ 

not isinstance(structure[0].magmom, list): 

raise ValueError("The structure must have the 'magmom' site " 

"property and each magnetic moment value must have 3 " 

"components. eg:- magmom = [0,0,2]") 

self.saxis = saxis 

self.prev_chgcar = prev_chgcar 

super(MPSOCSet, self).__init__(structure, prev_incar=prev_incar, 

reciprocal_density=reciprocal_density, 

**kwargs) 

 

@property 

def incar(self): 

incar = self.parent_vis.get_incar(self.structure) 

if self.prev_incar is not None: 

incar.update({k: v for k, v in self.prev_incar.items() 

if k not in self.kwargs.get("user_incar_settings", 

{})}) 

 

# Overwrite necessary INCAR parameters from previous runs 

incar.update({"ISYM": -1, "LSORBIT": "T", "ICHARG": 11, 

"SAXIS": list(self.saxis)}) 

 

return incar 

 

def write_input(self, output_dir, 

make_dir_if_not_present=True, include_cif=False): 

super(MPSOCSet, self).write_input(output_dir, 

make_dir_if_not_present=make_dir_if_not_present, 

include_cif=include_cif) 

if self.prev_chgcar: 

self.prev_chgcar.write_file(os.path.join(output_dir, "CHGCAR")) 

 

@classmethod 

def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True, 

nbands_factor=1.2, standardize=False, sym_prec=0.1, 

international_monoclinic=True, reciprocal_density=100, 

small_gap_multiply=None, **kwargs): 

""" 

Generate a set of Vasp input files for SOC calculations from a 

directory of previous static Vasp run. SOC calc requires all 3 

components for MAGMOM for each atom in the structure. 

 

Args: 

prev_calc_dir (str): The directory contains the outputs( 

vasprun.xml and OUTCAR) of previous vasp run. 

copy_chgcar: Whether to copy the old CHGCAR. Defaults to True. 

nbands_factor (float): Multiplicative factor for NBANDS. Choose a 

higher number if you are doing an LOPTICS calculation. 

standardize (float): Whether to standardize to a primitive 

standard cell. Defaults to False. 

sym_prec (float): Tolerance for symmetry finding. If not 0, 

the final structure from the previous run will be symmetrized 

to get a primitive standard cell. Set to 0 if you don't want 

that. 

international_monoclinic (bool): Whether to use international 

convention (vs Curtarolo) for monoclinic. Defaults True. 

reciprocal_density (int): density of k-mesh by reciprocal 

volume (defaults to 100) 

small_gap_multiply ([float, float]): If the gap is less than 

1st index, multiply the default reciprocal_density by the 2nd 

index. 

\*\*kwargs: All kwargs supported by MPSOCSet, 

other than structure, prev_incar and prev_chgcar which 

are determined from the prev_calc_dir. 

""" 

vasprun, outcar = get_vasprun_outcar(prev_calc_dir) 

 

incar = vasprun.incar 

# Get a magmom-decorated structure 

structure = get_structure_from_prev_run( 

vasprun, outcar, sym_prec=standardize and sym_prec, 

international_monoclinic=international_monoclinic) 

# override magmom if provided 

if kwargs.get("magmom", None): 

structure = structure.copy( 

site_properties={"magmom": kwargs["magmom"]}) 

kwargs.pop("magmom", None) 

# magmom has to be 3D for SOC calculation. 

if hasattr(structure[0], "magmom"): 

if not isinstance(structure[0].magmom, list): 

structure = structure.copy(site_properties={ 

"magmom": [[0, 0, site.magmom] for site in structure]}) 

else: 

raise ValueError("Neither the previous structure has mamgom " 

"property nor magmom provided") 

 

nbands = int(np.ceil(vasprun.parameters["NBANDS"] * nbands_factor)) 

incar.update({"NBANDS": nbands}) 

 

chgcar = None 

if copy_chgcar: 

chgcars = glob(os.path.join(prev_calc_dir, "CHGCAR*")) 

if len(chgcars) > 0: 

chgcar = Chgcar.from_file(sorted(chgcars)[-1]) 

 

# multiply the reciprocal density if needed: 

if small_gap_multiply: 

gap = vasprun.eigenvalue_band_properties[0] 

if gap <= small_gap_multiply[0]: 

reciprocal_density = reciprocal_density * small_gap_multiply[1] 

 

return MPSOCSet(structure, prev_incar=incar, 

prev_chgcar=chgcar, 

reciprocal_density=reciprocal_density, **kwargs) 

 

 

class MVLSlabSet(DictVaspInputSet): 

""" 

Class for writing a set of slab vasp runs, 

including both slabs (along the c direction) and orient unit cells (bulk), 

to ensure the same KPOINTS, POTCAR and INCAR criterion. 

 

Args: 

user_incar_settings(dict): A dict specifying additional incar 

settings, default to None, ediff_per_atom=False 

k_product: default to 50, kpoint number * length for a & b directions, 

also for c direction in bulk calculations 

potcar_functional: default to PBE 

bulk (bool): Set to True for bulk calculation. Defaults to False. 

**kwargs: 

Other kwargs supported by :class:`DictVaspInputSet`. 

""" 

def __init__(self, user_incar_settings=None, gpu=False, k_product=50, 

potcar_functional='PBE', bulk=False, **kwargs): 

 

user_incar_settings = user_incar_settings or {} 

vis = MPVaspInputSet(ediff_per_atom=False).as_dict() 

DictVaspInputSet.__init__(self, "MVLSlabSet", 

vis["config_dict"], 

**kwargs) 

incar_settings_basic = { 

"EDIFF": 1e-6, "EDIFFG": -0.01, "ENCUT": 400, 

"ISMEAR": 0, "SIGMA": 0.05, "ISIF": 3} 

 

if bulk: 

self.incar_settings.update(incar_settings_basic) 

else: 

incar_settings_basic["ISIF"] = 2 

incar_settings_basic["AMIN"] = 0.01 

incar_settings_basic["AMIX"] = 0.2 

incar_settings_basic["BMIX"] = 0.001 

incar_settings_basic["NELMIN"] = 8 

self.incar_settings.update(incar_settings_basic) 

 

if gpu: 

# Sets KPAR to allow for the use of VASP-gpu 

if "KPAR" not in user_incar_settings.keys(): 

# KPAR setting of 1 is the safest setting, 

# but for optimal performance, we normally 

# use the square root of the number of KPOINTS 

self.incar_settings["KPAR"] = 1 

if "NPAR" in self.incar_settings.keys(): 

del self.incar_settings["NPAR"] 

 

 

if user_incar_settings: 

self.incar_settings.update(user_incar_settings) 

 

self.user_incar_settings = user_incar_settings 

self.k_product = k_product 

self.potcar_functional = potcar_functional 

self.bulk = bulk 

 

def get_kpoints(self, structure): 

""" 

k_product, default to 50, is kpoint number * length for a & b directions, 

also for c direction in bulk calculations 

Automatic mesh & Gamma is the default setting. 

""" 

 

# To get input sets, the input structure has to has the same number 

# of required parameters as a Structure object (ie. 4). Slab 

# attributes aren't going to affect the VASP inputs anyways so 

# converting the slab into a structure should not matter 

 

kpt = super(MVLSlabSet, self).get_kpoints(structure) 

kpt.comment = "Automatic mesh" 

kpt.style = 'Gamma' 

 

# use k_product to calculate kpoints, k_product = kpts[0][0] * a 

abc = structure.lattice.abc 

kpt_calc = [int(self.k_product/abc[0]+0.5), 

int(self.k_product/abc[1]+0.5), 1] 

self.kpt_calc = kpt_calc 

# calculate kpts (c direction) for bulk. (for slab, set to 1) 

if self.bulk: 

kpt_calc[2] = int(self.k_product/abc[2]+0.5) 

 

kpt.kpts[0] = kpt_calc 

 

return kpt 

 

def get_incar(self, structure): 

 

# To get input sets, the input structure has to has the same number 

# of required parameters as a Structure object (ie. 4). Slab 

# attributes aren't going to affect the VASP inputs anyways so 

# converting the slab into a structure should not matter 

 

abc = structure.lattice.abc 

kpt_calc = [int(self.k_product/abc[0]+0.5), 

int(self.k_product/abc[1]+0.5), 

int(self.k_product/abc[1]+0.5)] 

 

 

kpts = kpt_calc 

 

if kpts[0]<5 and kpts[1]<5: 

if not self.bulk: 

self.incar_settings.update( 

{"ISMEAR": 0}) 

else: 

if kpts[2]<5: 

self.incar_settings.update( 

{"ISMEAR": 0}) 

if self.user_incar_settings: 

self.incar_settings.update(self.user_incar_settings) 

 

incr = super(MVLSlabSet, self).get_incar(structure) 

 

return incr 

 

def as_dict(self): 

d = super(MVLSlabSet, self).as_dict() 

d.update({ 

"potcar_functional": self.potcar_functional, 

"user_incar_settings": self.user_incar_settings 

}) 

return d 

 

def from_dict(cls, d): 

return cls( 

user_incar_settings=d.get("user_incar_settings", None), 

potcar_functional=d.get("potcar_functional", None)) 

 

def get_all_vasp_input(self, structure): 

""" 

Returns all input files as a dict of {filename: vaspio object} 

 

Args: 

structure (Structure/IStructure): Structure to generate vasp 

input for. 

Returns: 

dict of {filename: file_as_string}, e.g., {'INCAR':'EDIFF=1e-4...'} 

""" 

 

# To get input sets, the input structure has to has the same number 

# of required parameters as a Structure object (ie. 4). Slab 

# attributes aren't going to affect the VASP inputs anyways so 

# converting the slab into a structure should not matter 

 

data = {'INCAR': self.get_incar(structure), 

'KPOINTS': self.get_kpoints(structure), 

'POSCAR': self.get_poscar(structure), 

'POTCAR': self.get_potcar(structure)} 

return data 

 

 

def get_vasprun_outcar(path): 

vruns = glob(os.path.join(path, "vasprun.xml*")) 

outcars = glob(os.path.join(path, "OUTCAR*")) 

 

if len(vruns) == 0 or len(outcars) == 0: 

raise ValueError( 

"Unable to get vasprun.xml/OUTCAR from prev calculation in %s" % 

path) 

vsfile_fullpath = os.path.join(path, "vasprun.xml") 

outcarfile_fullpath = os.path.join(path, "OUTCAR") 

vsfile = vsfile_fullpath if vsfile_fullpath in vruns else sorted(vruns)[-1] 

outcarfile = outcarfile_fullpath if outcarfile_fullpath in outcars else sorted(outcars)[-1] 

return Vasprun(vsfile, parse_dos=False, parse_eigen=None), Outcar( 

outcarfile) 

 

 

def get_structure_from_prev_run(vasprun, outcar=None, sym_prec=0.1, 

international_monoclinic=True): 

""" 

Process structure from previous run. 

 

Args: 

vasp_run (Vasprun): Vasprun that contains the final structure 

from previous run. 

outcar (Outcar): Outcar that contains the magnetization info from 

previous run. 

sym_prec (float): Tolerance for symmetry finding for standardization. If 

no standardization is desired, set to 0 or a False. 

international_monoclinic (bool): Whether to use international 

convention (vs Curtarolo) for monoclinic. Defaults True. 

 

Returns: 

Returns the magmom-decorated structure that can be passed to get 

Vasp input files, e.g. get_kpoints. 

""" 

structure = vasprun.final_structure 

 

site_properties = {} 

# magmom 

if vasprun.is_spin: 

if outcar and outcar.magnetization: 

site_properties.update({"magmom": [i['tot'] 

for i in outcar.magnetization]}) 

else: 

site_properties.update({"magmom": vasprun.parameters['MAGMOM']}) 

# ldau 

if vasprun.parameters.get("LDAU", False): 

for k in ("LDAUU", "LDAUJ", "LDAUL"): 

vals = vasprun.incar[k] 

m = {} 

l = [] 

m[structure[0].specie.symbol] = vals.pop(0) 

for site in structure: 

if site.specie.symbol not in m: 

m[site.specie.symbol] = vals.pop(0) 

l.append(m[site.specie.symbol]) 

if len(l) == len(structure): 

site_properties.update({k.lower(): l}) 

else: 

raise ValueError("length of list {} not the same as" 

"structure".format(l)) 

 

structure = structure.copy(site_properties=site_properties) 

 

if sym_prec: 

sym_finder = SpacegroupAnalyzer(structure, symprec=sym_prec) 

new_structure = sym_finder.get_primitive_standard_structure( 

international_monoclinic=international_monoclinic) 

# the primitive structure finding has had several bugs in the past 

# defend through validation 

vpa_old = structure.volume / structure.num_sites 

vpa_new = new_structure.volume / new_structure.num_sites 

if abs(vpa_old - vpa_new) / vpa_old > 0.02: 

raise ValueError( 

"Standardizing cell failed! VPA old: {}, VPA new: {}".format( 

vpa_old, vpa_new)) 

sm = StructureMatcher() 

if not sm.fit(structure, new_structure): 

raise ValueError( 

"Standardizing cell failed! Old structure doesn't match new.") 

structure = new_structure 

 

return structure