def edit(self): """Modify atoms interactively through ag viewer. Conflicts leading to undesirable behviour might arise when matplotlib has been pre-imported with certain incompatible backends and while trying to use the plot feature inside the interactive ag. To circumvent, please set matplotlib.use('gtk') before calling this method. """ from ase.gui.images import Images from ase.gui.gui import GUI images = Images([self]) gui = GUI(images) gui.run() # use atoms returned from gui: # (1) delete all currently available atoms self.set_constraint() for z in range(len(self)): self.pop() edited_atoms = gui.images.get_atoms(0) # (2) extract atoms from edit session self.extend(edited_atoms) self.set_constraint(edited_atoms._get_constraints()) self.set_cell(edited_atoms.get_cell()) self.set_initial_magnetic_moments(edited_atoms.get_magnetic_moments()) self.set_tags(edited_atoms.get_tags()) return
def gui(display): orig_ui_error = ui.error try: ui.error = Error() gui = GUI() yield gui gui.exit() finally: ui.error = orig_ui_error
def run(opt, args): images = Images() if opt.aneb: opt.image_number = '-1' if len(args) > 0: from ase.io import string2index try: images.read(args, string2index(opt.image_number)) except IOError as e: if len(e.args) == 1: parser.error(e.args[0]) else: parser.error(e.args[1] + ': ' + e.filename) else: images.initialize([Atoms()]) if opt.interpolate: images.interpolate(opt.interpolate) if opt.aneb: images.aneb() if opt.repeat != '1': r = opt.repeat.split(',') if len(r) == 1: r = 3 * r images.repeat_images([int(c) for c in r]) if opt.radii_scale: images.set_radii(opt.radii_scale) if opt.output is not None: images.write(opt.output, rotations=opt.rotations, show_unit_cell=opt.show_unit_cell) opt.terminal = True if opt.terminal: if opt.graph is not None: data = images.graph(opt.graph) for line in data.T: for x in line: print(x, end=' ') print() else: from ase.gui.gui import GUI import ase.gui.gtkexcepthook ase gui = GUI(images, opt.rotations, opt.show_unit_cell, opt.bonds) gui.run(opt.graph)
def show_clusters(self): from ase.gui.gui import GUI from ase.gui.images import Images all_clusters = [] self.tag_by_probability() for uid in range(len(self.gaussians)): cluster = self.atoms[self.cluster_id == uid] cluster.info = {"name": "Cluster ID: {}".format(uid)} all_clusters.append(cluster) images = Images() images.initialize(all_clusters) gui = GUI(images) gui.show_name = True gui.run()
def _set_reactive_indexes(self, filename): ''' Manually set the molecule reactive atoms from the ASE GUI, imposing constraints on the desired atoms. ''' from ase import Atoms from ase.gui.gui import GUI from ase.gui.images import Images data = read_xyz(filename) coords = data.atomcoords[0] labels = ''.join([pt[i].symbol for i in data.atomnos]) atoms = Atoms(labels, positions=coords) while atoms.constraints == []: print(( '\nPlease, manually select the reactive atom(s) for molecule %s.' '\nRotate with right click and select atoms by clicking. Multiple selections can be done by Ctrl+Click.' '\nWith desired atom(s) selected, go to Tools -> Constraints -> Constrain, then close the GUI.' ) % (filename)) GUI(images=Images([atoms]), show_bonds=True).run() return list(atoms.constraints[0].get_indices())
def ase_view(mol): ''' Display an Hypermolecule instance from the ASE GUI ''' from ase import Atoms from ase.gui.gui import GUI from ase.gui.images import Images if hasattr(mol, 'reactive_atoms_classes_dict'): images = [] for c, coords in enumerate(mol.atomcoords): centers = np.vstack([ atom.center for atom in mol.reactive_atoms_classes_dict[c].values() ]) atomnos = np.concatenate((mol.atomnos, [0 for _ in centers])) totalcoords = np.concatenate((coords, centers)) images.append(Atoms(atomnos, positions=totalcoords)) else: images = [ Atoms(mol.atomnos, positions=coords) for coords in mol.atomcoords ] try: GUI(images=Images(images), show_bonds=True).run() except TclError: print( '--> GUI not available from command line interface. Skipping it.')
def run(args): from ase.gui.images import Images from ase.atoms import Atoms images = Images() if args.filenames: images.read(args.filenames, args.image_number) else: images.initialize([Atoms()]) if args.interpolate: images.interpolate(args.interpolate) if args.repeat != '1': r = args.repeat.split(',') if len(r) == 1: r = 3 * r images.repeat_images([int(c) for c in r]) if args.radii_scale: images.scale_radii(args.radii_scale) if args.output is not None: warnings.warn('You should be using "ase convert ..." instead!') images.write(args.output, rotations=args.rotations) args.terminal = True if args.terminal: if args.graph is not None: data = images.graph(args.graph) for line in data.T: for x in line: print(x, end=' ') print() else: import os from ase.gui.gui import GUI backend = os.environ.get('MPLBACKEND', '') if backend == 'module://ipykernel.pylab.backend_inline': # Jupyter should not steal our windows del os.environ['MPLBACKEND'] gui = GUI(images, args.rotations, args.bonds, args.graph) gui.run()
def run(args): f1 = ase.io.read(args[0]) f2 = ase.io.read(args[1]) i1 = Images([f1]) i2 = Images([f2]) gui1 = GUI(i1, '', 1, False) gui1.run(None) gui2 = GUI(i2, '', 1, False) gui2.run(None)
def run(opt, args): images = Images() if opt.aneb: opt.image_number = '-1' if len(args) > 0: from ase.io import string2index images.read(args, string2index(opt.image_number)) else: images.initialize([Atoms()]) if opt.interpolate: images.interpolate(opt.interpolate) if opt.aneb: images.aneb() if opt.repeat != '1': r = opt.repeat.split(',') if len(r) == 1: r = 3 * r images.repeat_images([int(c) for c in r]) if opt.radii_scale: images.set_radii(opt.radii_scale) if opt.output is not None: images.write(opt.output, rotations=opt.rotations, show_unit_cell=opt.show_unit_cell) opt.terminal = True if opt.terminal: if opt.graph is not None: data = images.graph(opt.graph) for line in data.T: for x in line: print(x, end=' ') print() else: from ase.gui.gui import GUI import ase.gui.gtkexcepthook ase gui = GUI(images, opt.rotations, opt.show_unit_cell, opt.bonds) gui.run(opt.graph)
def run(opt, args): images = Images() if opt.aneb: opt.image_number = '-1' if len(args) > 0: from ase.io import string2index images.read(args, string2index(opt.image_number)) else: images.initialize([Atoms()]) if opt.interpolate: images.interpolate(opt.interpolate) if opt.aneb: images.aneb() if opt.repeat != '1': r = opt.repeat.split(',') if len(r) == 1: r = 3 * r images.repeat_images([int(c) for c in r]) if opt.output is not None: images.write(opt.output, rotations=opt.rotations, show_unit_cell=opt.show_unit_cell) opt.terminal = True if opt.terminal: if opt.graph is not None: data = images.graph(opt.graph) for line in data.T: for x in line: print x, print else: from ase.gui.gui import GUI import ase.gui.gtkexcepthook gui = GUI(images, opt.rotations, opt.show_unit_cell, opt.bonds) gui.run(opt.graph)
def run(args): from ase.gui.images import Images from ase.atoms import Atoms images = Images() if args.filenames: from ase.io import string2index images.read(args.filenames, string2index(args.image_number)) else: images.initialize([Atoms()]) if args.interpolate: images.interpolate(args.interpolate) if args.repeat != '1': r = args.repeat.split(',') if len(r) == 1: r = 3 * r images.repeat_images([int(c) for c in r]) if args.radii_scale: images.set_radii(args.radii_scale) if args.output is not None: images.write(args.output, rotations=args.rotations, show_unit_cell=args.show_unit_cell) args.terminal = True if args.terminal: if args.graph is not None: data = images.graph(args.graph) for line in data.T: for x in line: print(x, end=' ') print() else: from ase.gui.gui import GUI gui = GUI(images, args.rotations, args.show_unit_cell, args.bonds) gui.run(args.graph)
def show_configs(): db = dataset.connect(DB_NAME) vac_tbl = db[VAC] sol_tbl = db[SOL] # Find unique runIDs ids = sol_tbl.distinct('runID') images = [] for runRes in ids: positions = [] symbols = [] charges = [] runID = runRes['runID'] for item in sol_tbl.find(runID=runID): symbols.append(item['symbol']) pos = [item['X'], item['Y'], item['Z']] positions.append(pos) charges.append(None) # Extract vacancy positions for item in vac_tbl.find(runID=runID): e = item['energy'] charges.append(e) pos = [item['X'], item['Y'], item['Z']] positions.append(pos) symbols.append('X') max_charge = max([c for c in charges if c is not None]) charges = [c - max_charge if c is not None else 0.0 for c in charges] images.append( Atoms(symbols=symbols, positions=positions, charges=charges)) from ase.gui.images import Images from ase.gui.gui import GUI images = Images(images) images.covalent_radii[0] = covalent_radii[12] gui = GUI(images) gui.run()
def run(args): from ase.gui.images import Images from ase.atoms import Atoms images = Images() if args.filenames: images.read(args.filenames, args.image_number) else: images.initialize([Atoms()]) if args.interpolate: images.interpolate(args.interpolate) if args.repeat != '1': r = args.repeat.split(',') if len(r) == 1: r = 3 * r images.repeat_images([int(c) for c in r]) if args.radii_scale: images.scale_radii(args.radii_scale) if args.output is not None: warnings.warn('You should be using "ase convert ..." instead!') images.write(args.output, rotations=args.rotations) args.terminal = True if args.terminal: if args.graph is not None: data = images.graph(args.graph) for line in data.T: for x in line: print(x, end=' ') print() else: from ase.gui.gui import GUI gui = GUI(images, args.rotations, args.bonds, args.graph) gui.run()
def _set_leaving_group(self, mol, neighbors_indexes): ''' Manually set the molecule leaving group from the ASE GUI, imposing a constraint on the desired atom. ''' if self.leaving_group_index is None: from ase import Atoms from ase.gui.gui import GUI from ase.gui.images import Images atoms = Atoms(mol.atomnos, positions=mol.atomcoords[0]) while True: print(('\nPlease, manually select the leaving group atom for molecule %s' '\nbonded to the sp3 reactive atom with index %s.' '\nRotate with right click and select atoms by clicking.' '\nThen go to Tools -> Constraints -> Constrain, and close the GUI.') % (mol.name, self.index)) GUI(images=Images([atoms]), show_bonds=True).run() if atoms.constraints != []: if len(list(atoms.constraints[0].get_indices())) == 1: if list(atoms.constraints[0].get_indices())[0] in neighbors_indexes: self.leaving_group_index = list(atoms.constraints[0].get_indices())[0] break else: print('\nSeems that the atom you selected is not bonded to the reactive center or is the reactive atom itself.\nThis is probably an error, please try again.') atoms.constraints = [] else: print('\nPlease only select one leaving group atom.') atoms.constraints = [] return self.others[neighbors_indexes.index(self.leaving_group_index)]
if __name__ == '__main__': args = p.parse_args() else: # We are running inside the test framework: ignore sys.args args = p.parse_args([]) for name in args.tests or alltests: for n in alltests: if n.startswith(name): name = n break else: 1 / 0 print(name) test = globals()[name] gui = GUI() def f(): test(gui) if not args.pause: gui.exit() gui.run(test=f) def window(): def hello(event=None): print('hello', event) menu = [('Hi', [ui.MenuItem('_Hello', hello, 'Ctrl+H')]), ('Hell_o', [ui.MenuItem('ABC', hello, choices='ABC')])]
def factory(images): gui = GUI(images) guis.append(gui) return gui
if opt.output is not None: images.write(opt.output, rotations=opt.rotations, show_unit_cell=opt.show_unit_cell) opt.terminal = True if opt.terminal: if opt.graph is not None: data = images.graph(opt.graph) for line in data.T: for x in line: print x, print else: from ase.gui.gui import GUI import ase.gui.gtkexcepthook gui = GUI(images, opt.rotations, opt.show_unit_cell, opt.bonds) gui.run(opt.graph) import traceback try: run(opt, args) except KeyboardInterrupt: pass except Exception: traceback.print_exc() print(_(""" An exception occurred! Please report the issue to [email protected] - thanks! Please also report this if it was a user error, so that a better error message can be provided next time."""))
gui.open(filename='h2o.json') save_dialog(gui, 'h2o.cif@-1') p = argparse.ArgumentParser() p.add_argument('tests', nargs='*') p.add_argument('-p', '--pause', action='store_true') if __name__ == '__main__': args = p.parse_args() else: # We are running inside the test framework: ignore sys.args args = p.parse_args([]) for name in args.tests or alltests: for n in alltests: if n.startswith(name): name = n break else: 1 / 0 print(name) test = globals()[name] gui = GUI() def f(): test(gui) if not args.pause: gui.exit() gui.run(test=f)
class KMC_ViewBox(threading.Thread, View, Status, FakeUI): """The part of the viewer GUI that displays the model's current configuration. """ def __init__(self, queue, signal_queue, vbox, window, rotations='', show_unit_cell=True, show_bonds=False): threading.Thread.__init__(self) self.image_queue = queue self.signal_queue = signal_queue self.configured = False self.ui = FakeUI.__init__(self) self.images = Images() self.aseGui = GUI() #self.aseGui.images.initialize([ase.atoms.Atoms()]) self.images.initialize([ase.atoms.Atoms()]) self.killed = False self.paused = False self.vbox = vbox self.window = window self.vbox.connect('scroll-event', self.scroll_event) self.window.connect('key-press-event', self.on_key_press) rotations = '0.0x,0.0y,0.0z' #[3,3,3]#np.zeros(3) self.config = { 'force_vector_scale': None, 'velocity_vector_scale': None, 'swap_mouse': False } View.__init__(self, rotations) Status.__init__(self) self.vbox.show() if os.name == 'posix': self.live_plot = True else: self.live_plot = False #self.drawing_area.realize() self.scaleA = 3.0 self.center = np.array([8, 8, 8]) #self.set_colors() #self.set_coordinates(0) self.center = np.array([0, 0, 0]) self.tofs = get_tof_names() # history tracking arrays self.times = [] self.tof_hist = [] self.occupation_hist = [] # prepare diagrams self.data_plot = plt.figure() #plt.xlabel('$t$ in s') self.tof_diagram = self.data_plot.add_subplot(211) self.tof_diagram.set_yscale('log') #self.tof_diagram.get_yaxis().get_major_formatter().set_powerlimits( #(3, 3)) self.tof_plots = [] for tof in self.tofs: self.tof_plots.append(self.tof_diagram.plot([], [], label=tof)[0]) self.tof_diagram.legend(loc='lower left') self.tof_diagram.set_ylabel( 'TOF in $\mathrm{s}^{-1}\mathrm{site}^{-1}$') self.occupation_plots = [] self.occupation_diagram = self.data_plot.add_subplot(212) for species in sorted(settings.representations): self.occupation_plots.append( self.occupation_diagram.plot([], [], label=species)[0], ) self.occupation_diagram.legend(loc=2) self.occupation_diagram.set_xlabel('$t$ in s') self.occupation_diagram.set_ylabel('Coverage') def update_vbox(self, atoms): """Update the ViewBox.""" if not self.center.any(): self.center = atoms.cell.diagonal() * .5 #self.images = Images([atoms]) #self.images.filenames = ['kmcos GUI - %s' % settings.model_name] #self.set_colors() #self.set_coordinates(0) #self.set_atoms(atoms) self.scale = self.scaleA self.aseGui.scale = self.scale atoms.center(vacuum=3.0) self.aseGui.images.initialize([atoms]) self.aseGui.images.center() self.aseGui.set_frame() #self.draw() #self.label.set_label('%.3e s (%.3e steps)' % (atoms.kmc_time, # atoms.kmc_step)) def update_plots(self, atoms): """Update the coverage and TOF plots.""" # fetch data piggy-backed on atoms object new_time = atoms.kmc_time occupations = atoms.occupation.sum(axis=1) / lattice.spuck tof_data = atoms.tof_data # store locally while len(self.times) > getattr(settings, 'hist_length', 30): self.tof_hist.pop(0) self.times.pop(0) self.occupation_hist.pop(0) self.times.append(atoms.kmc_time) self.tof_hist.append(tof_data) self.occupation_hist.append(occupations) # plot TOFs for i, tof_plot in enumerate(self.tof_plots): tof_plot.set_xdata(self.times) tof_plot.set_ydata([tof[i] for tof in self.tof_hist]) self.tof_diagram.set_xlim(self.times[0], self.times[-1]) self.tof_diagram.set_ylim( 1e-3, 10 * max([tof[i] for tof in self.tof_hist])) # plot occupation for i, occupation_plot in enumerate(self.occupation_plots): occupation_plot.set_xdata(self.times) occupation_plot.set_ydata([occ[i] for occ in self.occupation_hist]) max_occ = max(occ[i] for occ in self.occupation_hist) self.occupation_diagram.set_ylim([0, max(1, max_occ)]) self.occupation_diagram.set_xlim([self.times[0], self.times[-1]]) self.data_plot.canvas.draw_idle() manager = plt.get_current_fig_manager() if hasattr(manager, 'toolbar'): toolbar = manager.toolbar if hasattr(toolbar, 'set_visible'): toolbar.set_visible(False) plt.show() # [:] is necessary so that it copies the # values and doesn't reinitialize the pointer self.time = new_time return False def kill(self): self.killed = True def run(self): time.sleep(1.) while not self.killed: time.sleep(1) if not self.image_queue.empty(): atoms = self.image_queue.get() gobject.idle_add(self.update_vbox, atoms) if self.live_plot: gobject.idle_add(self.update_plots, atoms) def on_key_press(self, _widget, event): """Process key press event on view box.""" signal_dict = { 'a': 'ACCUM_RATE_SUMMATION', 'c': 'COVERAGE', 'd': 'DOUBLE', 'h': 'HALVE', 's': 'SWITCH_SURFACE_PROCESSS_OFF', 'S': 'SWITCH_SURFACE_PROCESSS_ON', 'w': 'WRITEOUT', } if event.string in [' ', 'p']: if not self.paused: self.signal_queue.put('PAUSE') self.paused = True else: self.signal_queue.put('START') self.paused = False elif event.string in ['?']: for key, command in list(signal_dict.items()): print('%4s %s' % (key, command)) elif event.string in signal_dict: self.signal_queue.put(signal_dict.get(event.string, '')) def scroll_event(self, _window, event): """Zoom in/out when using mouse wheel""" x = 1.0 if event.direction == gtk.gdk.SCROLL_UP: x = 1.2 elif event.direction == gtk.gdk.SCROLL_DOWN: x = 1.0 / 1.2 self._do_zoom(x) def _do_zoom(self, x): """Utility method for zooming""" self.scaleA *= x try: atoms = self.image_queue.get() except Exception as e: atoms = ase.atoms.Atoms() print(e) self.update_vbox(atoms)
def __init__(self, queue, signal_queue, vbox, window, rotations='', show_unit_cell=True, show_bonds=False): threading.Thread.__init__(self) self.image_queue = queue self.signal_queue = signal_queue self.configured = False self.ui = FakeUI.__init__(self) self.images = Images() self.aseGui = GUI() #self.aseGui.images.initialize([ase.atoms.Atoms()]) self.images.initialize([ase.atoms.Atoms()]) self.killed = False self.paused = False self.vbox = vbox self.window = window self.vbox.connect('scroll-event', self.scroll_event) self.window.connect('key-press-event', self.on_key_press) rotations = '0.0x,0.0y,0.0z' #[3,3,3]#np.zeros(3) self.config = { 'force_vector_scale': None, 'velocity_vector_scale': None, 'swap_mouse': False } View.__init__(self, rotations) Status.__init__(self) self.vbox.show() if os.name == 'posix': self.live_plot = True else: self.live_plot = False #self.drawing_area.realize() self.scaleA = 3.0 self.center = np.array([8, 8, 8]) #self.set_colors() #self.set_coordinates(0) self.center = np.array([0, 0, 0]) self.tofs = get_tof_names() # history tracking arrays self.times = [] self.tof_hist = [] self.occupation_hist = [] # prepare diagrams self.data_plot = plt.figure() #plt.xlabel('$t$ in s') self.tof_diagram = self.data_plot.add_subplot(211) self.tof_diagram.set_yscale('log') #self.tof_diagram.get_yaxis().get_major_formatter().set_powerlimits( #(3, 3)) self.tof_plots = [] for tof in self.tofs: self.tof_plots.append(self.tof_diagram.plot([], [], label=tof)[0]) self.tof_diagram.legend(loc='lower left') self.tof_diagram.set_ylabel( 'TOF in $\mathrm{s}^{-1}\mathrm{site}^{-1}$') self.occupation_plots = [] self.occupation_diagram = self.data_plot.add_subplot(212) for species in sorted(settings.representations): self.occupation_plots.append( self.occupation_diagram.plot([], [], label=species)[0], ) self.occupation_diagram.legend(loc=2) self.occupation_diagram.set_xlabel('$t$ in s') self.occupation_diagram.set_ylabel('Coverage')