How can i download the chgcar file for multiples mp_ids and convert them into individual npy files?

mp_ids=['mp-1','mp-42'] # the mp_id list

with MPRester(MP_API_KEY) as mpr:
    chgcars = mpr.get_charge_density_from_material_id(mp_ids) # avoiding looping the mp_id list

the above code works fine ,but how can i get the chgcar file for ‘mp-1’ and ‘mp-42’ individually?

Hi @bigtom4coding ,

The get_charge_density_from_material_id function isn’t actually intended to be used with multiple MPIDs input as a list, it’s meant to get a single CHGCAR entry for a given MPID. If you look at the structure attribute of the CHGCAR you pull from MP, it will only be one entry (whichever is newer). That’s a bug (I think).

That being said, if you want to pull CHGCARs from MP and save them either as gzipped JSON (maybe more natural for pymatgen objects) or as numpy arrays, here’s how you can do it.

Try to avoid doing this with many MPIDs (let’s say more than ~50). If you need more CHGCAR data on MP, it might be best to reach out directly to @tschaume or @munrojm.

from mp_api.client import MPRester
import numpy as np


mpids = ["mp-1","mp-42"]
with MPRester() as mpr:
    for mpid in mpids:
        # not recommended for many MPIDs
        chgcars = mpr.get_charge_density_from_material_id(mpid)

        # Saving as gzipped JSON
        chgcars.save(f"chgcar_{mpid}.json.gz")
        
        # Saving as numpy array
        chgcar_as_array = np.array([chgcars.data[k] for k in ["total","diff"] if chgcars.data.get(k) is not None])
        np.save(f"chgcar_{mpid}.npy")

I would like to say thank you to @Aaron_Kaplan and @bigtom4coding ,
for your Q&A indirectly solved my query that mp-api does not work for acquiring chgcar.

If one sees the following error:

 [... skipping hidden 1 frame]

/usr/local/lib/python3.10/dist-packages/emmet/core/tasks.py in model_post_init(self, _TaskDoc__context)
    451         # To determine task and run type, we search for input sets in this order
    452         # of precedence: calcs_reversed, inputs, orig_inputs
--> 453         for inp_set in [self.calcs_reversed[0].input, self.input, self.orig_inputs]:
    454             if inp_set is not None:
    455                 break

TypeError: 'NoneType' object is not subscriptable

It is because emmet-core 0.84.1 has a bug. The solution is:

pip install mp-api
pip install emmet-core==0.83.0
#pip install numpy==1.26.4 # numpy 2.0 does not work either

@munrojm @tschaume

Hi @sc303165, this may be more of an issue with older tasks in MP (we’re working to make sure they are all in the same format), but since the line of code this fails on is from a PR I made, I’ll look into it!

Cheers!

@Aaron_Kaplan Thank you very much ! You answer is very helpful!
@sc303165 Thank you as well for another piece of valuable information!