Determines if a structure is a sulfide/polysulfide

    Args:
        structure (Structure): Input structure.

    Returns:
        (str) sulfide/polysulfide/sulfate
495610
def sulfide_type(structure):
    
    structure = structure.copy()
    structure.remove_oxidation_states()
    s = Element("S")
    comp = structure.composition
    if comp.is_element or s not in comp:
        return None

    finder = SpacegroupAnalyzer(structure, symprec=0.1)
    symm_structure = finder.get_symmetrized_structure()
    s_sites = [sites[0] for sites in symm_structure.equivalent_sites if
               sites[0].specie == s]

    def process_site(site):

        # in an exceptionally rare number of structures, the search
        # radius needs to be increased to find a neighbor atom
        search_radius = 4
        neighbors = []
        while len(neighbors) == 0:
            neighbors = structure.get_neighbors(site, search_radius)
            search_radius *= 2
            if search_radius > max(structure.lattice.abc)*2:
                break

        neighbors = sorted(neighbors, key=lambda n: n[1])
        nn, dist = neighbors[0]
        coord_elements = [site.specie for site, d in neighbors
                          if d < dist + 0.4][:4]
        avg_electroneg = np.mean([e.X for e in coord_elements])
        if avg_electroneg > s.X:
            return "sulfate"
        elif avg_electroneg == s.X and s in coord_elements:
            return "polysulfide"
        else:
            return "sulfide"

    types = set([process_site(site) for site in s_sites])
    if "sulfate" in types:
        return None
    elif "polysulfide" in types:
        return "polysulfide"
    else:
        return "sulfide"
1327400
function() {
    // check if we have at least one atom, if not return null
    if (this._currChain === null) {
      return null;
    }
    var chain = null;
    var i;
    for (i = 0; i < this._sheets.length; ++i) {
      var sheet = this._sheets[i];
      chain = this._structure.chain(sheet.chainName);
      if (chain) {
        chain.assignSS(sheet.first, sheet.last, 'E');
      }
    }
    for (i = 0; i < this._helices.length; ++i) {
      var helix = this._helices[i];
      chain = this._structure.chain(helix.chainName);
      if (chain) {
        chain.assignSS(helix.first, helix.last, 'H');
      }
    }
    this._structure.setAssemblies(this._remark350Reader.assemblies());
    if (this._options.conectRecords) {
      this._assignBondsFromConectRecords(this._structure);
    }
    this._structure.deriveConnectivity();
    console.log('imported', this._structure.chains().length, 'chain(s),',
                this._structure.residueCount(), 'residue(s)');
    var result = this._structure;
    this._structure = new mol.Mol();
    this._currChain =  null;
    this._currRes = null;
    this._currAtom = null;
    this._rosettaMode = false;
    return result;
  }
132468
def trans_v(self, structure):
        
        nsites = structure.num_sites
        volume = structure.volume
        natoms = structure.composition.num_atoms
        weight = float(structure.composition.weight)
        mass_density = 1.6605e3 * nsites * weight / (natoms * volume)
        if self.g_vrh < 0:
            raise ValueError("k_vrh or g_vrh is negative, "
                             "sound velocity is undefined")
        return (1e9 * self.g_vrh / mass_density) ** 0.5
481569
def get_structure_from_canonical_name(self, structure_name):
        
        return next((st for st in self.structures if st.canonical_name == structure_name), None)
37670
private boolean isSP2Bond(IBond bond) {
        return bond.getAtomCount() == 2 && bond.getBegin().getHybridization() == Hybridization.SP2
               && bond.getEnd().getHybridization() == Hybridization.SP2;
    }
87599
def get_ss_class(pdb_file, dssp_file, chain):
    
    prag = pr.parsePDB(pdb_file)
    pr.parseDSSP(dssp_file, prag)
    alpha, threeTen, beta = get_dssp_ss_content_multiplechains(prag, chain)

    if alpha == 0 and beta > 0:
        classification = 'all-beta'
    elif beta == 0 and alpha > 0:
        classification = 'all-alpha'
    elif beta == 0 and alpha == 0:
        classification = 'mixed'
    elif float(alpha) / beta >= 20:
        classification = 'all-alpha'
    else:
        classification = 'mixed'

    return classification
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
645129
def get_declaration(self):
        
        if self.is_opaque:
            out = "{strrep} = type opaque".format(strrep=str(self))
        else:
            out = "{strrep} = type {struct}".format(
                strrep=str(self), struct=self.structure_repr())
        return out
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)
100788
def serialise(structure):
    
    return ctypes.cast(
        ctypes.pointer(structure),
        ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)),
    ).contents
627217
def lStructIn(self):
        
        lStruct = []
        for k in self._dStruct['lorder']:
            k0, k1 = k.split('_')
            if type(self._dStruct['dObj'][k0][k1]) is str:
                if any([ss in self._dStruct['dObj'][k0][k1]
                        for ss in ['Ves','PlasmaDomain']]):
                    lStruct.append(self._dStruct['dObj'][k0][k1])
            elif issubclass(self._dStruct['dObj'][k0][k1].__class__, StructIn):
                lStruct.append(self._dStruct['dObj'][k0][k1])
        return lStruct
459765
def get_structure_from_name(self, structure_name):
        
        return next((st for st in self.structures if st.name == structure_name), None)
1174689
def as_protein(structure, filter_residues=True):
    

    from ssbio.biopython.Bio.Struct.Protein import Protein
    return Protein.from_structure(structure, filter_residues)
