0
# Loading and File Operations
1
2
Load phonopy calculations from various file formats and manage input/output operations with different ab initio calculation codes. Phonopy provides comprehensive file I/O capabilities for seamless integration with multiple quantum mechanical calculators and data persistence.
3
4
## Capabilities
5
6
### Main Load Function
7
8
Create Phonopy instances from configuration files and calculation parameters.
9
10
```python { .api }
11
def load(
12
phonopy_yaml: str | os.PathLike | io.IOBase | None = None,
13
supercell_matrix: ArrayLike | None = None,
14
primitive_matrix: ArrayLike | str | None = None,
15
is_nac: bool = True,
16
calculator: str | None = None,
17
unitcell: PhonopyAtoms | None = None,
18
supercell: PhonopyAtoms | None = None,
19
nac_params: dict | None = None,
20
unitcell_filename: os.PathLike | str | None = None,
21
supercell_filename: os.PathLike | str | None = None,
22
born_filename: os.PathLike | str | None = None,
23
force_sets_filename: os.PathLike | str | None = None,
24
force_constants_filename: os.PathLike | str | None = None,
25
fc_calculator: Literal["traditional", "symfc", "alm"] | None = None,
26
fc_calculator_options: str | None = None,
27
factor: float | None = None,
28
produce_fc: bool = True,
29
is_symmetry: bool = True,
30
symmetrize_fc: bool = True,
31
is_compact_fc: bool = True,
32
use_pypolymlp: bool = False,
33
mlp_params: dict | None = None,
34
store_dense_svecs: bool = True,
35
use_SNF_supercell: bool = False,
36
symprec: float = 1e-5,
37
log_level: int = 0
38
) -> Phonopy:
39
"""
40
Create Phonopy instance from parameters and/or input files.
41
42
Parameters:
43
- phonopy_yaml: phonopy.yaml-like file path, file object, or None
44
- supercell_matrix: Supercell transformation matrix or [nx, ny, nz]
45
- primitive_matrix: Primitive transformation matrix or string ('auto', 'F', etc.)
46
- is_nac: Whether to use non-analytical correction parameters
47
- calculator: Calculator interface ('vasp', 'qe', 'abinit', 'aims', etc.)
48
- unitcell: Unit cell structure as PhonopyAtoms object
49
- supercell: Supercell structure as PhonopyAtoms object
50
- nac_params: Non-analytical correction parameters dictionary
51
- unitcell_filename: Path to unit cell structure file
52
- supercell_filename: Path to supercell structure file
53
- born_filename: Path to Born effective charge file
54
- force_sets_filename: Path to force sets file (FORCE_SETS)
55
- force_constants_filename: Path to force constants file
56
- fc_calculator: Force constants calculator ('traditional', 'symfc', 'alm')
57
- fc_calculator_options: Additional options for force constants calculator
58
- factor: Unit conversion factor (deprecated)
59
- produce_fc: Whether to produce force constants from forces
60
- is_symmetry: Whether to use crystal symmetry
61
- symmetrize_fc: Force symmetrization of force constants (default: True)
62
- is_compact_fc: Use compact force constants format (default: True)
63
- use_pypolymlp: Use PyPolyMLP for machine learning potential (default: False)
64
- mlp_params: Machine learning potential parameters dictionary
65
- store_dense_svecs: Store shortest vectors in dense format (default: True)
66
- use_SNF_supercell: Use SNF algorithm for supercell building (default: False)
67
- symprec: Symmetry precision tolerance
68
- log_level: Logging verbosity level
69
70
Returns:
71
Configured Phonopy instance ready for calculations
72
"""
73
```
74
75
**Examples:**
76
77
```python
78
from phonopy import load
79
80
# Load from phonopy.yaml file (most common)
81
ph = load("phonopy.yaml")
82
83
# Load with specific calculator interface
84
ph = load("phonopy.yaml", calculator="vasp")
85
86
# Load from separate files
87
ph = load(
88
unitcell_filename="POSCAR",
89
force_sets_filename="FORCE_SETS",
90
supercell_matrix=[2, 2, 2],
91
calculator="vasp"
92
)
93
94
# Load with force constants instead of force sets
95
ph = load(
96
unitcell_filename="POSCAR",
97
force_constants_filename="FORCE_CONSTANTS",
98
supercell_matrix=[2, 2, 2]
99
)
100
101
# Load without producing force constants
102
ph = load(
103
phonopy_yaml="phonopy.yaml",
104
produce_fc=False, # Keep displacement dataset only
105
log_level=1
106
)
107
```
108
109
### PhonopyYaml File Operations
110
111
Handle phonopy.yaml configuration files for persistent storage.
112
113
```python { .api }
114
class PhonopyYaml:
115
def __init__(
116
self,
117
filename: str | PathLike | IOBase = None,
118
configuration: dict = None
119
):
120
"""
121
Initialize PhonopyYaml for reading/writing phonopy configuration.
122
123
Parameters:
124
- filename: Path to phonopy.yaml file or file object
125
- configuration: Dictionary with phonopy configuration data
126
"""
127
128
def read(self, filename: str | PathLike | IOBase):
129
"""
130
Read phonopy configuration from YAML file.
131
132
Parameters:
133
- filename: Path to phonopy.yaml file or file object
134
"""
135
136
def write(self, filename: str | PathLike = None):
137
"""
138
Write phonopy configuration to YAML file.
139
140
Parameters:
141
- filename: Output file path (default: same as input)
142
"""
143
144
@property
145
def unitcell(self) -> PhonopyAtoms:
146
"""Get unit cell structure."""
147
148
@property
149
def supercell_matrix(self) -> ndarray:
150
"""Get supercell transformation matrix."""
151
152
@property
153
def primitive_matrix(self) -> ndarray:
154
"""Get primitive transformation matrix."""
155
156
@property
157
def dataset(self) -> dict:
158
"""Get displacement dataset."""
159
160
@property
161
def force_constants(self) -> ndarray:
162
"""Get force constants matrix."""
163
164
@property
165
def nac_params(self) -> dict:
166
"""Get non-analytical correction parameters."""
167
168
@property
169
def calculator(self) -> str:
170
"""Get calculator interface name."""
171
172
def set_phonon_info(self, phonopy: Phonopy):
173
"""
174
Set phonopy information from Phonopy instance.
175
176
Parameters:
177
- phonopy: Phonopy instance to extract information from
178
"""
179
```
180
181
**Example:**
182
183
```python
184
from phonopy.interface.phonopy_yaml import PhonopyYaml
185
186
# Read existing phonopy.yaml
187
ph_yaml = PhonopyYaml("phonopy.yaml")
188
unitcell = ph_yaml.unitcell
189
supercell_matrix = ph_yaml.supercell_matrix
190
force_constants = ph_yaml.force_constants
191
192
print(f"Calculator: {ph_yaml.calculator}")
193
print(f"Supercell matrix: {supercell_matrix}")
194
195
# Create PhonopyYaml from Phonopy instance
196
ph = Phonopy(unitcell, supercell_matrix)
197
# ... perform calculations ...
198
199
ph_yaml_new = PhonopyYaml()
200
ph_yaml_new.set_phonon_info(ph)
201
ph_yaml_new.write("new_phonopy.yaml")
202
203
# Modify existing configuration
204
ph_yaml.read("phonopy.yaml")
205
# Modify parameters as needed
206
ph_yaml.write("modified_phonopy.yaml")
207
```
208
209
### Calculator Interface Functions
210
211
Load structures and data from various quantum mechanical calculators.
212
213
```python { .api }
214
# VASP Interface
215
def read_vasp(filename: str | PathLike) -> PhonopyAtoms:
216
"""
217
Read VASP POSCAR/CONTCAR file.
218
219
Parameters:
220
- filename: Path to VASP structure file
221
222
Returns:
223
PhonopyAtoms object with structure
224
"""
225
226
def read_vasp_from_strings(strings: list) -> PhonopyAtoms:
227
"""Read VASP structure from list of strings."""
228
229
def write_vasp(filename: str, cell: PhonopyAtoms, direct: bool = True):
230
"""
231
Write structure to VASP POSCAR format.
232
233
Parameters:
234
- filename: Output file path
235
- cell: Structure to write
236
- direct: Use direct (fractional) coordinates
237
"""
238
239
# Quantum ESPRESSO Interface
240
def read_crystal_structure(
241
filename: str | PathLike,
242
interface_mode: str = None
243
) -> PhonopyAtoms:
244
"""
245
Read crystal structure from Quantum ESPRESSO input file.
246
247
Parameters:
248
- filename: Path to QE input file
249
- interface_mode: Specific QE input format
250
251
Returns:
252
PhonopyAtoms object with structure
253
"""
254
255
def write_pwscf(filename: str, cell: PhonopyAtoms, **kwargs):
256
"""Write structure to Quantum ESPRESSO pw.x input format."""
257
258
# CRYSTAL Interface
259
def read_crystal(filename: str | PathLike) -> PhonopyAtoms:
260
"""Read CRYSTAL structure file."""
261
262
def write_crystal(filename: str, cell: PhonopyAtoms):
263
"""Write structure to CRYSTAL format."""
264
265
# ABINIT Interface
266
def read_abinit(filename: str | PathLike) -> PhonopyAtoms:
267
"""Read ABINIT structure file."""
268
269
def write_abinit(filename: str, cell: PhonopyAtoms):
270
"""Write structure to ABINIT format."""
271
```
272
273
**Examples:**
274
275
```python
276
from phonopy.interface.vasp import read_vasp, write_vasp
277
from phonopy.interface.qe import read_crystal_structure, write_pwscf
278
from phonopy.interface.crystal import read_crystal
279
280
# Read from different calculator formats
281
vasp_structure = read_vasp("POSCAR")
282
qe_structure = read_crystal_structure("pw.in")
283
crystal_structure = read_crystal("crystal.d12")
284
285
# Write to different formats
286
write_vasp("POSCAR_out", vasp_structure)
287
write_pwscf("pw_out.in", vasp_structure)
288
```
289
290
### Force Sets and Force Constants
291
292
Handle force data from ab initio calculations.
293
294
```python { .api }
295
def create_FORCE_SETS(
296
disp_dataset: dict,
297
forces_filenames: list = None,
298
calculator: str = None,
299
log_level: int = 0
300
):
301
"""
302
Create FORCE_SETS file from displacement dataset and force files.
303
304
Parameters:
305
- disp_dataset: Displacement dataset dictionary
306
- forces_filenames: List of force output files from calculator
307
- calculator: Calculator interface for parsing forces
308
- log_level: Logging verbosity
309
"""
310
311
def parse_FORCE_SETS(filename: str = "FORCE_SETS") -> dict:
312
"""
313
Parse FORCE_SETS file.
314
315
Parameters:
316
- filename: Path to FORCE_SETS file
317
318
Returns:
319
Dictionary with displacement dataset and forces
320
"""
321
322
def write_FORCE_SETS(dataset: dict, filename: str = "FORCE_SETS"):
323
"""
324
Write displacement dataset to FORCE_SETS file.
325
326
Parameters:
327
- dataset: Displacement dataset dictionary
328
- filename: Output file path
329
"""
330
331
def parse_FORCE_CONSTANTS(filename: str) -> ndarray:
332
"""
333
Parse force constants from file.
334
335
Parameters:
336
- filename: Path to force constants file
337
338
Returns:
339
Force constants matrix
340
"""
341
342
def write_FORCE_CONSTANTS(
343
force_constants: ArrayLike,
344
filename: str = "FORCE_CONSTANTS"
345
):
346
"""
347
Write force constants to file.
348
349
Parameters:
350
- force_constants: Force constants matrix
351
- filename: Output file path
352
"""
353
```
354
355
**Examples:**
356
357
```python
358
from phonopy.cui.create_force_sets import create_FORCE_SETS
359
from phonopy.file_IO import (parse_FORCE_SETS, write_FORCE_SETS,
360
parse_FORCE_CONSTANTS, write_FORCE_CONSTANTS)
361
362
# Create FORCE_SETS from VASP calculations
363
disp_dataset = {'natom': 8, 'first_atoms': [...]}
364
force_files = ['vasprun-001.xml', 'vasprun-002.xml', 'vasprun-003.xml']
365
366
create_FORCE_SETS(
367
disp_dataset=disp_dataset,
368
forces_filenames=force_files,
369
calculator="vasp"
370
)
371
372
# Read existing FORCE_SETS
373
dataset = parse_FORCE_SETS("FORCE_SETS")
374
forces = dataset['forces']
375
displacements = dataset['displacements']
376
377
# Read/write force constants
378
fc_matrix = parse_FORCE_CONSTANTS("FORCE_CONSTANTS")
379
write_FORCE_CONSTANTS(fc_matrix, "FORCE_CONSTANTS_new")
380
```
381
382
### Born Effective Charges and NAC
383
384
Handle non-analytical correction parameters for polar materials.
385
386
```python { .api }
387
def parse_BORN(filename: str) -> dict:
388
"""
389
Parse Born effective charges file.
390
391
Parameters:
392
- filename: Path to BORN file
393
394
Returns:
395
Dictionary with Born charges and dielectric tensor
396
"""
397
398
def write_BORN(
399
nac_params: dict,
400
filename: str = "BORN",
401
factor: float = None
402
):
403
"""
404
Write Born effective charges to file.
405
406
Parameters:
407
- nac_params: Non-analytical correction parameters
408
- filename: Output file path
409
- factor: Unit conversion factor
410
"""
411
412
def get_born_VASP(
413
vasprun_xml: str = "vasprun.xml",
414
outcar: str = "OUTCAR"
415
) -> dict:
416
"""
417
Extract Born charges from VASP output files.
418
419
Parameters:
420
- vasprun_xml: Path to vasprun.xml file
421
- outcar: Path to OUTCAR file
422
423
Returns:
424
NAC parameters dictionary
425
"""
426
427
def get_born_QE(
428
ph_out: str,
429
dynmat_files: list = None
430
) -> dict:
431
"""
432
Extract Born charges from Quantum ESPRESSO output.
433
434
Parameters:
435
- ph_out: Path to ph.x output file
436
- dynmat_files: List of dynmat files
437
438
Returns:
439
NAC parameters dictionary
440
"""
441
```
442
443
**Examples:**
444
445
```python
446
from phonopy.interface.vasp import get_born_VASP
447
from phonopy.interface.qe import get_born_QE
448
from phonopy.file_IO import parse_BORN, write_BORN
449
450
# Extract Born charges from VASP
451
nac_params_vasp = get_born_VASP("vasprun.xml", "OUTCAR")
452
453
# Extract from Quantum ESPRESSO
454
nac_params_qe = get_born_QE("ph.out")
455
456
# Read/write BORN files
457
nac_params = parse_BORN("BORN")
458
write_BORN(nac_params, "BORN_new")
459
460
# Apply to phonopy calculation
461
ph = load("phonopy.yaml")
462
ph.nac_params = nac_params
463
```
464
465
### Machine Learning Potential Integration
466
467
Interface with machine learning potentials for large-scale phonon calculations.
468
469
```python { .api }
470
class PhonopyMLP:
471
"""Machine learning potential interface for phonopy."""
472
473
def __init__(self, mlp_params: dict = None):
474
"""
475
Initialize MLP interface.
476
477
Parameters:
478
- mlp_params: Machine learning potential parameters
479
"""
480
481
def generate_force_constants(
482
self,
483
phonopy: Phonopy,
484
mlp_dataset: dict = None
485
) -> ndarray:
486
"""
487
Generate force constants using machine learning potential.
488
489
Parameters:
490
- phonopy: Phonopy instance
491
- mlp_dataset: MLP training dataset
492
493
Returns:
494
Force constants matrix
495
"""
496
497
class PypolymlpParams:
498
"""PyPolyMLP parameters interface."""
499
500
def __init__(self, params: dict = None):
501
"""Initialize PyPolyMLP parameters."""
502
503
def write(self, filename: str = "polymlp.in"):
504
"""Write parameters to file."""
505
506
def read(self, filename: str = "polymlp.in"):
507
"""Read parameters from file."""
508
```
509
510
### File Format Conversions
511
512
Convert between different file formats and calculator interfaces.
513
514
```python { .api }
515
def convert_crystal_structure(
516
input_filename: str,
517
output_filename: str,
518
input_format: str,
519
output_format: str
520
):
521
"""
522
Convert crystal structure between different formats.
523
524
Parameters:
525
- input_filename: Input structure file
526
- output_filename: Output structure file
527
- input_format: Input format ('vasp', 'qe', 'cif', etc.)
528
- output_format: Output format ('vasp', 'qe', 'cif', etc.)
529
"""
530
531
def get_calculator_physical_units(calculator: str) -> dict:
532
"""
533
Get physical unit conversion factors for calculator.
534
535
Parameters:
536
- calculator: Calculator name ('vasp', 'qe', etc.)
537
538
Returns:
539
Dictionary with unit conversion factors
540
"""
541
```
542
543
## Complete Loading Workflow Examples
544
545
### Standard Workflow with VASP
546
547
```python
548
from phonopy import load
549
from phonopy.interface.vasp import get_born_VASP
550
551
# 1. Load phonopy calculation
552
ph = load(
553
unitcell_filename="POSCAR",
554
supercell_matrix=[2, 2, 2],
555
primitive_matrix="auto",
556
force_sets_filename="FORCE_SETS",
557
calculator="vasp",
558
is_nac=True
559
)
560
561
# 2. Add Born effective charges (for polar materials)
562
nac_params = get_born_VASP("vasprun.xml", "OUTCAR")
563
ph.nac_params = nac_params
564
565
# 3. Perform calculations
566
ph.run_mesh([20, 20, 20])
567
ph.run_thermal_properties()
568
569
# 4. Save results
570
ph.save("phonopy_params.yaml")
571
```
572
573
### Loading from phonopy.yaml
574
575
```python
576
from phonopy import load
577
578
# Load complete calculation from phonopy.yaml
579
ph = load("phonopy.yaml")
580
581
# Check what's loaded
582
print(f"Calculator: {ph.calculator}")
583
print(f"Has force constants: {ph.force_constants is not None}")
584
print(f"Has NAC parameters: {ph.nac_params is not None}")
585
print(f"Supercell matrix: {ph.supercell_matrix}")
586
587
# Continue with analysis
588
if ph.force_constants is not None:
589
ph.run_band_structure_auto()
590
ph.run_mesh([20, 20, 20])
591
ph.run_thermal_properties()
592
```
593
594
### Multi-Calculator Workflow
595
596
```python
597
from phonopy import load
598
from phonopy.interface.vasp import read_vasp
599
from phonopy.interface.qe import get_born_QE
600
601
# Load structure from VASP
602
unitcell = read_vasp("POSCAR")
603
604
# Load forces from Quantum ESPRESSO calculation
605
ph = load(
606
unitcell=unitcell,
607
supercell_matrix=[2, 2, 2],
608
force_sets_filename="FORCE_SETS_QE",
609
calculator="qe"
610
)
611
612
# Add Born charges from QE
613
nac_params = get_born_QE("ph.out")
614
ph.nac_params = nac_params
615
616
# Complete workflow
617
ph.produce_force_constants()
618
ph.run_thermal_properties()
619
```
620
621
### Incremental Loading and Saving
622
623
```python
624
from phonopy import Phonopy, load
625
from phonopy.interface.phonopy_yaml import PhonopyYaml
626
627
# Start with minimal setup
628
ph = Phonopy(unitcell, supercell_matrix=[2, 2, 2])
629
630
# Generate displacements and save
631
ph.generate_displacements(distance=0.01)
632
ph.save("step1_displacements.yaml")
633
634
# After DFT calculations, load and add forces
635
ph = load("step1_displacements.yaml")
636
ph.forces = forces_from_dft
637
ph.produce_force_constants()
638
ph.save("step2_force_constants.yaml")
639
640
# Load for analysis
641
ph = load("step2_force_constants.yaml")
642
ph.run_mesh([20, 20, 20])
643
ph.run_thermal_properties()
644
ph.save("step3_final_results.yaml")
645
646
# Extract specific data using PhonopyYaml
647
ph_yaml = PhonopyYaml("step3_final_results.yaml")
648
thermal_props = ph_yaml.dataset.get('thermal_properties', {})
649
```
650
651
### Error Handling and Validation
652
653
```python
654
from phonopy import load
655
import os
656
657
def safe_load_phonopy(yaml_file, fallback_files=None):
658
"""Safely load phonopy with fallback options."""
659
660
try:
661
# Try loading from yaml first
662
if os.path.exists(yaml_file):
663
ph = load(yaml_file)
664
return ph
665
except Exception as e:
666
print(f"Failed to load {yaml_file}: {e}")
667
668
# Try fallback files
669
if fallback_files:
670
try:
671
ph = load(**fallback_files)
672
return ph
673
except Exception as e:
674
print(f"Failed to load from fallback: {e}")
675
676
return None
677
678
# Usage with fallbacks
679
ph = safe_load_phonopy(
680
yaml_file="phonopy.yaml",
681
fallback_files={
682
'unitcell_filename': "POSCAR",
683
'force_sets_filename': "FORCE_SETS",
684
'supercell_matrix': [2, 2, 2],
685
'calculator': 'vasp'
686
}
687
)
688
689
if ph is not None:
690
print("Successfully loaded phonopy calculation")
691
# Continue with analysis
692
else:
693
print("Failed to load phonopy calculation")
694
```