Coverage for ase/gui/save.py: 79.17%

48 statements  

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

1"""Dialog for saving one or more configurations.""" 

2 

3import numpy as np 

4 

5import ase.gui.ui as ui 

6from ase.gui.i18n import _ 

7from ase.io.formats import ( 

8 filetype, 

9 get_ioformat, 

10 parse_filename, 

11 string2index, 

12 write, 

13) 

14 

15text = _("""\ 

16Append name with "@n" in order to write image 

17number "n" instead of the current image. Append 

18"@start:stop" or "@start:stop:step" if you want 

19to write a range of images. You can leave out 

20"start" and "stop" so that "name@:" will give 

21you all images. Negative numbers count from the 

22last image. Examples: "name@-1": last image, 

23"name@-2:": last two.""") 

24 

25 

26def save_dialog(gui, filename=None): 

27 dialog = ui.SaveFileDialog(gui.window.win, _('Save ...')) 

28 ui.Text(text).pack(dialog.top) 

29 filename = filename or dialog.go() 

30 if not filename: 

31 return 

32 

33 filename, index = parse_filename(filename) 

34 if index is None: 

35 index = slice(gui.frame, gui.frame + 1) 

36 elif isinstance(index, str): 

37 index = string2index(index) 

38 elif isinstance(index, slice): 

39 pass 

40 else: 

41 if index < 0: 

42 index += len(gui.images) 

43 index = slice(index, index + 1) 

44 format = filetype(filename, read=False) 

45 io = get_ioformat(format) 

46 

47 extra = {} 

48 remove_hidden = False 

49 if format in ['png', 'eps', 'pov']: 

50 bbox = np.empty(4) 

51 size = gui.window.size / gui.scale 

52 bbox[0:2] = np.dot(gui.center, gui.axes[:, :2]) - size / 2 

53 bbox[2:] = bbox[:2] + size 

54 extra['rotation'] = gui.axes 

55 extra['show_unit_cell'] = gui.window['toggle-show-unit-cell'] 

56 extra['bbox'] = bbox 

57 colors = gui.get_colors(rgb=True) 

58 extra['colors'] = [ 

59 rgb for rgb, visible in zip(colors, gui.images.visible) if visible 

60 ] 

61 remove_hidden = True 

62 

63 images = [ 

64 gui.images.get_atoms(i, remove_hidden=remove_hidden) 

65 for i in range(*index.indices(len(gui.images))) 

66 ] 

67 

68 if len(images) > 1 and io.single: 

69 # We want to write multiple images, but the file format does not 

70 # support it. The solution is to write multiple files, inserting 

71 # a number in the file name before the suffix. 

72 j = filename.rfind('.') 

73 filename = filename[:j] + '{0:05d}' + filename[j:] 

74 for i, atoms in enumerate(images): 

75 write(filename.format(i), atoms, **extra) 

76 else: 

77 try: 

78 write(filename, images, **extra) 

79 except Exception as err: 

80 from ase.gui.ui import showerror 

81 

82 showerror(_('Error'), err) 

83 raise