Creates a Glycine residue
433192
def makeGly(segID, N, CA, C, O, geo):
    ''''''
    ##Create Residue Data Structure
    res= Residue((' ', segID, ' '), "GLY", '    ')

    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)

    ##print(res)
    return res
1315093
def _get_residue_mapping(self, chains_to_skip = set()):
        ''''''
        for c in self.representative_chains:
            # Skip specified chains
            if c not in chains_to_skip:
                if self.alignment.get(c):
                    uniparc_entry = self.get_uniparc_object(c)
                    sa = SequenceAligner()
                    sa.add_sequence(c, self.fasta[c])
                    sa.add_sequence(uniparc_entry.UniParcID, uniparc_entry.sequence)
                    sa.align()
                    residue_mapping, residue_match_mapping = sa.get_residue_mapping()

                    # Create a SequenceMap
                    s = PDBUniParcSequenceMap()
                    assert(sorted(residue_mapping.keys()) == sorted(residue_match_mapping.keys()))
                    for k, v in residue_mapping.iteritems():
                        s.add(k, (uniparc_entry.UniParcID, v), residue_match_mapping[k])
                    self.seqres_to_uniparc_sequence_maps[c] = s

                else:
                    self.seqres_to_uniparc_sequence_maps[c] = PDBUniParcSequenceMap()

        # Use the representatives' alignments for their respective equivalent classes. This saves memory as the same SequenceMap is used.
        for c_1, related_chains in self.equivalence_fiber.iteritems():
            for c_2 in related_chains:
                if self.seqres_to_uniparc_sequence_maps.get(c_1):
                    self.seqres_to_uniparc_sequence_maps[c_2] = self.seqres_to_uniparc_sequence_maps[c_1]
1167499
def CA_TRACE(residue):
    

    cg_residue = deepcopy(residue)

    for atom in cg_residue.child_dict.keys():
        if cg_residue[atom].name != 'CA':
            cg_residue.detach_child(cg_residue[atom].name)
    
    return cg_residue
1020826
@Override
    public void customize(IAtomContainer molecule, Object nodeToAdd) throws Exception {
        if (!(nodeToAdd instanceof CMLMolecule)) throw new CDKException("NodeToAdd must be of type nu.xom.Element!");

        //The nodeToAdd
        CMLMolecule molToCustomize = (CMLMolecule) nodeToAdd;

        if ((molecule instanceof MDMolecule)) {
            MDMolecule mdmol = (MDMolecule) molecule;
            molToCustomize.setConvention("md:mdMolecule");
            molToCustomize.addNamespaceDeclaration("md", "http://www.bioclipse.net/mdmolecule/");

            //Residues
            if (mdmol.getResidues().size() > 0) {
                Iterator it = mdmol.getResidues().iterator();
                while (it.hasNext()) {
                    Residue residue = (Residue) it.next();
                    int number = residue.getNumber();

                    CMLMolecule resMol = new CMLMolecule();
                    resMol.setDictRef("md:residue");
                    resMol.setTitle(residue.getName());

                    //Append resNo
                    CMLScalar residueNumber = new CMLScalar(number);
                    residueNumber.addAttribute(new Attribute("dictRef", "md:resNumber"));
                    resMol.addScalar(residueNumber);

                    // prefix for residue atom id
                    String rprefix = "r" + number;
                    //Append atoms
                    CMLAtomArray ar = new CMLAtomArray();
                    for (int i = 0; i < residue.getAtomCount(); i++) {
                        CMLAtom cmlAtom = new CMLAtom();
                        //            			System.out.println("atom ID: "+ residue.getAtom(i).getID());
                        //            			cmlAtom.addAttribute(new Attribute("ref", residue.getAtom(i).getID()));
                        // the next thing is better, but throws an exception
                        //
                        // setRef to keep consistent usage
                        // setId to satisfy Jumbo 54. need for all atoms to have id
                        cmlAtom.setRef(residue.getAtom(i).getID());
                        cmlAtom.setId(rprefix + "_" + residue.getAtom(i).getID());
                        ar.addAtom(cmlAtom);
                    }
                    resMol.addAtomArray(ar);

                    molToCustomize.appendChild(resMol);
                }
            }

            //Chargegroups
            if (mdmol.getChargeGroups().size() > 0) {
                Iterator it = mdmol.getChargeGroups().iterator();
                while (it.hasNext()) {
                    ChargeGroup chargeGroup = (ChargeGroup) it.next();
                    int number = chargeGroup.getNumber();

                    //FIXME: persist the ChargeGroup
                    CMLMolecule cgMol = new CMLMolecule();
                    cgMol.setDictRef("md:chargeGroup");
                    // etc: add name, refs to atoms etc

                    //Append chgrpNo
                    CMLScalar cgNo = new CMLScalar(number);
                    cgNo.addAttribute(new Attribute("dictRef", "md:cgNumber"));
                    cgMol.appendChild(cgNo);

                    // prefix for residue atom id
                    String cprefix = "cg" + number;

                    //Append atoms from chargeGroup as it is an AC
                    CMLAtomArray ar = new CMLAtomArray();
                    for (int i = 0; i < chargeGroup.getAtomCount(); i++) {
                        CMLAtom cmlAtom = new CMLAtom();
                        // setRef to keep consistent usage
                        // setId to satisfy Jumbo 5.4 need for all atoms to have id
                        cmlAtom.setRef(chargeGroup.getAtom(i).getID());
                        cmlAtom.setId(cprefix + "_" + chargeGroup.getAtom(i).getID());

                        //Append switching atom?
                        if (chargeGroup.getAtom(i).equals(chargeGroup.getSwitchingAtom())) {
                            CMLScalar scalar = new CMLScalar();
                            scalar.setDictRef("md:switchingAtom");
                            cmlAtom.addScalar(scalar);
                        }
                        ar.addAtom(cmlAtom);
                    }
                    cgMol.addAtomArray(ar);

                    molToCustomize.appendChild(cgMol);
                }
            }
        }
    }
1198016
def _set_residue_map(self):
        
        self.map_residue_to_mol = {}
        lookup = {}
        for idx, mol in enumerate(self.mols):
            if not mol.formula in lookup:
                mol.translate_sites(indices=range(len(mol)),
                                    vector=-mol.center_of_mass)
                lookup[mol.formula] = mol.copy()
            self.map_residue_to_mol["ml{}".format(idx + 1)] = lookup[mol.formula]
945140
public ResidueRangeAndLength trimToValidResidues(ResidueRange rr) {
		ResidueNumber start = rr.getStart();
		ResidueNumber end = rr.getEnd();
		String chain = rr.getChainName();
		// Add chainName
		if(start.getChainName() == null) {
			start = new ResidueNumber(chain,start.getSeqNum(),start.getInsCode());
		}
		if(end.getChainName() == null) {
			end = new ResidueNumber(chain,end.getSeqNum(),end.getInsCode());
		}
		// Check that start and end are present in the map.
		// If not, try to find the next valid residue
		// (terminal residues sometimes lack CA atoms, so they don't appear)
		Integer startIndex = getPosition(start);
		if( startIndex == null) {
			// Assume that the residue numbers are sequential
			// Find startIndex such that the SeqNum is bigger than start's seqNum
			for(ResidueNumber key :  treeMap.keySet()) {
				if( !key.getChainName().equals(chain) )
					continue;
				if( start.getSeqNum() <= key.getSeqNum() ) {
					start = key;
					startIndex = getPosition(key);
					break;
				}
			}
			if( startIndex == null ) {
				logger.error("Unable to find Residue {} in AtomPositionMap, and no plausible substitute.",start);
				return null;
			} else {
				logger.warn("Unable to find Residue {}, so substituting {}.",rr.getStart(),start);
			}
		}
		Integer endIndex = getPosition(end);
		if( endIndex == null) {
			// Assume that the residue numbers are sequential
			// Find startIndex such that the SeqNum is bigger than start's seqNum
			for(ResidueNumber key :  treeMap.descendingKeySet()) {
				if( !key.getChainName().equals(chain) )
					continue;
				Integer value = getPosition(key);
				if( value < startIndex ) {
					// start is before the end!
					break;
				}
				if( end.getSeqNum() >= key.getSeqNum() ) {
					end = key;
					endIndex = value;
					break;
				}
			}
			if( endIndex == null ) {
				logger.error("Unable to find Residue {} in AtomPositionMap, and no plausible substitute.",end);
				return null;
			} else {
				logger.warn("Unable to find Residue {}, so substituting {}.",rr.getEnd(),end);
			}
		}

		// now use those to calculate the length
		// if start or end is null, will throw NPE
		int length = getLength(startIndex, endIndex,chain);

		return new ResidueRangeAndLength(chain, start, end, length);
	}
