get the position of PDB residue nr X in the ato marray

@param pdbresnum pdbresidue number
@param authId chain name
@param atoms atom array
@return
332217
private static int getPositionForPDBresunm(String pdbresnum, String authId , Atom[] atoms){
		ResidueNumber residueNumber =  ResidueNumber.fromString(pdbresnum);
		residueNumber.setChainName(authId);

		boolean blankChain = authId == null || authId.equalsIgnoreCase("null") || authId.equals("_");

		for ( int i =0; i< atoms.length ;i++){
			Group g = atoms[i].getGroup();

			// match _ to any chain
			if( blankChain ) {
				residueNumber.setChainName(g.getChain().getName());
			}

			//System.out.println(g.getResidueNumber() + "< ? >" + residueNumber +"<");
			if ( g.getResidueNumber().equals(residueNumber)){
				//System.out.println(g + " == " + residueNumber );
				Chain c = g.getChain();
				if ( blankChain || c.getName().equals(authId)){
					return i;
				}
			}
		}
		return -1;
	}
318945
public IAtom getUnplacedRingHeavyAtom(IAtomContainer molecule, IAtom atom) {
        List<IBond> bonds = molecule.getConnectedBondsList(atom);
        IAtom connectedAtom = null;
        for (IBond bond : bonds) {
            connectedAtom = bond.getOther(atom);
            if (isUnplacedHeavyAtom(connectedAtom) && connectedAtom.getFlag(CDKConstants.ISINRING)) {
                return connectedAtom;
            }
        }
        return connectedAtom;
    }
374965
def proc_line_coordinate(self, line):
        """"""
        pdb_atom_col_dict = global_settings['ampal']['pdb_atom_col_dict']
        at_type = line[0:6].strip()  # 0
        at_ser = int(line[6:11].strip())  # 1
        at_name = line[12:16].strip()  # 2
        alt_loc = line[16].strip()  # 3
        res_name = line[17:20].strip()  # 4
        chain_id = line[21].strip()  # 5
        res_seq = int(line[22:26].strip())  # 6
        i_code = line[26].strip()  # 7
        x = float(line[30:38].strip())  # 8
        y = float(line[38:46].strip())  # 9
        z = float(line[46:54].strip())  # 10
        occupancy = float(line[54:60].strip())  # 11
        temp_factor = float(line[60:66].strip())  # 12
        element = line[76:78].strip()  # 13
        charge = line[78:80].strip()  # 14
        if at_name not in pdb_atom_col_dict:
            pdb_atom_col_dict[at_name] = line[12:16]
            pdb_col_e = PDBColFormat(atom_name=at_name, atom_col=line[12:16])
            ampal_data_session.add(pdb_col_e)
            self.new_labels = True
        return (at_type, at_ser, at_name, alt_loc, res_name, chain_id, res_seq,
                i_code, x, y, z, occupancy, temp_factor, element, charge)
233608
def write_pdb(self, mol, filename, name=None, num=None):
        

        # ugly hack to get around the openbabel issues with inconsistent
        # residue labelling.
        scratch = tempfile.gettempdir()
        with ScratchDir(scratch, copy_to_current_on_exit=False) as _:
            mol.to(fmt="pdb", filename="tmp.pdb")
            bma = BabelMolAdaptor.from_file("tmp.pdb", "pdb")

        num = num or 1
        name = name or "ml{}".format(num)

        # bma = BabelMolAdaptor(mol)
        pbm = pb.Molecule(bma._obmol)
        for i, x in enumerate(pbm.residues):
            x.OBResidue.SetName(name)
            x.OBResidue.SetNum(num)

        pbm.write(format="pdb", filename=filename, overwrite=True)
1038882
def check_residues(self):
        ''''''
        for chain, residue_ids in self.residues.iteritems():
            for residue_id, residue in residue_ids.iteritems():
                for record_type, atoms in residue.records.iteritems():
                    freq = {}
                    for atom in atoms:
                        rec_id = atom.name + atom.conformation
                        freq[rec_id] = freq.get(rec_id, 0)
                        freq[rec_id] += 1
                    for atom_type, count in freq.items():
                        if count > 1:
                            raise Exception('{0} occurrences of atom type {1} for record type {2} occur in residue {3} in chain {4}.'.format(count, atom_type, record_type, residue_id.strip(), chain))
1365662
public static Point3d[] atomsToPoints(Atom[] atoms) {
		Point3d[] points = new Point3d[atoms.length];
		for(int i = 0; i< atoms.length;i++) {
			points[i] = atoms[i].getCoordsAsPoint3d();
		}
		return points;
	}
36986
private static AFPChain partitionAFPchain(AFPChain afpChain,
			Atom[] ca1, Atom[] ca2, int order) throws StructureException{

		int[][][] newAlgn = new int[order][][];
		int repeatLen = afpChain.getOptLength()/order;

		//Extract all the residues considered in the first chain of the alignment
		List<Integer> alignedRes = new ArrayList<Integer>();
		for (int su=0; su<afpChain.getBlockNum(); su++){
			for (int i=0; i<afpChain.getOptLen()[su]; i++){
				alignedRes.add(afpChain.getOptAln()[su][0][i]);
			}
		}

		//Build the new alignment
		for (int su=0; su<order; su++){
			newAlgn[su] = new int[2][];
			newAlgn[su][0] = new  int[repeatLen];
			newAlgn[su][1] = new  int[repeatLen];
			for (int i=0; i<repeatLen; i++){
				newAlgn[su][0][i] = alignedRes.get(repeatLen*su+i);
				newAlgn[su][1][i] = alignedRes.get(
						(repeatLen*(su+1)+i)%alignedRes.size());
			}
		}

		return AlignmentTools.replaceOptAln(newAlgn, afpChain, ca1, ca2);
	}
447386
private int getPiSystemsCount(IAtomContainer ac, IAtom atom) {
        List neighbours = ac.getConnectedAtomsList(atom);
        int picounter = 0;
        List bonds = null;
        for (int i = 0; i < neighbours.size(); i++) {
            IAtom neighbour = (IAtom) neighbours.get(i);
            bonds = ac.getConnectedBondsList(neighbour);
            for (int j = 0; j < bonds.size(); j++) {
                IBond bond = (IBond) bonds.get(j);
                if (bond.getOrder() != IBond.Order.SINGLE && !bond.getOther(neighbour).equals(atom)
                        && !neighbour.getSymbol().equals("P") && !neighbour.getSymbol().equals("S")) {
                    picounter += 1;
                }/*
                  * else if (bonds[j].getOther(neighbours[i])!=atom &&
                  * !neighbours[i].getSymbol().equals("P") &&
                  * !neighbours[i].getSymbol().equals("S") &&
                  * bonds[j].getOther
                  * (neighbours[i]).getFlag(CDKConstants.ISAROMATIC)){ picounter
                  * += 1; }
                  */
            }
        }
        return picounter;
    }
1019199
def get_atom_mapping(self):
        """"""
        # Atom mappings
        smiles_to_pdb_mapping = self.bindingsite.xpath('mappings/smiles_to_pdb/text()')
        if smiles_to_pdb_mapping == []:
            self.mappings = {'smiles_to_pdb': None, 'pdb_to_smiles': None}
        else:
            smiles_to_pdb_mapping = {int(y[0]): int(y[1]) for y in [x.split(':')
                                                                    for x in smiles_to_pdb_mapping[0].split(',')]}
            self.mappings = {'smiles_to_pdb': smiles_to_pdb_mapping}
            self.mappings['pdb_to_smiles'] = {v: k for k, v in self.mappings['smiles_to_pdb'].items()}
573931
private int getHalogenCount(IAtomContainer ac, IAtom atom) {
        List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
        int acounter = 0;
        for (IAtom neighbour : neighbours) {
            if (neighbour.getSymbol().equals("F") || neighbour.getSymbol().equals("I")
                    || neighbour.getSymbol().equals("Cl") || neighbour.getSymbol().equals("Br")) {
                acounter += 1;
            }
        }
        return acounter;
    }
765816
def getAtomLinesForResidueInRosettaStructure(self, resid):
        ''''''
        lines = [line for line in self.lines if line[0:4] == "ATOM" and resid == int(line[22:27])]
        if not lines:
            #print('Failed searching for residue %d.' % resid)
            #print("".join([line for line in self.lines if line[0:4] == "ATOM"]))
            raise Exception("Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'." % vars())
        return lines
