Skip to content

Instantly share code, notes, and snippets.

@computron
Last active March 20, 2025 06:10
Show Gist options
  • Save computron/7efcf5668e8694c1c881e35a23c8f67f to your computer and use it in GitHub Desktop.
Save computron/7efcf5668e8694c1c881e35a23c8f67f to your computer and use it in GitHub Desktop.
Export phonon band structure data from the Materials Project API. Related video tutorial on phonons: https://youtu.be/acT6zQbiiio
"""
Export phonon band structure data from the Materials Project API for visualization on the phonons web site (https://henriquemiranda.github.io/phononwebsite/phonon.html).
Author: Anubhav Jain (https://github.com/computron)
Related video tutorial on phonons: https://youtu.be/acT6zQbiiio
## Setup Instructions:
1. **Obtain an API Key:**
- Register for an account at the Materials Project: https://materialsproject.org
- Generate an API key from your account settings: https://materialsproject.org/api
2. **Set Up Your API Key:**
- Option 1: Set the api_key below in this script by replacing `YOUR_API_KEY_HERE`.
- Option 2: Configure the api_key via environment variable or configuration file and set the api_key to None.
3. Install the mp-api library (``pip install mp-api``)
4. If you need additional instructions, see this video: https://youtu.be/e4hSkv1Ghbk
## Usage:
- Replace `material_id` with the Materials Project ID of the desired material.
- Run this script to save the phonon band structure data as a JSON file.
- The JSON file can be loaded into the phonon visualizer from Henrique Miranda: https://henriquemiranda.github.io/phononwebsite/phonon.html
"""
import json
from mp_api.client import MPRester
# Setup: replace your API key here
# (either paste your API key string or use None if you've already set an environment variable or configured a .pmgrc.yaml file)
api_key = "YOUR_API_KEY"
# Setup: select the material ID to fetch data for
material_id = "mp-10760"
# Setup (optional): choose the output file path and name
output_fname = f"{material_id}-phonondata.json"
# Execute: fetch phonon data
try:
with MPRester(api_key) as mpr:
phonon_docs = mpr.materials.phonon.search(material_ids=[material_id])
if not phonon_docs:
raise ValueError(f"No phonon data found for material ID: {material_id}")
phonon_bs = phonon_docs[0].ph_bs # Extract phonon band structure
phonon_dict = phonon_bs.as_phononwebsite()
# Save to file
with open(output_fname, "w") as json_file:
json.dump(phonon_dict, json_file, indent=4)
print(f"Phonon data successfully saved to {output_fname}")
except Exception as e:
print(f"Error fetching phonon data: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment