Exemplo n.º 1
0
    def generate_2D_Slabs(b):
        global view, view_2, struc1, struc2, s1, s2, slabgen1, slabgen2, pressed
        pressed = 0
        struc1 = slabgen1.get_slabs()[SID1_slide.value].get_sorted_structure()
        s1 = build_ase_struc_2d(struc1)

        view = nglview.show_ase(s1)
        view.add_representation('unitcell')
        view.background = 'black'
        view.camera = "orthographic"

        struc2 = slabgen2.get_slabs()[SID2_slide.value].get_sorted_structure()
        s2 = build_ase_struc_2d(struc2)

        view_2 = nglview.show_ase(s2)
        view_2.add_representation('unitcell')
        view_2.background = 'black'
        view_2.camera = "orthographic"

        with output_1:
            output_1.clear_output()
            display(view)
            display(view_2)

        merge_slabs.disabled = False
        rep_interface.disabled = False
        down_interface.disabled = False
Exemplo n.º 2
0
    def get_3D_Structures(b):
        global view, view_2, struc1, struc2, s1, s2, pressed
        pressed = 0
        struc1 = a.get_structure_by_material_id(material_1.value)
        struc1 = SpacegroupAnalyzer(
            struc1).get_conventional_standard_structure()
        s1 = build_ase_struc_3d(struc1)
        view = nglview.show_ase(s1)
        view.add_representation('unitcell')
        view.background = 'black'
        view.camera = "orthographic"

        struc2 = a.get_structure_by_material_id(material_2.value)
        struc2 = SpacegroupAnalyzer(
            struc2).get_conventional_standard_structure()
        s2 = build_ase_struc_3d(struc2)
        view_2 = nglview.show_ase(s2)
        view_2.add_representation('unitcell')
        view_2.background = 'black'
        view_2.camera = "orthographic"

        with output_1:
            output_1.clear_output()
            display(view)
            display(view_2)

        list_interfaces.disabled = False
        rep_structures.disabled = False
        down_structures.disabled = False
Exemplo n.º 3
0
    def view_structure(self, snapshot=-1, spacefill=True, show_cell=True):
        """

        Args:
            snapshot (int): Snapshot of the trajectory one wants
            spacefill (bool):
            show_cell (bool):

        Returns:
            view: nglview IPython widget

        """
        import nglview

        atoms = self.get_structure(snapshot)
        picture = nglview.show_ase(atoms)
        if spacefill:
            picture.add_spacefill(radius_type="vdw", scale=0.5)
            picture.remove_ball_and_stick()
        else:
            picture.add_ball_and_stick()
        if show_cell:
            if atoms.cell is not None:
                picture.add_unitcell()
        return picture
Exemplo n.º 4
0
def nb_viz(doc, repeat=1, bonds=None):
    """ Return an ipywidget for nglview visualisation in
    a Jupyter notebook or otherwise.

    Parameters:
        doc (matador.crystal.Crystal / dict): matador document to show.

    Keyword arguments:
        repeat (int): number of periodic images to include.
        bonds (str): custom bond selection.

    """
    import nglview
    atoms = doc2ase(doc)
    atoms = atoms.repeat((repeat, repeat, repeat))
    view = nglview.show_ase(atoms)
    view.add_unitcell()
    view.remove_ball_and_stick()
    view.add_spacefill(radius_type='vdw', scale=0.3)
    if bonds is None:
        for elements in set(doc['atom_types']):
            view.add_ball_and_stick(selection='#{}'.format(elements.upper()))
    else:
        if not isinstance(bonds, list):
            bonds = [bonds]
        for bond in bonds:
            view.add_ball_and_stick(selection='#{}'.format(bond.upper()))
    view.parameters = {'clipDist': 0}
    view.camera = 'orthographic'
    view.background = '#FFFFFF'
    view.center()
    return view
Exemplo n.º 5
0
 def replicate_structures(b):
     global view, view_2, s1, s2
     s1 = s1.repeat((rep_x1.value, rep_y1.value, rep_z1.value))
     s2 = s2.repeat((rep_x2.value, rep_y2.value, rep_z2.value))
     view = nglview.show_ase(s1)
     view.add_representation('unitcell')
     view.background = 'black'
     view.camera = "orthographic"
     view_2 = nglview.show_ase(s2)
     view_2.add_representation('unitcell')
     view_2.background = 'black'
     view_2.camera = "orthographic"
     with output_1:
         output_1.clear_output()
         display(view)
         display(view_2)
    def plotConf(self):
        """ Plot configuration using nglview """

        v = nglview.show_ase(self.conf)
        v.add_representation("unitcell")
        boxy=widgets.Box([v],layout=self.box_layout)
        display(boxy)
 def plotEnv(self,myEnvironment):
     env_atom_types = np.asarray(self.conf.get_chemical_symbols())[myEnvironment.indeces.astype(int)] #,np.array('C')] #Template[env_number].myindex)]
     env_atom_types = np.append(env_atom_types,np.asarray(self.conf.get_chemical_symbols())[myEnvironment.myindex])
     env_positions = np.vstack((myEnvironment.delta*10,np.array([0,0,0]) ) )
     env = ase.Atoms(env_atom_types,env_positions)
     v = nglview.show_ase(env)
     boxy=widgets.Box([v],layout=self.box_layout)
     display(boxy)
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
 def replicate_interface(b):
     global view_3, s3
     s3 = s3.repeat((rep_x3.value, rep_y3.value, rep_z3.value))
     view_3 = nglview.show_ase(s3)
     view_3.add_representation('unitcell')
     view_3.background = 'black'
     view_3.camera = "orthographic"
     with output_1:
         output_1.clear_output()
         display(view_3)
