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"""
2IO support for the Gaussian cube format.
4See the format specifications on:
5http://local.wasp.uwa.edu.au/~pbourke/dataformats/cube/
6"""
9import numpy as np
10import time
11from ase.atoms import Atoms
12from ase.io import read
13from ase.units import Bohr
16def write_cube(fileobj, atoms, data=None, origin=None, comment=None):
17 """
18 Function to write a cube file.
20 fileobj: str or file object
21 File to which output is written.
22 atoms: Atoms object
23 Atoms object specifying the atomic configuration.
24 data : 3dim numpy array, optional (default = None)
25 Array containing volumetric data as e.g. electronic density
26 origin : 3-tuple
27 Origin of the volumetric data (units: Angstrom)
28 comment : str, optional (default = None)
29 Comment for the first line of the cube file.
30 """
32 if data is None:
33 data = np.ones((2, 2, 2))
34 data = np.asarray(data)
36 if data.dtype == complex:
37 data = np.abs(data)
39 if comment is None:
40 comment = 'Cube file from ASE, written on ' + time.strftime('%c')
41 else:
42 comment = comment.strip()
43 fileobj.write(comment)
45 fileobj.write('\nOUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z\n')
47 if origin is None:
48 origin = np.zeros(3)
49 else:
50 origin = np.asarray(origin) / Bohr
52 fileobj.write('{0:5}{1:12.6f}{2:12.6f}{3:12.6f}\n'
53 .format(len(atoms), *origin))
55 for i in range(3):
56 n = data.shape[i]
57 d = atoms.cell[i] / n / Bohr
58 fileobj.write('{0:5}{1:12.6f}{2:12.6f}{3:12.6f}\n'.format(n, *d))
60 positions = atoms.positions / Bohr
61 numbers = atoms.numbers
62 for Z, (x, y, z) in zip(numbers, positions):
63 fileobj.write('{0:5}{1:12.6f}{2:12.6f}{3:12.6f}{4:12.6f}\n'
64 .format(Z, 0.0, x, y, z))
66 data.tofile(fileobj, sep='\n', format='%e')
69def read_cube(fileobj, read_data=True, program=None, verbose=False):
70 """Read atoms and data from CUBE file.
72 fileobj : str or file
73 Location to the cubefile.
74 read_data : boolean
75 If set true, the actual cube file content, i.e. an array
76 containing the electronic density (or something else )on a grid
77 and the dimensions of the corresponding voxels are read.
78 program: str
79 Use program='castep' to follow the PBC convention that first and
80 last voxel along a direction are mirror images, thus the last
81 voxel is to be removed. If program=None, the routine will try
82 to catch castep files from the comment lines.
83 verbose : bool
84 Print some more information to stdout.
86 Returns a dict with the following keys:
88 * 'atoms': Atoms object
89 * 'data' : (Nx, Ny, Nz) ndarray
90 * 'origin': (3,) ndarray, specifying the cube_data origin.
91 """
93 readline = fileobj.readline
94 line = readline() # the first comment line
95 line = readline() # the second comment line
97 # The second comment line *CAN* contain information on the axes
98 # But this is by far not the case for all programs
99 axes = []
100 if 'OUTER LOOP' in line.upper():
101 axes = ['XYZ'.index(s[0]) for s in line.upper().split()[2::3]]
102 if not axes:
103 axes = [0, 1, 2]
105 # castep2cube files have a specific comment in the second line ...
106 if 'castep2cube' in line:
107 program = 'castep'
108 if verbose:
109 print('read_cube identified program: castep')
111 # Third line contains actual system information:
112 line = readline().split()
113 natoms = int(line[0])
115 # Origin around which the volumetric data is centered
116 # (at least in FHI aims):
117 origin = np.array([float(x) * Bohr for x in line[1::]])
119 cell = np.empty((3, 3))
120 shape = []
122 # the upcoming three lines contain the cell information
123 for i in range(3):
124 n, x, y, z = [float(s) for s in readline().split()]
125 shape.append(int(n))
127 # different PBC treatment in castep, basically the last voxel row is
128 # identical to the first one
129 if program == 'castep':
130 n -= 1
131 cell[i] = n * Bohr * np.array([x, y, z])
133 numbers = np.empty(natoms, int)
134 positions = np.empty((natoms, 3))
135 for i in range(natoms):
136 line = readline().split()
137 numbers[i] = int(line[0])
138 positions[i] = [float(s) for s in line[2:]]
140 positions *= Bohr
142 atoms = Atoms(numbers=numbers, positions=positions, cell=cell)
144 # CASTEP will always have PBC, although the cube format does not
145 # contain this kind of information
146 if program == 'castep':
147 atoms.pbc = True
149 dct = {'atoms': atoms}
151 if read_data:
152 data = np.array([float(s)
153 for s in fileobj.read().split()]).reshape(shape)
154 if axes != [0, 1, 2]:
155 data = data.transpose(axes).copy()
157 if program == 'castep':
158 # Due to the PBC applied in castep2cube, the last entry along each
159 # dimension equals the very first one.
160 data = data[:-1, :-1, :-1]
162 dct['data'] = data
163 dct['origin'] = origin
165 return dct
168def read_cube_data(filename):
169 """Wrapper function to read not only the atoms information from a cube file
170 but also the contained volumetric data.
171 """
172 dct = read(filename, format='cube', read_data=True, full_output=True)
173 return dct['data'], dct['atoms']