123913
def find_charged(self, mol):
        """"""
        data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain')
        a_set = []
        # Iterate through all residue, exclude those in chains defined as peptides
        for res in [r for r in pybel.ob.OBResidueIter(mol.OBMol) if not r.GetChain() in config.PEPTIDES]:
            if config.INTRA is not None:
                if res.GetChain() != config.INTRA:
                    continue
            a_contributing = []
            a_contributing_orig_idx = []
            if res.GetName() in ('ARG', 'HIS', 'LYS'):  # Arginine, Histidine or Lysine have charged sidechains
                for a in pybel.ob.OBResidueAtomIter(res):
                    if a.GetType().startswith('N') and res.GetAtomProperty(a, 8) \
                            and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
                        a_contributing.append(pybel.Atom(a))
                        a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
                if not len(a_contributing) == 0:
                    a_set.append(data(atoms=a_contributing,
                                      atoms_orig_idx=a_contributing_orig_idx,
                                      type='positive',
                                      center=centroid([ac.coords for ac in a_contributing]),
                                      restype=res.GetName(),
                                      resnr=res.GetNum(),
                                      reschain=res.GetChain()))
            if res.GetName() in ('GLU', 'ASP'):  # Aspartic or Glutamic Acid
                for a in pybel.ob.OBResidueAtomIter(res):
                    if a.GetType().startswith('O') and res.GetAtomProperty(a, 8) \
                            and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
                        a_contributing.append(pybel.Atom(a))
                        a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
                if not len(a_contributing) == 0:
                    a_set.append(data(atoms=a_contributing,
                                      atoms_orig_idx=a_contributing_orig_idx,
                                      type='negative',
                                      center=centroid([ac.coords for ac in a_contributing]),
                                      restype=res.GetName(),
                                      resnr=res.GetNum(),
                                      reschain=res.GetChain()))
        return a_set
610845
def is_het_residue(self, obres):
        """"""
        if not obres.GetResidueProperty(0):
            # If the residue is NOT amino (0)
            # It can be amino_nucleo, coenzme, ion, nucleo, protein, purine, pyrimidine, solvent
            # In these cases, it is a ligand candidate
            return True
        else:
            # Here, the residue is classified as amino
            # Amino acids can still be ligands, so we check for HETATM entries
            # Only residues with at least one HETATM entry are processed as ligands
            het_atoms = []
            for atm in pybel.ob.OBResidueAtomIter(obres):
                het_atoms.append(obres.IsHetAtom(atm))
            if True in het_atoms:
                return True
        return False
417212
def make_table(self):
        """"""
        num_records = np.sum([1 for frame in self.timeseries])
        dtype = [("frame",float),("time",float),("ligand atom id",int),
                ("ligand atom name","|U4"),("cutoff",float),
                ("protein atom names",list),("protein atom ids",list),
                ("resid",int),("resname","|U4"),("segid","|U8") ]
        out = np.empty((num_records,),dtype=dtype)
        cursor=0
        for contact in self.timeseries:
            out[cursor] = (contact.frame, contact.time,contact.ligandatomindex,contact.ligandatomname,contact.cutoff,
                           contact.proteinatomname,contact.proteinatomindex,contact.resid,contact.resname,contact.segid)
            cursor+=1
        return out.view(np.recarray)
