Coverage for ase/visualize/mlab.py: 13.51%

74 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import optparse 

2 

3import numpy as np 

4 

5from ase.calculators.calculator import get_calculator_class 

6from ase.data import covalent_radii 

7from ase.data.colors import cpk_colors 

8from ase.io.cube import read_cube_data 

9 

10 

11def plot(atoms, data, contours): 

12 """Plot atoms, unit-cell and iso-surfaces using Mayavi. 

13 

14 Parameters 

15 ---------- 

16 

17 atoms: Atoms object 

18 Positions, atomic numbers and unit-cell. 

19 data: 3-d ndarray of float 

20 Data for iso-surfaces. 

21 contours: list of float 

22 Contour values. 

23 """ 

24 

25 # Delay slow imports: 

26 import os 

27 

28 from mayavi import mlab 

29 

30 # mayavi GUI bug fix for remote access via ssh (X11 forwarding) 

31 if 'SSH_CONNECTION' in os.environ: 

32 f = mlab.gcf() 

33 f.scene._lift() 

34 

35 mlab.figure(1, bgcolor=(1, 1, 1)) # make a white figure 

36 

37 # Plot the atoms as spheres: 

38 for pos, Z in zip(atoms.positions, atoms.numbers): 

39 mlab.points3d( 

40 *pos, 

41 scale_factor=covalent_radii[Z], 

42 resolution=20, 

43 color=tuple(cpk_colors[Z]), 

44 ) 

45 

46 # Draw the unit cell: 

47 A = atoms.cell 

48 for i1, a in enumerate(A): 

49 i2 = (i1 + 1) % 3 

50 i3 = (i1 + 2) % 3 

51 for b in [np.zeros(3), A[i2]]: 

52 for c in [np.zeros(3), A[i3]]: 

53 p1 = b + c 

54 p2 = p1 + a 

55 mlab.plot3d( 

56 [p1[0], p2[0]], 

57 [p1[1], p2[1]], 

58 [p1[2], p2[2]], 

59 tube_radius=0.1, 

60 ) 

61 

62 cp = mlab.contour3d( 

63 data, contours=contours, transparent=True, opacity=0.5, colormap='hot' 

64 ) 

65 # Do some tvtk magic in order to allow for non-orthogonal unit cells: 

66 polydata = cp.actor.actors[0].mapper.input 

67 pts = np.array(polydata.points) - 1 

68 # Transform the points to the unit cell: 

69 polydata.points = np.dot(pts, A / np.array(data.shape)[:, np.newaxis]) 

70 

71 # Apparently we need this to redraw the figure, maybe it can be done in 

72 # another way? 

73 mlab.view(azimuth=155, elevation=70, distance='auto') 

74 # Show the 3d plot: 

75 mlab.show() 

76 

77 

78def view_mlab(atoms, *args, **kwargs): 

79 return plot(atoms, *args, **kwargs) 

80 

81 

82description = """\ 

83Plot iso-surfaces from a cube-file or a wave function or an electron 

84density from a calculator-restart file.""" 

85 

86 

87def main(args=None): 

88 parser = optparse.OptionParser( 

89 usage='%prog [options] filename', description=description 

90 ) 

91 add = parser.add_option 

92 add( 

93 '-n', 

94 '--band-index', 

95 type=int, 

96 metavar='INDEX', 

97 help='Band index counting from zero.', 

98 ) 

99 add( 

100 '-s', 

101 '--spin-index', 

102 type=int, 

103 metavar='SPIN', 

104 help='Spin index: zero or one.', 

105 ) 

106 add( 

107 '-e', 

108 '--electrostatic-potential', 

109 action='store_true', 

110 help='Plot the electrostatic potential.', 

111 ) 

112 add( 

113 '-c', 

114 '--contours', 

115 default='4', 

116 help='Use "-c 3" for 3 contours or "-c -0.5,0.5" for specific ' 

117 + 'values. Default is four contours.', 

118 ) 

119 add('-r', '--repeat', help='Example: "-r 2,2,2".') 

120 add('-C', '--calculator-name', metavar='NAME', help='Name of calculator.') 

121 

122 opts, args = parser.parse_args(args) 

123 if len(args) != 1: 

124 parser.error('Incorrect number of arguments') 

125 

126 arg = args[0] 

127 if arg.endswith('.cube'): 

128 data, atoms = read_cube_data(arg) 

129 else: 

130 calc = get_calculator_class(opts.calculator_name)(arg, txt=None) 

131 atoms = calc.get_atoms() 

132 if opts.band_index is None: 

133 if opts.electrostatic_potential: 

134 data = calc.get_electrostatic_potential() 

135 else: 

136 data = calc.get_pseudo_density(opts.spin_index) 

137 else: 

138 data = calc.get_pseudo_wave_function( 

139 opts.band_index, opts.spin_index or 0 

140 ) 

141 if data.dtype == complex: 

142 data = abs(data) 

143 

144 mn = data.min() 

145 mx = data.max() 

146 print('Min: %16.6f' % mn) 

147 print('Max: %16.6f' % mx) 

148 

149 if opts.contours.isdigit(): 

150 n = int(opts.contours) 

151 d = (mx - mn) / n 

152 contours = np.linspace(mn + d / 2, mx - d / 2, n).tolist() 

153 else: 

154 contours = [float(x) for x in opts.contours.rstrip(',').split(',')] 

155 

156 if len(contours) == 1: 

157 print('1 contour:', contours[0]) 

158 else: 

159 print( 

160 '%d contours: %.6f, ..., %.6f' 

161 % (len(contours), contours[0], contours[-1]) 

162 ) 

163 

164 if opts.repeat: 

165 repeat = [int(r) for r in opts.repeat.split(',')] 

166 data = np.tile(data, repeat) 

167 atoms *= repeat 

168 

169 plot(atoms, data, contours) 

170 

171 

172if __name__ == '__main__': 

173 main()