Coverage for /builds/ase/ase/ase/cli/reciprocal.py: 76.09%

46 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2025-08-02 00:12 +0000

1# fmt: off 

2 

3# Note: 

4# Try to avoid module level import statements here to reduce 

5# import time during CLI execution 

6from ase.cli.main import CLIError 

7 

8 

9def plot_reciprocal_cell(path, output=None): 

10 import matplotlib.pyplot as plt 

11 

12 path.plot() 

13 

14 if output: 

15 plt.savefig(output) 

16 else: 

17 plt.show() 

18 

19 

20def read_object(filename): 

21 from ase.io import read 

22 from ase.io.formats import UnknownFileTypeError 

23 from ase.io.jsonio import read_json 

24 

25 try: 

26 return read(filename) 

27 except UnknownFileTypeError: 

28 # Probably a bandpath/bandstructure: 

29 return read_json(filename) 

30 

31 

32def obj2bandpath(obj): 

33 from ase import Atoms 

34 from ase.dft.kpoints import BandPath 

35 

36 if isinstance(obj, BandPath): 

37 print('Object is a band path') 

38 print(obj) 

39 return obj 

40 

41 if isinstance(getattr(obj, 'path', None), BandPath): 

42 print(f'Object contains a bandpath: {obj}') 

43 path = obj.path 

44 print(path) 

45 return path 

46 

47 if isinstance(obj, Atoms): 

48 print(f'Atoms object: {obj}') 

49 print('Determining standard form of Bravais lattice:') 

50 lat = obj.cell.get_bravais_lattice(pbc=obj.pbc) 

51 print(lat.description()) 

52 print('Showing default bandpath') 

53 return lat.bandpath(density=0) 

54 

55 raise CLIError(f'Strange object: {obj}') 

56 

57 

58class CLICommand: 

59 """Show the reciprocal space. 

60 

61 Read unit cell from a file and show a plot of the 1. Brillouin zone. If 

62 the file contains information about k-points, then those can be plotted 

63 too. 

64 

65 Examples: 

66 

67 $ ase build -x fcc Al al.traj 

68 $ ase reciprocal al.traj 

69 """ 

70 

71 @staticmethod 

72 def add_arguments(parser): 

73 add = parser.add_argument 

74 add('name', metavar='input-file', 

75 help='Input file containing unit cell.') 

76 add('output', nargs='?', help='Write plot to file (.png, .svg, ...).') 

77 

78 @staticmethod 

79 def run(args, parser): 

80 obj = read_object(args.name) 

81 path = obj2bandpath(obj) 

82 plot_reciprocal_cell(path, output=args.output)