Exemplo n.º 10
0
    def merge_2D_slabs(b):
        global view, view_2, struc1, struc2, s1, s2, slabgen1, slabgen2, s3, view_3, pressed
        pressed = 1
        a1_tmp = (s2.cell.lengths()[0] / (s1.cell.lengths()[0]))
        a2_tmp = (s2.cell.lengths()[1] / (s1.cell.lengths()[1]))
        a1 = 1
        b1 = 1
        a2 = 1
        b2 = 1
        if (a1_tmp >= 1):
            a1 = int(np.round(a1))
        else:
            b1 = int(np.round(1 / a1))

        if (a2_tmp >= 1):
            a2 = int(np.round(a1))
        else:
            b2 = int(np.round(1 / a1))

        s1 = s1.repeat((a1, a2, 1))
        s2 = s2.repeat((b1, b2, 1))

        if (substrate_slide.value == 1):
            cell_final = s1.cell.copy()
            fix_val = 0
        else:
            cell_final = s2.cell.copy()
            fix_val = 1

        vac = gap_slide.value / 2
        s1.center(vacuum=vac, axis=2)
        s2.center(vacuum=vac, axis=2)

        s3, s1_strain, s2_strain = stack(s1,
                                         s2,
                                         axis=2,
                                         fix=0,
                                         cell=cell_final,
                                         maxstrain=None,
                                         distance=None,
                                         output_strained=True)

        strain1 = np.sqrt(((s1_strain.cell - s1.cell).sum(axis=0)**2).sum())
        strain2 = np.sqrt(((s2_strain.cell - s2.cell).sum(axis=0)**2).sum())

        view_3 = nglview.show_ase(s3)
        view_3.add_representation('unitcell')
        view_3.background = 'black'
        view_3.camera = "orthographic"

        with output_1:
            output_1.clear_output()
            print("Strain on cell of Material 1 is", strain1)
            print("Strain on cell of Material 2 is", strain2)
            display(view_3)
Exemplo n.º 11
0
 def _plot3d_ase(
     self,
     spacefill=True,
     show_cell=True,
     camera="perspective",
     particle_size=0.5,
     background="white",
     color_scheme="element",
     show_axes=True,
 ):
     """
     Possible color schemes:
       " ", "picking", "random", "uniform", "atomindex", "residueindex",
       "chainindex", "modelindex", "sstruc", "element", "resname", "bfactor",
       "hydrophobicity", "value", "volume", "occupancy"
     Returns:
     """
     try:  # If the graphical packages are not available, the GUI will not work.
         import nglview
     except ImportError:
         raise ImportError(
             "The package nglview needs to be installed for the plot3d() function!"
         )
     # Always visualize the parent basis
     parent_basis = self._ref_atoms.get_parent_basis()
     view = nglview.show_ase(parent_basis)
     if spacefill:
         view.add_spacefill(radius_type="vdw",
                            color_scheme=color_scheme,
                            radius=particle_size)
         # view.add_spacefill(radius=1.0)
         view.remove_ball_and_stick()
     else:
         view.add_ball_and_stick()
     if show_cell:
         if parent_basis.cell is not None:
             if all(np.max(parent_basis.cell, axis=0) > 1e-2):
                 view.add_unitcell()
     if show_axes:
         view.shape.add_arrow([-2, -2, -2], [2, -2, -2], [1, 0, 0], 0.5)
         view.shape.add_arrow([-2, -2, -2], [-2, 2, -2], [0, 1, 0], 0.5)
         view.shape.add_arrow([-2, -2, -2], [-2, -2, 2], [0, 0, 1], 0.5)
     if camera != "perspective" and camera != "orthographic":
         print("Only perspective or orthographic is permitted")
         return None
     view.camera = camera
     view.background = background
     return view
Exemplo n.º 12
0
def show_atoms(atoms, dis=True):
    import nglview
    v = nglview.show_ase(atoms)
    v.clear_representations()
    v.add_unitcell()
    v.add_spacefill(radius_type='vdw',
                    radius_scale=0.5,
                    roughness=1,
                    metalness=0)

    v.parameters = dict(clipDist=-100, sampleLevel=2)
    v.control.spin([1, 0, 0], 3.14 * 1.5)
    if dis:
        display(v)
    else:
        return v
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
def ase_view(s, gui=False):
    view=nv.show_ase(s, gui=gui)
    view.clear_representations()
    view.add_ball_and_stick(aspectRatio=4)
    return view
Exemplo n.º 15
0
def test_show_ase():
    from ase import Atom, Atoms
    dimer = Atoms([Atom('X', (0, 0, 0)),
                   Atom('X', (0, 0, 1))])
    dimer.set_positions([(1, 2, 3), (4, 5, 6.2)])
    nv.show_ase(dimer)
Exemplo n.º 16
0
def test_show_ase():
    from ase import Atom, Atoms
    dimer = Atoms([Atom('X', (0, 0, 0)), Atom('X', (0, 0, 1))])
    dimer.set_positions([(1, 2, 3), (4, 5, 6.2)])
    nv.show_ase(dimer)
Exemplo n.º 17
0
Arquivo: io.py Projeto: ryokbys/nap
def get_nglview(nsys):
    """
    Retern a nglview object via ase_atoms.
    """
    import nglview as nv
    return nv.show_ase(nsys.to_ase_atoms())
# interact(f, x=10);

# +
# import nglview as np

# from nglview.datafiles import ASE_Traj

# ASE_Traj

# +
# import MDAnalysis as mda
import nglview as nv
from nglview.datafiles import PDB, XTC

# u = mda.Universe(PDB, XTC)

# protein = u.select_atoms('protein')

# +
# w = nv.ASEStructure(atoms)
# nv.ASEStructure?

# w
# -

nv.__version__

nv.show_ase(atoms)

nv.demo()
Exemplo n.º 19
0
    def visualize_MO(self, index, particle_size=0.5, show_bonds=True):
        '''
            Visualize the MO identified by its index.

            **Arguments**

            index       index of the MO, as listed by print_MO()

            particle_size
                        size of the atoms for visualization, lower value if orbital is too small to see

            show_bonds  connect atoms or not

            **Notes**

            This function should always be accompanied with the following commands (in a separate cell)

            view[1].update_surface(isolevel=1, color='blue', opacity=.3)
            view[2].update_surface(isolevel=-1, color='red', opacity=.3)

            This makes sure that the bonding and non-bonding MO's are plotted and makes them transparent
        '''
        n_MO = self.get('output/structure/dft/scf_density').shape[0]
        assert index >= 0 and index < n_MO
        assert len(
            self.get('output/structure/numbers')
        ) < 50  # check whether structure does not become too large for interactive calculation of cube file

        # print orbital information
        occ_alpha = int(
            self.get('output/structure/dft/n_alpha_electrons') > index)
        occ_beta = int(
            self.get('output/structure/dft/n_beta_electrons') > index)

        if self.get('output/structure/dft/beta_orbital_e') is None:
            orbital_energy = self.get(
                'output/structure/dft/alpha_orbital_e')[index]
            print("Orbital energy = {:>10.5f} \t Occ. = {}".format(
                orbital_energy, occ_alpha + occ_beta))
        else:
            orbital_energy = [
                self.get('output/structure/dft/alpha_orbital_e')[index],
                self.get('output/structure/dft/beta_orbital_e')[index]
            ]
            print(
                "Orbital energies (alpha,beta) = {:>10.5f},{:>10.5f} \t Occ. = {},{}"
                .format(orbital_energy[0], orbital_energy[1], occ_alpha,
                        occ_beta))

        # make cube file
        path = self.path + '_hdf5/' + self.name + '/input'
        out = subprocess.check_output(
            "ml load Gaussian/g16_E.01-intel-2019a;module use /apps/gent/CO7/haswell-ib/modules/all; cubegen 1 MO={} {}.fchk {}.cube"
            .format(index + 1, path, path),
            stderr=subprocess.STDOUT,
            universal_newlines=True,
            shell=True,
        )
        # visualize cube file
        try:
            import nglview
        except ImportError:
            raise ImportError(
                "The animate_nma_mode() function requires the package nglview to be installed"
            )

        atom_numbers = []
        atom_positions = []

        with open('{}.cube'.format(path), 'r') as f:
            for i in range(2):
                f.readline()
            n_atoms = int(f.readline().split()[0][1:])
            for i in range(3):
                f.readline()
            for n in range(n_atoms):
                line = f.readline().split()
                atom_numbers.append(int(line[0]))
                atom_positions.append(
                    np.array([float(m) for m in line[2:]]) / angstrom)

        structure = Atoms(numbers=np.array(atom_numbers),
                          positions=atom_positions)
        view = nglview.show_ase(structure)
        if not show_bonds:
            view.add_spacefill(radius_type='vdw',
                               scale=0.5,
                               radius=particle_size)
            view.remove_ball_and_stick()
        else:
            view.add_ball_and_stick()
        view.add_component('{}.cube'.format(path))
        view.add_component('{}.cube'.format(path))
        return view
Exemplo n.º 20
0
 def atom_view(self):
     return nv.show_ase(self.atoms)  #, gui=True)