241380
private void recordUnidentifiableAtomLinkages(List<ModifiedCompound> modComps,
			List<Group> ligands) {

		// first put identified linkages in a map for fast query
		Set<StructureAtomLinkage> identifiedLinkages = new HashSet<StructureAtomLinkage>();
		for (ModifiedCompound mc : modComps) {
			identifiedLinkages.addAll(mc.getAtomLinkages());
		}

		// record
		// cross link
		int nRes = residues.size();
		for (int i=0; i<nRes-1; i++) {
			Group group1 = residues.get(i);
			for (int j=i+1; j<nRes; j++) {
				Group group2 = residues.get(j);
				List<Atom[]> linkages = StructureUtil.findAtomLinkages(
						group1, group2, true, bondLengthTolerance);
				for (Atom[] atoms : linkages) {
					StructureAtomLinkage link = StructureUtil.getStructureAtomLinkage(atoms[0],
							true, atoms[1], true);
					unidentifiableAtomLinkages.add(link);
				}
			}
		}

		// attachment
		int nLig = ligands.size();
		for (int i=0; i<nRes; i++) {
			Group group1 = residues.get(i);
			for (int j=0; j<nLig; j++) {
				Group group2 = ligands.get(j);
				if (group1.equals(group2)) { // overlap between residues and ligands
					continue;
				}
				List<Atom[]> linkages = StructureUtil.findAtomLinkages(
						group1, group2, false, bondLengthTolerance);
				for (Atom[] atoms : linkages) {
					StructureAtomLinkage link = StructureUtil.getStructureAtomLinkage(atoms[0],
							true, atoms[1], false);
					unidentifiableAtomLinkages.add(link);
				}
			}
		}
	}
1331152
def prune_structure_according_to_loops_file(self, loops_file_content, search_radius, expected_loop_length = None, generate_pymol_session = True):
        ''''''
        lf = LoopsFile(loops_file_content)
        assert(len(lf.data) == 1) # todo: remove

        # Extract the list of Residues defined in the loops file
        loop_residues = []
        for loop in lf.data:
            # Identify the Residues corresponding to the loops file definition
            start_id = str(loop['start'])
            end_id = str(loop['end'])
            start = []
            end = []
            for chain, chain_residues in self.residues.iteritems():
                for res, residue_object in chain_residues.iteritems():
                    if res.strip() == start_id:
                        start.append((chain, res, residue_object))
                    if res.strip() == end_id:
                        end.append((chain, res, residue_object))
            if len(start) != len(end) != 1:
                raise Exception('The PDB is ambiguous with respect to the loops file i.e. more than one PDB residue corresponds to the start or end residue defined in the loops file.')
            start, end = start[0], end[0]

            # We assume that the loops file identifies a range in document order
            loop_start = False
            for l in self.indexed_lines:
                if l[0] == 'ATOM' or l[0] == 'HETATM':
                    atom_residue = l[3].residue
                    if not loop_start:
                        if atom_residue == start[2]:
                            loop_start = True
                            if atom_residue not in loop_residues:
                                loop_residues.append(atom_residue)
                    else:
                        if atom_residue not in loop_residues:
                            loop_residues.append(atom_residue)
                        if atom_residue == end[2]:
                            break
        if expected_loop_length != None and expected_loop_length != len(loop_residues):
            raise Exception('Expected to identify {0} residues but {1} were identified.'.format(expected_loop_length, len(loop_residues)))

        # Determine the sidechain atoms to be removed
        sidechain_atom_serial_numbers = self.find_sidechain_atoms_within_radius_of_residue_objects(loop_residues, search_radius)

        # Determine the loop residue atoms to be removed
        loop_residues_ids = set()
        loop_atom_serial_numbers = set()
        for loop_residue in loop_residues:
            for aatom in loop_residue.get('ATOM'):
                loop_atom_serial_numbers.add(aatom.serial_number)
        assert(len(sidechain_atom_serial_numbers.intersection(loop_atom_serial_numbers)) == 0)

        return self.prune(loop_atom_serial_numbers, sidechain_atom_serial_numbers, generate_pymol_session = generate_pymol_session)