44709
public IAtom getNextPlacedHeavyAtomWithUnplacedAliphaticNeighbour(IAtomContainer molecule) {
        Iterator<IBond> bonds = molecule.bonds().iterator();
        while (bonds.hasNext()) {
            IBond bond = bonds.next();
            IAtom atom0 = bond.getBegin();
            IAtom atom1 = bond.getEnd();
            if (atom0.getFlag(CDKConstants.ISPLACED) && !(atom1.getFlag(CDKConstants.ISPLACED))) {
                if (isAliphaticHeavyAtom(atom1) && isHeavyAtom(atom0)) {
                    return atom0;
                }
            }
            if (atom1.getFlag(CDKConstants.ISPLACED) && !(atom0.getFlag(CDKConstants.ISPLACED))) {
                if (isAliphaticHeavyAtom(atom0) && isHeavyAtom(atom1)) {
                    return atom1;
                }
            }
        }
        return null;
    }
1307352
def whichresnumber(atom):
    """"""
    atom = atom if not isinstance(atom, Atom) else atom.OBAtom  # Convert to OpenBabel Atom
    return atom.GetResidue().GetNum() if atom.GetResidue() is not None else None
150800
def _get_SEQRES_sequences(self):
        ''''''

        pdb_id = self.get_pdb_id()
        SEQRES_lines = self.parsed_lines["SEQRES"]

        modified_residue_mapping_3 = self.modified_residue_mapping_3
        # I commented this out since we do not need it for my current test cases
        #for k, v in self.modified_residues.iteritems():
        #    assert(v['modified_residue'] not in modified_residues)
        #    modified_residues[v['modified_residue']] = v['original_residue_3']

        for x in range(0, len(SEQRES_lines)):
            assert(SEQRES_lines[x][7:10].strip().isdigit())

        if not SEQRES_lines:
            #colortext.warning("WARNING: No SEQRES records were found. Kyle is trying to handle this gracefully, but Shane may need to fix it")
            return

        seqres_chain_order = []
        SEQRES_lines = [line[11:].rstrip() for line in SEQRES_lines] # we cannot strip the left characters as some cases e.g. 2MBP are missing chain identifiers

        # Collect all residues for all chains, remembering the chain order
        chain_tokens = {}
        for line in SEQRES_lines:
            chainID = line[0]
            if missing_chain_ids.get(self.pdb_id):
                chainID = missing_chain_ids[self.pdb_id]
            if chainID not in seqres_chain_order:
                seqres_chain_order.append(chainID)
            chain_tokens[chainID] = chain_tokens.get(chainID, [])
            chain_tokens[chainID].extend(line[6:].strip().split())

        sequences = {}
        self.chain_types = {}

        canonical_acid_types = set(residue_type_3to1_map.keys())
        canonical_acid_types.remove('UNK')
        assert(len(canonical_acid_types) == 20)

        for chain_id, tokens in chain_tokens.iteritems():

            # Determine whether the chain is DNA, RNA, or a protein chain
            # 1H38 is a good test for this - it contains DNA (chains E and G and repeated by H, K, N, J, M, P), RNA (chain F, repeated by I, L, O) and protein (chain D, repeated by A,B,C) sequences
            # 1ZC8 is similar but also has examples of DU
            # 4IHY has examples of DI (I is inosine)
            # 2GRB has RNA examples of I and U
            # 1LRP has protein chains with only CA atoms
            # This will throw an exception when a non-canonical is found which is not listed in basics.py. In that case, the list in basics.py should be updated.

            chain_type = None
            set_of_tokens = set(tokens)
            if (set_of_tokens.union(all_recognized_dna) == all_recognized_dna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'DNA'
            elif (set_of_tokens.union(all_recognized_rna) == all_recognized_rna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'RNA'
            elif len(set_of_tokens) == 1 and 'UNK' in set_of_tokens:
                chain_type = 'Unknown'
            elif not(set_of_tokens.intersection(canonical_acid_types)):
                # Zero canonical residues may imply a ligand or a heterogen chain
                chain_type = PDB._determine_heterogen_chain_type(set_of_tokens)
            else:
                assert(len(set(tokens).intersection(dna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                chain_type = 'Protein'
                if not self.chain_atoms.get(chain_id):
                    # possible for biological unit files
                    continue
                if self.chain_atoms[chain_id] == set(['CA']):
                    chain_type = 'Protein skeleton'

            # Get the sequence, mapping non-canonicals to the appropriate letter
            self.chain_types[chain_id] = chain_type

            sequence = []
            if chain_type == 'DNA':
                for r in tokens:
                    if dna_nucleotides_2to1_map.get(r):
                        sequence.append(dna_nucleotides_2to1_map[r])
                    else:
                        if non_canonical_dna.get(r):
                            sequence.append(non_canonical_dna[r])
                        else:
                            raise Exception("Unknown DNA residue %s." % r)
            elif chain_type == 'RNA':
                for r in tokens:
                    if r in rna_nucleotides:
                        sequence.append(r)
                    else:
                        if non_canonical_rna.get(r):
                            sequence.append(non_canonical_rna[r])
                        else:
                            raise Exception("Unknown RNA residue %s." % r)
            else:
                token_counter = 0
                for r in tokens:
                    token_counter += 1
                    if residue_type_3to1_map.get(r):
                        sequence.append(residue_type_3to1_map[r])
                    else:

                        if self.modified_residue_mapping_3.get(r):
                            sequence.append(residue_type_3to1_map[self.modified_residue_mapping_3.get(r)])
                        elif non_canonical_amino_acids.get(r):
                            #print('Mapping non-canonical residue %s to %s.' % (r, non_canonical_amino_acids[r]))
                            #print(SEQRES_lines)
                            #print(line)
                            sequence.append(non_canonical_amino_acids[r])
                        elif r == 'UNK':
                            continue
                        # Skip these residues
                        elif r == 'ACE' and token_counter == 1:
                            # Always allow ACE as the first residue of a chain
                            sequence.append('X')
                        elif r == 'ACE' and pdb_id in cases_with_ACE_residues_we_can_ignore:
                            sequence.append('X')
                            #continue
                        # End of skipped residues
                        else:
                            #print(modified_residue_mapping_3)
                            if modified_residue_mapping_3.get(r):
                                if modified_residue_mapping_3[r] == 'UNK':
                                    sequence.append('X')
                                else:
                                    assert(modified_residue_mapping_3[r] in residue_types_3)
                                    sequence.append(residue_type_3to1_map[modified_residue_mapping_3[r]])
                            else:
                                raise Exception("Unknown protein residue %s in chain %s." % (r, chain_id))
            sequences[chain_id] = "".join(sequence)

        self.seqres_chain_order = seqres_chain_order

        # Create Sequence objects for the SEQRES sequences
        for chain_id, sequence in sequences.iteritems():
            self.seqres_sequences[chain_id] = Sequence.from_sequence(chain_id, sequence, self.chain_types[chain_id])
28956
def get_rosetta_sequence_to_atom_json_map(self):
        ''''''
        import json
        if not self.rosetta_to_atom_sequence_maps and self.rosetta_sequences:
            raise Exception('The PDB to Rosetta mapping has not been determined. Please call construct_pdb_to_rosetta_residue_map first.')

        d = {}
        for c, sm in self.rosetta_to_atom_sequence_maps.iteritems():
            for k, v in sm.map.iteritems():
                d[k] = v
            #d[c] = sm.map
        return json.dumps(d, indent = 4, sort_keys = True)
13618
private boolean getPresenceOfNitro(IAtomContainer ac, IAtom atom) {
        List neighbours = ac.getConnectedAtomsList(atom);
        List second = null;
        IBond bond = null;
        //int counter = 0;
        for (int i = 0; i < neighbours.size(); i++) {
            IAtom neighbour = (IAtom) neighbours.get(i);
            if (neighbour.getSymbol().equals("N")) {
                second = ac.getConnectedAtomsList(neighbour);
                for (int b = 0; b < second.size(); b++) {
                    IAtom conAtom = (IAtom) second.get(b);
                    if (conAtom.getSymbol().equals("O")) {
                        bond = ac.getBond(neighbour, conAtom);
                        if (bond.getOrder() == IBond.Order.DOUBLE) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
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);
	}