Coverage for ase/gui/colors.py: 81.90%
105 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""colors.py - select how to color the atoms in the GUI."""
3import numpy as np
5import ase.gui.ui as ui
6from ase.gui.i18n import _
7from ase.gui.utils import get_magmoms
10class ColorWindow:
11 """A window for selecting how to color the atoms."""
13 def __init__(self, gui):
14 self.reset(gui)
16 def reset(self, gui):
17 """create a new color window"""
18 self.win = ui.Window(_('Colors'))
19 self.gui = gui
20 self.win.add(ui.Label(_('Choose how the atoms are colored:')))
21 values = [
22 'jmol',
23 'tag',
24 'force',
25 'velocity',
26 'initial charge',
27 'magmom',
28 'neighbors',
29 ]
30 labels = [
31 _('By atomic number, default "jmol" colors'),
32 _('By tag'),
33 _('By force'),
34 _('By velocity'),
35 _('By initial charge'),
36 _('By magnetic moment'),
37 _('By number of neighbors'),
38 ]
40 haveit = [
41 'numbers',
42 'positions',
43 'forces',
44 'momenta',
45 'initial_charges',
46 'initial_magmoms',
47 ]
48 for key in self.gui.atoms.arrays:
49 if key not in haveit:
50 values.append(key)
51 labels.append(f'By user-defined "{key}"')
53 self.radio = ui.RadioButtons(labels, values, self.toggle, vertical=True)
54 self.radio.value = gui.colormode
55 self.win.add(self.radio)
56 self.activate()
57 self.label = ui.Label()
58 self.win.add(self.label)
60 if hasattr(self, 'mnmx'):
61 self.win.add(self.cmaps)
62 self.win.add(self.mnmx)
64 def change_mnmx(self, mn=None, mx=None):
65 """change min and/or max values for colormap"""
66 if mn:
67 self.mnmx[1].value = mn
68 if mx:
69 self.mnmx[3].value = mx
70 mn, mx = self.mnmx[1].value, self.mnmx[3].value
71 colorscale, _, _ = self.gui.colormode_data
72 self.gui.colormode_data = colorscale, mn, mx
73 self.gui.draw()
75 def activate(self):
76 images = self.gui.images
77 atoms = self.gui.atoms
78 radio = self.radio
79 radio['tag'].active = atoms.has('tags')
81 # XXX not sure how to deal with some images having forces,
82 # and other images not. Same goes for below quantities
83 F = images.get_forces(atoms)
84 radio['force'].active = F is not None
85 radio['velocity'].active = atoms.has('momenta')
86 radio['initial charge'].active = atoms.has('initial_charges')
87 radio['magmom'].active = get_magmoms(atoms).any()
88 radio['neighbors'].active = True
90 def toggle(self, value):
91 self.gui.colormode = value
92 if value == 'jmol' or value == 'neighbors':
93 if hasattr(self, 'mnmx'):
94 'delete the min max fields by creating a new window'
95 del self.mnmx
96 del self.cmaps
97 self.win.close()
98 self.reset(self.gui)
99 text = ''
100 else:
101 scalars = np.ma.array(
102 [
103 self.gui.get_color_scalars(i)
104 for i in range(len(self.gui.images))
105 ]
106 )
107 mn = np.min(scalars)
108 mx = np.max(scalars)
109 self.gui.colormode_data = None, mn, mx
111 cmaps = ['default', 'old']
112 try:
113 import pylab as plt
115 cmaps += [m for m in plt.cm.datad if not m.endswith('_r')]
116 except ImportError:
117 pass
118 self.cmaps = [
119 _('cmap:'),
120 ui.ComboBox(cmaps, cmaps, self.update_colormap),
121 _('N:'),
122 ui.SpinBox(26, 0, 100, 1, self.update_colormap),
123 ]
124 self.update_colormap('default')
126 try:
127 unit = {
128 'tag': '',
129 'force': 'eV/Ang',
130 'velocity': '(eV/amu)^(1/2)',
131 'charge': '|e|',
132 'initial charge': '|e|',
133 'magmom': 'μB',
134 }[value]
135 except KeyError:
136 unit = ''
137 text = ''
139 rng = mx - mn # XXX what are optimal allowed range and steps ?
140 self.mnmx = [
141 _('min:'),
142 ui.SpinBox(
143 mn,
144 mn - 10 * rng,
145 mx + rng,
146 rng / 10.0,
147 self.change_mnmx,
148 width=20,
149 ),
150 _('max:'),
151 ui.SpinBox(
152 mx,
153 mn - 10 * rng,
154 mx + rng,
155 rng / 10.0,
156 self.change_mnmx,
157 width=20,
158 ),
159 _(unit),
160 ]
161 self.win.close()
162 self.reset(self.gui)
164 self.label.text = text
165 self.radio.value = value
166 self.gui.draw()
167 return text # for testing
169 def notify_atoms_changed(self):
170 "Called by gui object when the atoms have changed."
171 self.activate()
172 mode = self.gui.colormode
173 if not self.radio[mode].active:
174 mode = 'jmol'
175 self.toggle(mode)
177 def update_colormap(self, cmap=None, N=26):
178 "Called by gui when colormap has changed"
179 import matplotlib
181 if cmap is None:
182 cmap = self.cmaps[1].value
183 try:
184 N = int(self.cmaps[3].value)
185 except AttributeError:
186 N = 26
187 colorscale, mn, mx = self.gui.colormode_data
188 if cmap == 'default':
189 colorscale = [
190 '#{0:02X}80{0:02X}'.format(int(red))
191 for red in np.linspace(0, 250, N)
192 ]
193 elif cmap == 'old':
194 colorscale = [
195 f'#{int(red):02X}AA00' for red in np.linspace(0, 230, N)
196 ]
197 else:
198 cmap_obj = matplotlib.colormaps[cmap]
199 colorscale = [
200 matplotlib.colors.rgb2hex(c[:3])
201 for c in cmap_obj(np.linspace(0, 1, N))
202 ]
203 self.gui.colormode_data = colorscale, mn, mx
204 self.gui.draw()