def show_vibs(calc, amplitude=1): import traitlets import nglview import ipywidgets as widgets from ipywidgets import Layout, HBox, VBox trajs = [] freqs, modes = calc.get_vibrational_modes() freq_list = [ '-%.2f' % (f.real * 1000) if np.iscomplexobj(f) else '%.2f' % (f * 1000) for f in freqs ] for n, mode in enumerate(modes): trajs.append( [a.positions for a in form_traj(calc.atoms, mode, amplitude)]) v = nglview.show_asetraj([calc.atoms]) v.clear_representations() v.add_spacefill(radius_type='vdw', radius_scale=0.5, roughness=1, metalness=0) v._set_size('450px', '300px') v.camera = 'orthographic' v.parameters = dict(clipDist=0, sampleLevel=1) select = widgets.Select(options=freq_list, value=freq_list[-1], layout=Layout(width='100px', height='270px'), disabled=False) play = widgets.Play(value=0, min=-10, max=10, step=1, _repeat=True, description="Press play", disabled=False) slider = widgets.IntSlider( value=0, min=-10, max=10, ) class FnScope: traj = trajs[-1] def handle_slider_change(change): v.set_coordinates({0: FnScope.traj[change.new]}) def handle_select_change(change): FnScope.traj = trajs[change.new] slider.observe(handle_slider_change, names='value') select.observe(handle_select_change, names='index') traitlets.link((play, 'value'), (slider, 'value')) vib_viewer = HBox([VBox([v, HBox([play, slider])]), select]) display(vib_viewer)
def getMiniGUI(self): view = nglview.show_asetraj(self.movie) view.parameters = dict(background_color='white', camera_type='perpective', camera_fov=15) view._camera_orientation = [ -28.583735327243016, -0.2970873285220947, 1.198387795047608, 0, -0.3455812695981218, 28.584920668432527, -1.1563751171127739, 0, -1.1853133653976955, -1.1697730312356562, -28.561879887836003, 0, -7.061999797821045, -8.524999618530273, -8.855999946594238, 1 ] #Default camera view button = widgets.Button(description='Confirm', disabled=False, button_style='') slider = widgets.IntSlider(min=0, max=self.confidence_feedback_size - 1, step=1, description='Confidence: ', value=0, continuous_update=False, readout=True, layout=widgets.Layout(width='60%', height='80px', position='right')) def confirm(event): pref_feedback = int(view.frame) conf_feedback = int(slider.value) self.user_feedback_preference = self.current_xi_grid[( pref_feedback), :] self.user_feedback_confidence = conf_feedback self.user_feedback_was_given = True button.on_click(confirm) return view, button, slider
def animate_structure(self, spacefill=True, show_cell=True, stride=1, center_of_mass=False, particle_size=0.5): """ Animates the job if a trajectory is present Args: spacefill (bool): show_cell (bool): stride (int): show animation every stride [::stride] use value >1 to make animation faster default=1 center_of_mass (bool): Returns: animation: nglview IPython widget """ if not self.status.finished: raise ValueError("This job can't be animated until it is finished") try: import nglview except ImportError: raise ImportError("The animate() function requires the package nglview to be installed") animation = nglview.show_asetraj(self.trajectory(stride=stride, center_of_mass=center_of_mass)) if spacefill: animation.add_spacefill(radius_type='vdw', scale=0.5, radius=particle_size) animation.remove_ball_and_stick() else: animation.add_ball_and_stick() if show_cell: if self.structure.cell is not None: animation.add_unitcell() return animation
def __init__(self, atoms, xsize=500, ysize=500): import nglview import nglview.color from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox self.atoms = atoms if isinstance(atoms[0], Atoms): # Assume this is a trajectory or struct list self.view = nglview.show_asetraj(atoms, default=False) self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1) self.frm.observe(self._update_frame) self.struct = atoms[0] else: # Assume this is just a single structure self.view = nglview.show_ase(atoms, default=False) self.struct = atoms self.frm = None self.colors = {} self.view._remote_call('setSize', target='Widget', args=['%dpx' % (xsize,), '%dpx' % (ysize,)]) self.view.add_unitcell() self.view.add_spacefill() self.view.camera = 'orthographic' self.view.parameters = { "clipDist": 0 } self.view.center() self.asel = Dropdown(options=['All'] + list(set(self.struct.get_chemical_symbols())), value='All', description='Show') self.csel = Dropdown(options=nglview.color.COLOR_SCHEMES, value='element', description='Color scheme') self.rad = FloatSlider(value=0.5, min=0.0, max=1.5, step=0.01, description='Ball size') self.asel.observe(self._select_atom) self.csel.observe(self._update_repr) self.rad.observe(self._update_repr) self.view.update_spacefill(radiusType='covalent', radiusScale=0.5, color_scheme=self.csel.value, color_scale='rainbow') wdg = [self.asel, self.csel, self.rad] if self.frm: wdg.append(self.frm) self.gui = HBox([self.view, VBox(wdg)]) # Make useful shortcuts for the user of the class self.gui.view = self.view self.gui.control_box = self.gui.children[1] self.gui.custom_colors = self.custom_colors
def animate_nma_mode(self, index, amplitude=1.0, frames=24, spacefill=False, particle_size=0.5): ''' Visualize the normal mode corresponding to an index **Arguments** index index corresponding to a normal mode amplitude size of the deviation of the normal mode frames number of frames that constitute the full mode (lower means faster movement) spacefill remove atom bonds particle size size of the atoms in the structure ''' print("This mode corresponds to a frequency of {} 1/cm".format( self.freqs[index] / lightspeed / (1. / centimeter))) coordinates = self.coordinates symbols = [periodic[n].symbol for n in self.numbers] mode = self.modes[:, index] if self.masses3 is not None: mode /= np.sqrt(self.masses3) mode /= np.linalg.norm(mode) positions = np.zeros((frames, len(symbols), 3)) for frame in range(frames): factor = amplitude * np.sin(2 * np.pi * float(frame) / frames) positions[frame] = (coordinates + factor * mode.reshape( (-1, 3))) / angstrom try: import nglview except ImportError: raise ImportError( "The animate_nma_mode() function requires the package nglview to be installed" ) animation = nglview.show_asetraj( Trajectory(positions, self.job.structure)) if spacefill: animation.add_spacefill(radius_type='vdw', scale=0.5, radius=particle_size) animation.remove_ball_and_stick() else: animation.add_ball_and_stick() return animation
def show_traj(traj, dis=True): # traj can be list of atoms import nglview v = nglview.show_asetraj(traj) v.clear_representations() # it seems that nglview traj cannot handle unit cell right now #v.add_unitcell() v.add_spacefill(radius_type='vdw', radius_scale=0.5, roughness=1, metalness=0) v.parameters = dict(clipDist=-100, sampleLevel=2) if dis: display(v) else: return v
def animate_structure( self, spacefill=True, show_cell=True, stride=1, center_of_mass=False, particle_size=0.5, camera="orthographic", ): """ Animates the job if a trajectory is present Args: spacefill (bool): show_cell (bool): stride (int): show animation every stride [::stride] use value >1 to make animation faster default=1 center_of_mass (bool): camera (str): camera perspective, choose from "orthographic" or "perspective" Returns: animation: nglview IPython widget """ try: import nglview except ImportError: raise ImportError( "The animate() function requires the package nglview to be installed" ) animation = nglview.show_asetraj( self.trajectory(stride=stride, center_of_mass=center_of_mass) ) if spacefill: animation.add_spacefill(radius_type="vdw", scale=0.5, radius=particle_size) animation.remove_ball_and_stick() else: animation.add_ball_and_stick() if show_cell: if self.structure.cell is not None: animation.add_unitcell() animation.camera = camera return animation
def __init__(self, atoms, xsize=500, ysize=500): import nglview from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox self.atoms = atoms if isinstance(atoms[0], Atoms): # Assume this is a trajectory or struct list self.view = nglview.show_asetraj(atoms) self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1) self.frm.observe(self._update_frame) self.struct = atoms[0] else: # Assume this is just a single structure self.view = nglview.show_ase(atoms) self.struct = atoms self.frm = None self.colors = {} self.view._remote_call('setSize', target='Widget', args=['%dpx' % (xsize,), '%dpx' % (ysize,)]) self.view.add_unitcell() self.view.add_spacefill() self.view.camera = 'orthographic' self.view.update_spacefill(radiusType='covalent', scale=0.7) self.view.center() self.asel = Dropdown(options=['All'] + list(set(self.struct.get_chemical_symbols())), value='All', description='Show') self.rad = FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01, description='Ball size') self.asel.observe(self._select_atom) self.rad.observe(self._update_repr) wdg = [self.asel, self.rad] if self.frm: wdg.append(self.frm) self.gui = HBox([self.view, VBox(wdg)]) # Make useful shortcuts for the user of the class self.gui.view = self.view self.gui.control_box = self.gui.children[1] self.gui.custom_colors = self.custom_colors
def visualiser_trajectoire(pos, stride): from ase.visualize import view from nglview import show_asetraj, show_ase from ase import Atoms Natom, _ = pos[0].shape num = [1] * Natom xsize, ysize = 400, 300 frames = [ Atoms(numbers=num, positions=pp, pbc=False) for pp in pos[::stride] ] view = show_asetraj(frames, gui=False) view.clear_representations() view.representations = [{ "type": "ball+stick", "params": { "aspectRatio": 4, 'color': "atomindex", } }, { "type": "distance", "params": { "atomPair": [[it, it + 1] for it in range(Natom - 1)], 'colorScheme': "black", 'labelSize': 4, 'labelColor': "white", 'labelVisible': False, 'labelUnit': "angstrom", 'radiusScale': 1, 'opacity': 1, 'name': "link", 'side': "front", 'useCylinder': True } }] view._remote_call('setSize', target='Widget', args=['%dpx' % (xsize, ), '%dpx' % (ysize, )]) return view
def traj_view(t): view=nv.show_asetraj(t) view.clear_representations() view.add_ball_and_stick(aspectRatio=4) return view
def animate_structure( self, spacefill: bool = True, show_cell: bool = True, stride: int = 1, center_of_mass: bool = False, particle_size: float = 0.5, camera: str = "orthographic", atom_indices: Union[list, np.ndarray] = None, snapshot_indices: Union[list, np.ndarray] = None, repeat: Union[int, Tuple[int, int, int]] = None, ): """ Animates the job if a trajectory is present Args: spacefill (bool): If True, then atoms are visualized in spacefill stype show_cell (bool): True if the cell boundaries of the structure is to be shown stride (int): show animation every stride [::stride] use value >1 to make animation faster default=1 particle_size (float): Scaling factor for the spheres representing the atoms. (The radius is determined by the atomic number) center_of_mass (bool): False (default) if the specified positions are w.r.t. the origin camera (str): camera perspective, choose from "orthographic" or "perspective" atom_indices (list/numpy.ndarray): The atom indices for which the trajectory should be generated snapshot_indices (list/numpy.ndarray): The snapshots for which the trajectory should be generated repeat (int/3-tuple of int): Repeat the structures by this before animating Returns: animation: nglview IPython widget """ try: import nglview except ImportError: raise ImportError( "The animate() function requires the package nglview to be installed" ) if self.number_of_structures <= 1: raise ValueError("job must have more than one structure to animate!") traj = self.trajectory( stride=stride, center_of_mass=center_of_mass, atom_indices=atom_indices, snapshot_indices=snapshot_indices, ) if repeat is not None: traj = traj.transform(lambda s: s.repeat(repeat)) animation = nglview.show_asetraj(traj) if spacefill: animation.add_spacefill(radius_type="vdw", scale=0.5, radius=particle_size) animation.remove_ball_and_stick() else: animation.add_ball_and_stick() if show_cell: if self.structure.cell is not None: animation.add_unitcell() animation.camera = camera return animation
def traj_view(self): return nv.show_asetraj(self.trajectory)