735422
def _validate_residue_types(self):
        ''''''

        for chain_id, sequence_map in self.rosetta_to_atom_sequence_maps.iteritems():
            rosetta_sequence = self.rosetta_sequences[chain_id]
            atom_sequence = self.atom_sequences[chain_id]
            for rosetta_id, atom_id, _ in sequence_map:
                assert(rosetta_sequence[rosetta_id].ResidueAA == atom_sequence[atom_id].ResidueAA)

        for chain_id, sequence_map in self.atom_to_seqres_sequence_maps.iteritems():
            atom_sequence = self.atom_sequences[chain_id]
            seqres_sequence = self.seqres_sequences[chain_id]
            for atom_id, seqres_id, _ in sorted(sequence_map):
                assert(atom_sequence[atom_id].ResidueAA == seqres_sequence[seqres_id].ResidueAA)

        for chain_id, sequence_map in self.seqres_to_uniparc_sequence_maps.iteritems():
            if self.pdb_chain_to_uniparc_chain_mapping.get(chain_id):
                seqres_sequence = self.seqres_sequences[chain_id]
                uniparc_sequence = self.uniparc_sequences[self.pdb_chain_to_uniparc_chain_mapping[chain_id]]
                for seqres_id, uniparc_id_resid_pair, substitution_match in sequence_map:
                    uniparc_id = uniparc_id_resid_pair[1]
                    # Some of the matches may not be identical but all the '*' Clustal Omega matches should be identical
                    if substitution_match and substitution_match.clustal == 1:
                        assert(seqres_sequence[seqres_id].ResidueAA == uniparc_sequence[uniparc_id].ResidueAA)
1235823
public Structure getStructureForCathDomain(StructureName structureName, CathDatabase cathInstall) throws IOException, StructureException {

		CathDomain cathDomain = cathInstall.getDomainByCathId(structureName.getIdentifier());

		Structure s = getStructureForPdbId(cathDomain.getIdentifier());
		Structure n = cathDomain.reduce(s);

		// add the ligands of the chain...

		Chain newChain = n.getPolyChainByPDB(structureName.getChainId());
		List<Chain> origChains = s.getNonPolyChainsByPDB(structureName.getChainId());
		for ( Chain origChain : origChains) {
			List<Group> ligands = origChain.getAtomGroups();

			for (Group g : ligands) {
				if (!newChain.getAtomGroups().contains(g)) {
					newChain.addGroup(g);
				}
			}
		}

		return n;
	}
992734
def _frame_structure_check(structure_description):
        

        standard_frame_structure = [LLDPDUChassisID.__name__,
                                    LLDPDUPortID.__name__,
                                    LLDPDUTimeToLive.__name__,
                                    '<...>',
                                    LLDPDUEndOfLLDPDU.__name__]

        if len(structure_description) < 4:
            raise LLDPInvalidFrameStructure(
                'Invalid frame structure.\ngot: {}\nexpected: '
                '{}'.format(' '.join(structure_description),
                            ' '.join(standard_frame_structure)))

        for idx, layer_name in enumerate(standard_frame_structure):

            if layer_name == '<...>':
                break
            if layer_name != structure_description[idx]:
                raise LLDPInvalidFrameStructure(
                    'Invalid frame structure.\ngot: {}\nexpected: '
                    '{}'.format(' '.join(structure_description),
                                ' '.join(standard_frame_structure)))

        if structure_description[-1] != standard_frame_structure[-1]:
            raise LLDPInvalidFrameStructure(
                'Invalid frame structure.\ngot: {}\nexpected: '
                '{}'.format(' '.join(structure_description),
                            ' '.join(standard_frame_structure)))
708830
def _relativise_files(self, structure):
        # type: (Dict[Any, Any]) -> None
        """"""
        # Base case - we found a File we need to update
        _logger.debug(u"[provenance] Relativising: %s", structure)

        if isinstance(structure, MutableMapping):
            if structure.get("class") == "File":
                relative_path = None
                if "checksum" in structure:
                    alg, checksum = structure["checksum"].split("$")
                    if alg != SHA1:
                        raise TypeError(
                            "Only SHA1 CWL checksums are currently supported: "
                            "{}".format(structure))
                    if self.has_data_file(checksum):
                        prefix = checksum[0:2]
                        relative_path = posixpath.join(
                            "data", prefix, checksum)

                if not relative_path is not None and "location" in structure:
                    # Register in RO; but why was this not picked
                    # up by used_artefacts?
                    _logger.info("[provenance] Adding to RO %s", structure["location"])
                    fsaccess = StdFsAccess("")
                    with fsaccess.open(structure["location"], "rb") as fp:
                        relative_path = self.add_data_file(fp)
                        checksum = posixpath.basename(relative_path)
                        structure["checksum"] = "%s$%s" % (SHA1, checksum)
                if relative_path is not None:
                    # RO-relative path as new location
                    structure["location"] = posixpath.join("..", relative_path)
                else:
                    _logger.warning("Could not determine RO path for file %s", structure)
                if "path" in structure:
                    del structure["path"]

            if structure.get("class") == "Directory":
                # TODO: Generate anonymoys Directory with a "listing"
                # pointing to the hashed files
                del structure["location"]

            for val in structure.values():
                self._relativise_files(val)
            return

        if isinstance(structure, (str, Text)):
            # Just a string value, no need to iterate further
            return
        try:
            for obj in iter(structure):
                # Recurse and rewrite any nested File objects
                self._relativise_files(obj)
        except TypeError:
            pass