682772
def remove_isolated_residues(seq, len = 2)
      gap_starts = seq.to_enum(:scan, /(-\w{1,#{len}}-)/i).map { |_m| $`.size + 1 }
      # remove isolated residues
      gap_starts.each do |i|
        (i..i + len - 1).each { |j| seq[j] = '-' if isalpha(seq[j]) }
      end
      # remove isolated gaps
      res_starts = seq.to_enum(:scan, /([?\w]-{1,2}[?\w])/i).map { |_m| $`.size + 1 }
      res_starts.each do |i|
        (i..i + len - 1).each { |j| seq[j] = '?' if seq[j] == '-' }
      end
      seq
    end
968792
def getAtomLine(self, chain, resid):
        ''''''
        for line in self.lines:
            fieldtype = line[0:6].strip()
            assert(fieldtype == "ATOM" or fieldtype == "HETATM")
            if line[21:22] == chain and resid == line[22:27]:
                return line
        raise Exception("Could not find the ATOM/HETATM line corresponding to chain '%(chain)s' and residue '%(resid)s'." % vars())
794504
def makeAsp(segID, N, CA, C, O, geo):
    ''''''
    ##R-Group
    CA_CB_length=geo.CA_CB_length
    C_CA_CB_angle=geo.C_CA_CB_angle
    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle

    CB_CG_length=geo.CB_CG_length
    CA_CB_CG_angle=geo.CA_CB_CG_angle
    N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle

    CG_OD1_length=geo.CG_OD1_length
    CB_CG_OD1_angle=geo.CB_CG_OD1_angle
    CA_CB_CG_OD1_diangle=geo.CA_CB_CG_OD1_diangle

    CG_OD2_length=geo.CG_OD2_length
    CB_CG_OD2_angle=geo.CB_CG_OD2_angle
    CA_CB_CG_OD2_diangle=geo.CA_CB_CG_OD2_diangle

    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
    CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")
    carbon_g= calculateCoordinates(N, CA, CB, CB_CG_length, CA_CB_CG_angle, N_CA_CB_CG_diangle)
    CG= Atom("CG", carbon_g, 0.0, 1.0, " ", " CG", 0, "C")
    oxygen_d1= calculateCoordinates(CA, CB, CG, CG_OD1_length, CB_CG_OD1_angle, CA_CB_CG_OD1_diangle)
    OD1= Atom("OD1", oxygen_d1, 0.0, 1.0, " ", " OD1", 0, "O")
    oxygen_d2= calculateCoordinates(CA, CB, CG, CG_OD2_length, CB_CG_OD2_angle, CA_CB_CG_OD2_diangle)
    OD2= Atom("OD2", oxygen_d2, 0.0, 1.0, " ", " OD2", 0, "O")

    ##Create Residue Data Structure
    res= Residue((' ', segID, ' '), "ASP", '    ')
    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)
    res.add(CB)
    res.add(CG) 
    res.add(OD1)
    res.add(OD2)
    return res
601186
def makeSer(segID, N, CA, C, O, geo):
    ''''''
    ##R-Group
    CA_CB_length=geo.CA_CB_length
    C_CA_CB_angle=geo.C_CA_CB_angle
    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle

    CB_OG_length=geo.CB_OG_length
    CA_CB_OG_angle=geo.CA_CB_OG_angle
    N_CA_CB_OG_diangle=geo.N_CA_CB_OG_diangle
    
    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
    CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")
    oxygen_g= calculateCoordinates(N, CA, CB, CB_OG_length, CA_CB_OG_angle, N_CA_CB_OG_diangle)
    OG= Atom("OG", oxygen_g, 0.0, 1.0, " ", " OG", 0, "O")

    ##Create Reside Data Structure
    res= Residue((' ', segID, ' '), "SER", '    ')
    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)
    res.add(CB)
    res.add(OG)

    ##print(res)
    return res
1007605
def makeAla(segID, N, CA, C, O, geo):
    ''''''
    ##R-Group
    CA_CB_length=geo.CA_CB_length
    C_CA_CB_angle=geo.C_CA_CB_angle
    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle

    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
    CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")

    ##Create Residue Data Structure
    res = Residue((' ', segID, ' '), "ALA", '    ')
    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)
    res.add(CB)
    return res
877220
public static int[][] aaBondInfo() {

        if (aminoAcids == null) {
            createAAs();
        }

        int[][] info = new int[153][4];

        int counter = 0;
        int total = 0;
        for (int aa = 0; aa < aminoAcids.length; aa++) {
            AminoAcid acid = aminoAcids[aa];

            LOGGER.debug("#bonds for ", acid.getProperty(RESIDUE_NAME).toString(), " = " + acid.getBondCount());
            total += acid.getBondCount();
            LOGGER.debug("total #bonds: ", total);

            Iterator<IBond> bonds = acid.bonds().iterator();
            while (bonds.hasNext()) {
                IBond bond = (IBond) bonds.next();
                info[counter][0] = counter;
                info[counter][1] = acid.indexOf(bond.getBegin());
                info[counter][2] = acid.indexOf(bond.getEnd());
                info[counter][3] = bond.getOrder().numeric();
                counter++;
            }
        }

        if (counter > 153) {
            LOGGER.error("Error while creating AA info! Bond count is too large: ", counter);
            return null;
        }

        return info;
    }