My aim is to voxelize a CHGCAR file. I am trying to build up a workflow to do the same. With the aid of the Matter Modeling community members, I have figured out a way to convert a CHGCAR file into the CUBE format. Now I want to further process the CUBE file, in an attempt to voxelize it.

  • $\begingroup$ I read here that "Voxelization is the process of converting data structures that store geometric information in a continuous domain (such as a 3D triangular mesh) into a rasterized image (a discrete grid)." A cube file stores information on a discrete 3d grid, i.e. it already is "voxelized". $\endgroup$ Jun 27, 2021 at 11:17

1 Answer 1


I'm not sure precisely what you mean, but if you want to convert a Cube file to an ($N\times4$) matrix where $N$ is the number of points and the 4 columns are (x,y,z,value), you can try the following code snippet taken from my GitHub repository here, which I reproduce below:

cube_filepath = '/path/to/mycube.cube' # Path to Cube File

def cube_to_xyzval(cube_file):
    Converts cube to pandas DataFrame

        cube_file (string): path to cube file
        pd_data (Pandas dataframe): dataframe of (x,y,z,val) grid
    nline = 0
    data = []
    with open(cube_file,'r') as f:
        for line in f:
            nline += 1
            if nline == 3:
            elif nline >3 and nline <= 6:
            elif nline > 6 and nline <= 6+nat:
            elif nline > 5 and nline > 6+nat:
                for i in line.split():
    idx = -1
    for i in range(0,int(spacing_vec[0][0])):
        for j in range(0,int(spacing_vec[1][0])):
            for k in range(0,int(spacing_vec[2][0])):
                idx += 1
                x,y,z = i*float(spacing_vec[0][1]),j*float(spacing_vec[1][2]),k*float(spacing_vec[2][3])
    pd_data = pd.DataFrame(data)
    return pd_data

df = cube_to_xyzval(cube_filepath)
df.columns = ['x','y','z','val']

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .