Returns pymatgen structure from ASE Atoms.

        Args:
            atoms: ASE Atoms object
            cls: The Structure class to instantiate (defaults to pymatgen structure)

        Returns:
            Equivalent pymatgen.core.structure.Structure
344895
def get_structure(atoms, cls=None):
        
        symbols = atoms.get_chemical_symbols()
        positions = atoms.get_positions()
        lattice = atoms.get_cell()

        cls = Structure if cls is None else cls
        return cls(lattice, symbols, positions,
                   coords_are_cartesian=True)
1174689
def as_protein(structure, filter_residues=True):
    

    from ssbio.biopython.Bio.Struct.Protein import Protein
    return Protein.from_structure(structure, filter_residues)
938575
public static final Atom[] getAtomArray(Atom[] ca,List<Group> hetatms ) throws StructureException{
		List<Atom> atoms = new ArrayList<Atom>();
		Collections.addAll(atoms, ca);

		logger.debug("got {} hetatoms", hetatms.size());

		// we only add atom nr 1, since the getAlignedStructure method actually adds the parent group, and not the atoms...
		for (Group g : hetatms){
			if (g.size() < 1)
				continue;
			//if (debug)
			//   System.out.println("adding group " + g);
			Atom a = g.getAtom(0);
			//if (debug)
			//  System.out.println(a);
			a.setGroup(g);
			atoms.add(a);
		}

		Atom[] arr = atoms.toArray(new Atom[atoms.size()]);

		return arr;
	}
1134174
def from_ast(
        pyast_node, node=None, node_cls=None, Node=Node,
        iter_fields=ast.iter_fields, AST=ast.AST):
    '''
    '''
    node_cls = node_cls or Node
    node = node or node_cls()
    name = pyast_node.__class__.__name__

    attrs = []
    for field, value in iter_fields(pyast_node):
        if name == 'Dict':
            for key, value in zip(pyast_node.keys, pyast_node.values):
                if isinstance(value, list):
                    for item in value:
                        if isinstance(item, AST):
                            value = from_ast(item)
                elif isinstance(value, AST):
                    value = from_ast(value)
                attrs.append((key.s, value))
        else:
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, AST):
                        value = from_ast(item)
            elif isinstance(value, AST):
                value = from_ast(value)
            attrs.append((field, value))
    node.update(attrs, type=name)
    return node
162160
public static List<AtomSite> convertStructureToAtomSites(Structure s) {
		List<AtomSite> list = new ArrayList<AtomSite>();

		for (int m=0;m<s.nrModels();m++) {
			for (Chain c:s.getChains(m)) {
				list.addAll(convertChainToAtomSites(c, m+1, c.getName(), c.getId()));
			}
		}
		return list;
	}
934394
def atoms_order(self):
        
        if not len(self):  # for empty containers
            return {}
        elif len(self) == 1:  # optimize single atom containers
            return dict.fromkeys(self, 2)

        params = {n: (int(node), tuple(sorted(int(edge) for edge in self._adj[n].values())))
                  for n, node in self.atoms()}
        newlevels = {}
        countprime = iter(primes)
        weights = {x: newlevels.get(y) or newlevels.setdefault(y, next(countprime))
                   for x, y in sorted(params.items(), key=itemgetter(1))}

        tries = len(self) * 4

        numb = len(set(weights.values()))
        stab = 0

        while tries:
            oldnumb = numb
            neweights = {}
            countprime = iter(primes)

            # weights[n] ** 2 NEED for differentiation of molecules like A-B or any other complete graphs.
            tmp = {n: reduce(mul, (weights[x] for x in m), weights[n] ** 2) for n, m in self._adj.items()}

            weights = {x: (neweights.get(y) or neweights.setdefault(y, next(countprime)))
                       for x, y in sorted(tmp.items(), key=itemgetter(1))}

            numb = len(set(weights.values()))
            if numb == len(self):  # each atom now unique
                break
            elif numb == oldnumb:
                x = Counter(weights.values())
                if x[min(x)] > 1:
                    if stab == 3:
                        break
                elif stab >= 2:
                    break

                stab += 1
            elif stab:
                stab = 0

            tries -= 1
            if not tries and numb < oldnumb:
                warning('morgan. number of attempts exceeded. uniqueness has decreased. next attempt will be made')
                tries = 1
        else:
            warning('morgan. number of attempts exceeded')

        return weights
1334276
def get_atom(value):
    
    atom = Atom()
    if value and value[0] in CFWS_LEADER:
        token, value = get_cfws(value)
        atom.append(token)
    if value and value[0] in ATOM_ENDS:
        raise errors.HeaderParseError(
            "expected atom but found '{}'".format(value))
    token, value = get_atext(value)
    atom.append(token)
    if value and value[0] in CFWS_LEADER:
        token, value = get_cfws(value)
        atom.append(token)
    return atom, value
481849
def get_atom_coltype(self, kind=None):
        
        if kind is None:
            kind = self.kind
        if self.kind.startswith('uint'):
            col_name = "UInt{name}Col".format(name=kind[4:])
        else:
            col_name = "{name}Col".format(name=kind.capitalize())

        return getattr(_tables(), col_name)
929538
def _get_atomsection(mol2_lst):
        """"""
        started = False
        for idx, s in enumerate(mol2_lst):
            if s.startswith('@<TRIPOS>ATOM'):
                first_idx = idx + 1
                started = True
            elif started and s.startswith('@<TRIPOS>'):
                last_idx_plus1 = idx
                break
        return mol2_lst[first_idx:last_idx_plus1]
1350411
def add_atom(self, atom, _map=None):
        
        if _map is None:
            _map = max(self, default=0) + 1
        elif _map in self._node:
            raise KeyError('atom with same number exists')

        attr_dict = self.node_attr_dict_factory()
        if isinstance(atom, str):
            attr_dict.element = atom
        elif isinstance(atom, int):
            attr_dict.element = elements_list[atom - 1]
        else:
            attr_dict.update(atom)

        self._adj[_map] = self.adjlist_inner_dict_factory()
        self._node[_map] = attr_dict
        self.flush_cache()
        return _map
414163
def generate_pymol_session(self, pymol_executable = 'pymol', settings = {}):
        ''' '''

        if not self.fixed:
            self.fix()

        b = BatchBuilder(pymol_executable = pymol_executable)

        for s in self.structures:
            s.add_residues_of_interest(self.get_differing_atom_residue_ids(s.structure_name))

        PSE_files = b.run(MultiStructureBuilder, [self.structures], settings = settings)

        return PSE_files[0], b.PSE_scripts[0]
962047
def structure(self, instance, client=None):
        '''
        '''
        struct = self.struct_map.get(instance._meta.name)
        if struct is None:
            raise ModelNotAvailable('"%s" is not available for backend '
                                    '"%s"' % (instance._meta.name, self))
        client = client if client is not None else self.client
        return struct(instance, self, client)
1284920
def _format_ase2clusgeo(obj, all_atomtypes=None):
    
    #atoms metadata
    totalAN = len(obj)
    if all_atomtypes is not None:
        atomtype_set = set(all_atomtypes)
    else:
        atomtype_set = set(obj.get_atomic_numbers())

    atomtype_lst = np.sort(list(atomtype_set))
    n_atoms_per_type_lst = []
    pos_lst = []
    for atomtype in atomtype_lst:
        condition = obj.get_atomic_numbers() == atomtype
        pos_onetype = obj.get_positions()[condition]
        n_onetype = pos_onetype.shape[0]

        # store data in lists
        pos_lst.append(pos_onetype)
        n_atoms_per_type_lst.append(n_onetype)

    typeNs = n_atoms_per_type_lst
    Ntypes = len(n_atoms_per_type_lst)
    atomtype_lst
    Apos = np.concatenate(pos_lst).ravel()
    return Apos, typeNs, Ntypes, atomtype_lst, totalAN
189291
def from_structure(structure):
    

    try:
        from Bio import PDB
        if isinstance(structure, str):
            p = PDB.PDBParser()
            structure = p.get_structure('S', structure)
        if isinstance(structure, PDB.Structure.Structure):
            for _ in structure.get_chains():
                atoms = [np.array(atom.get_coord())
                         for atom in structure.get_atoms()]
    except ImportError:
        print("Biopython not found.")
        raise

    atoms = np.array(structure)
    try:
        import scipy
        D = scipy.spatial.distance.pdist(atoms, 'euclidean')
        D = scipy.spatial.distance.squareform(D)
    except ImportError:
        print("Scipy not found.")
        raise
    m = np.max(1 / D[D != 0])
    M = np.zeros(D.shape)
    M[D != 0] = 1 / D[D != 0]
    M[D == 0] = m
    return M
1171918
public static Atom[] getRepresentativeAtoms(Structure structure) {

		if (structure.isNmr())
			return StructureTools.getRepresentativeAtomArray(structure);

		else {

			// Get Atoms of all models
			List<Atom> atomList = new ArrayList<Atom>();
			for (int m = 0; m < structure.nrModels(); m++) {
				for (Chain c : structure.getModel(m))
					atomList.addAll(Arrays.asList(StructureTools
							.getRepresentativeAtomArray(c)));
			}
			return atomList.toArray(new Atom[0]);
		}

	}
148729
def structure_to_abivars(structure, **kwargs):
    
    if not structure.is_ordered:
        raise ValueError("""\
Received disordered structure with partial occupancies that cannot be converted into an Abinit input
Please use OrderDisorderedStructureTransformation or EnumerateStructureTransformation
to build an appropriate supercell from partial occupancies or alternatively use the Virtual Crystal Approximation.""")

    types_of_specie = structure.types_of_specie
    natom = structure.num_sites

    znucl_type = [specie.number for specie in types_of_specie]
    znucl_atoms = structure.atomic_numbers

    typat = np.zeros(natom, np.int)
    for atm_idx, site in enumerate(structure):
        typat[atm_idx] = types_of_specie.index(site.specie) + 1

    rprim = ArrayWithUnit(structure.lattice.matrix, "ang").to("bohr")
    angdeg = structure.lattice.angles
    xred = np.reshape([site.frac_coords for site in structure], (-1, 3))

    # Set small values to zero. This usually happens when the CIF file
    # does not give structure parameters with enough digits.
    rprim = np.where(np.abs(rprim) > 1e-8, rprim, 0.0)
    xred = np.where(np.abs(xred) > 1e-8, xred, 0.0)

    # Info on atoms.
    d = dict(
        natom=natom,
        ntypat=len(types_of_specie),
        typat=typat,
        znucl=znucl_type,
        xred=xred,
    )

    # Add info on the lattice.
    # Should we use (rprim, acell) or (angdeg, acell) to specify the lattice?
    geomode = kwargs.pop("geomode", "rprim")
    if geomode == "automatic":
        geomode = "rprim"
        if structure.lattice.is_hexagonal: # or structure.lattice.is_rhombohedral
            geomode = "angdeg"
            angdeg = structure.lattice.angles
            # Here one could polish a bit the numerical values if they are not exact.
            # Note that in pmg the angles are 12, 20, 01 while in Abinit 12, 02, 01
            # One should make sure that the orientation is preserved (see Curtarolo's settings)

    if geomode == "rprim":
        d.update(
            acell=3 * [1.0],
            rprim=rprim,
        )

    elif geomode == "angdeg":
        d.update(
            acell=ArrayWithUnit(structure.lattice.abc, "ang").to("bohr"),
            angdeg=angdeg,
        )
    else:
        raise ValueError("Wrong value for geomode: %s" % geomode)

    return d
1116026
def create_single_structure_pse(structure_name, structure_content, residue_ids_of_interest, pymol_executable = 'pymol', settings = {}):
    ''' '''
    b = BatchBuilder(pymol_executable = pymol_executable)
    PSE_files = b.run(SingleStructureBuilder, [{structure_name : PDBContainer(structure_name, structure_content, residue_ids_of_interest)}], settings = settings)
    return PSE_files[0], b.PSE_scripts[0]