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 _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 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 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 update_vbox(self, atoms): if not self.center.any(): self.center = atoms.cell.diagonal() * .5 self.images = Images([atoms]) self.images.filenames = ['kmos GUI - %s' % settings.model_name] self.set_colors() self.set_coordinates(0) self.draw() self.label.set_label('%.3e s (%.3e steps)' % (atoms.kmc_time, atoms.kmc_step))
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 get_fit(self): """Returns the parameters for fitting images to band.""" images = self._images if not hasattr(images, 'repeat'): from ase.gui.images import Images images = Images(images) N = images.repeat.prod() natoms = images.natoms // N R = images.P[:, :natoms] E = images.E F = images.F[:, :natoms] s, E, Sfit, Efit, lines = fit0(E, F, R, images.A[0], images.pbc) return s, E, Sfit, Efit, lines
def __init__(self, images=None, rotations='', show_bonds=False, expr=None): if not isinstance(images, Images): images = Images(images) self.images = images self.observers = [] self.config = read_defaults() if show_bonds: self.config['show_bonds'] = True menu = self.get_menu_data() self.window = ui.ASEGUIWindow(close=self.exit, menu=menu, config=self.config, scroll=self.scroll, scroll_event=self.scroll_event, press=self.press, move=self.move, release=self.release, resize=self.resize) View.__init__(self, rotations) Status.__init__(self) self.subprocesses = [] # list of external processes self.movie_window = None self.vulnerable_windows = [] self.simulation = {} # Used by modules on Calculate menu. self.module_state = {} # Used by modules to store their state. self.arrowkey_mode = self.ARROWKEY_SCAN self.move_atoms_mask = None self.set_frame(len(self.images) - 1, focus=True) # Used to move the structure with the mouse self.prev_pos = None self.last_scroll_time = time() self.orig_scale = self.scale if len(self.images) > 1: self.movie() if expr is None: expr = self.config['gui_graphs_string'] if expr is not None and expr != '' and len(self.images) > 1: self.plot_graphs(expr=expr, ignore_if_nan=True)
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 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, e: if len(e.args) == 1: parser.error(e.args[0]) else: parser.error(e.args[1] + ': ' + e.filename)
def run(args, parser): # Nothing will ever be stored in args.output; need to manually find # if its supplied by checking extensions. if args.filenames[-1].endswith('.pdf'): args.output = args.filenames.pop(-1) else: args.output = 'nebplots.pdf' images = Images() images.read(args.filenames) nebtools = NEBTools(images=images) nebtools.plot_bands(constant_x=args.constant_x, constant_y=args.constant_y, nimages=args.n_images, label=args.output[:-4])
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 __init__(self, images=None, rotations='', show_unit_cell=True, show_bonds=False): # Try to change into directory of file you are viewing try: os.chdir(os.path.split(sys.argv[1])[0]) # This will fail sometimes (e.g. for starting a new session) except: pass if not images: images = Images() images.initialize([Atoms()]) self.images = images self.config = read_defaults() menu = self.get_menu_data(show_unit_cell, show_bonds) self.window = ui.ASEGUIWindow(close=self.exit, menu=menu, config=self.config, scroll=self.scroll, scroll_event=self.scroll_event, press=self.press, move=self.move, release=self.release, resize=self.resize) View.__init__(self, rotations) Status.__init__(self) self.graphs = [] # list of matplotlib processes self.graph_wref = [] # list of weakrefs to Graph objects self.movie_window = None self.vulnerable_windows = [] self.simulation = {} # Used by modules on Calculate menu. self.module_state = {} # Used by modules to store their state. self.arrowkey_mode = self.ARROWKEY_SCAN self.move_atoms_mask = 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.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)]
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 __init__(self, config, images=None, element_colors=None): """Initialise the GUI. Parameters ---------- config: ViewConfig initial configuration settings images : ase.gui.images.Images list of ase.Atoms, with some settings for visualisations (mainly radii) element_colors: list[tuple] hex colour for each atomic number (defaults to 'jmol' scheme) """ if not isinstance(images, Images): images = Images(images) self.images = images self.observers = [] self.config = attr.asdict(config) # aliases required by ui.ASEGUIWindow self.config["gui_foreground_color"] = self.config["canvas_color_foreground"] self.config["gui_background_color"] = self.config["canvas_color_background"] self.config["swap_mouse"] = self.config["gui_swap_mouse"] menu = self.get_menu_data() self.window = ui.ASEGUIWindow( close=self.exit, menu=menu, config=self.config, scroll=self.scroll, scroll_event=self.scroll_event, press=self.press, move=self.move, release=self.release, resize=self.resize, ) # used by ``View.update_labels`` label_sites = {"index": 1, "magmom": 2, "element": 3, "charge": 4}.get( self.config["atom_label_by"], 0 ) if not self.config["atom_show_label"]: label_sites = 0 self.window["show-labels"] = label_sites View.__init__(self, self.config["rotations"]) if element_colors: self.colors = dict(enumerate(element_colors)) self.subprocesses = [] # list of external processes self.movie_window = None self.vulnerable_windows = [] self.simulation = {} # Used by modules on Calculate menu. self.module_state = {} # Used by modules to store their state. self.arrowkey_mode = self.ARROWKEY_SCAN self.move_atoms_mask = None self.set_frame(len(self.images) - 1, focus=True) # Used to move the structure with the mouse self.prev_pos = None self.last_scroll_time = self.t0 = time() self.orig_scale = self.scale self.xy = None if len(self.images) > 1: self.movie()