Coverage for /builds/kinetik161/ase/ase/gui/save.py: 79.59%

49 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-12-10 11:04 +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 (filetype, get_ioformat, parse_filename, 

8 string2index, write) 

9 

10text = _("""\ 

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

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

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

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

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

16you all images. Negative numbers count from the 

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

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

19 

20 

21def save_dialog(gui, filename=None): 

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

23 # fix tkinter not automatically setting dialog type 

24 # remove from Python3.8+ 

25 # see https://github.com/python/cpython/pull/25187 

26 # and https://bugs.python.org/issue43655 

27 # and https://github.com/python/cpython/pull/25592 

28 ui.set_windowtype(dialog.top, 'dialog') 

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

30 filename = filename or dialog.go() 

31 if not filename: 

32 return 

33 

34 filename, index = parse_filename(filename) 

35 if index is None: 

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

37 elif isinstance(index, str): 

38 index = string2index(index) 

39 elif isinstance(index, slice): 

40 pass 

41 else: 

42 if index < 0: 

43 index += len(gui.images) 

44 index = slice(index, index + 1) 

45 format = filetype(filename, read=False) 

46 io = get_ioformat(format) 

47 

48 extra = {} 

49 remove_hidden = False 

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

51 bbox = np.empty(4) 

52 size = gui.window.size / gui.scale 

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

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

55 extra['rotation'] = gui.axes 

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

57 extra['bbox'] = bbox 

58 colors = gui.get_colors(rgb=True) 

59 extra['colors'] = [rgb for rgb, visible 

60 in zip(colors, gui.images.visible) 

61 if visible] 

62 remove_hidden = True 

63 

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

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

66 

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

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

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

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

71 j = filename.rfind('.') 

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

73 for i, atoms in enumerate(images): 

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

75 else: 

76 try: 

77 write(filename, images, **extra) 

78 except Exception as err: 

79 from ase.gui.ui import showerror 

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

81 raise