Elements of residue_list should be strings extracted from PDB lines from position 21-26 inclusive (zero-indexing)
       i.e. the chain letter concatenated by the 5-character (including insertion code) residue ID.
767466
def create_pymol_selection_from_PDB_residue_ids(residue_list):
    ''''''
    residues_by_chain = {}
    for residue_id in residue_list:
        chain_id = residue_id[0]
        pruned_residue_id = residue_id[1:]
        residues_by_chain[chain_id] = residues_by_chain.get(chain_id, [])
        residues_by_chain[chain_id].append(pruned_residue_id)

    str = []
    for chain_id, residue_list in sorted(residues_by_chain.iteritems()):
        str.append('(chain %s and resi %s)' % (chain_id, '+'.join(map(string.strip, sorted(residue_list)))))
    return ' or '.join(str)
1042621
def parse_atoms(self, pdb):
    """"""
    
    atomre = re.compile("ATOM")
    
    atomlines = [line for line in pdb.lines if atomre.match(line)]
    
    chainresnums = {}
    
    for line in atomlines:
      chain = line[21]
      resname = line[17:20]
      resnum = line[22:27]
      #print resnum
      chainresnums.setdefault(chain, [])
      
      if resnum in chainresnums[chain]:
        assert self[chain][chainresnums[chain].index(resnum)] == resname
      else:
        if resnum[-1] == ' ':
          self.setdefault(chain, [])
          self[chain] += [resname]
          chainresnums[chain] += [resnum]
    
    return chainresnums
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)
1322607
def get_differing_atom_residue_ids(self, pdb_name, pdb_list = []):
        ''''''

        # partition_by_sequence is a map pdb_name -> Int where two pdb names in the same equivalence class map to the same integer (i.e. it is a partition)
        # representative_pdbs is a map Int -> pdb_object mapping the equivalence classes (represented by an integer) to a representative PDB file
        # self.pdb_name_to_structure_mapping : pdb_name -> pdb_object

        # Sanity checks
        assert(pdb_name in self.pdb_names)
        assert(set(pdb_list).intersection(set(self.pdb_names)) == set(pdb_list)) # the names in pdb_list must be in pdb_names

        # 1. Get the representative structure for pdb_name
        representative_pdb_id = self.partition_by_sequence[pdb_name]
        representative_pdb = self.representative_pdbs[representative_pdb_id]

        # 2. Get the other representative structures as dictated by pdb_list
        other_representative_pdbs = set()
        other_representative_pdb_ids = set()
        if not pdb_list:
            pdb_list = self.pdb_names
        for opdb_name in pdb_list:
            orepresentative_pdb_id = self.partition_by_sequence[opdb_name]
            other_representative_pdb_ids.add(orepresentative_pdb_id)
            other_representative_pdbs.add(self.representative_pdbs[orepresentative_pdb_id])
        other_representative_pdbs.discard(representative_pdb)
        other_representative_pdb_ids.discard(representative_pdb_id)

        # Early out if pdb_list was empty (or all pdbs were in the same equivalence class)
        if not other_representative_pdbs:
            return []

        # 3. Return all residues of pdb_name's representative which differ from all the other representatives
        differing_atom_residue_ids = set()
        for other_representative_pdb_id in other_representative_pdb_ids:
            differing_atom_residue_ids = differing_atom_residue_ids.union(set(self.differing_atom_residue_ids[(representative_pdb_id, other_representative_pdb_id)]))

        return sorted(differing_atom_residue_ids)
361888
def _parse(self):
        
        
        atom_counter = 0
        
        structure_build = self.structure_builder
        
        residues = self._extract_residues()
        
        cur_model = None
        cur_chain = None
        structure_build.init_seg(' ') # There is never a SEGID present
        
        for r in residues:

            # New model?
            if cur_model != r['model']:
                cur_model = r['model']
                try:
                    structure_build.init_model(cur_model)
                except PDBConstructionException, message:
                    self._handle_builder_exception(message, r) 
            
            # New chain?
            if cur_chain != r['chain']:
                cur_chain = r['chain']
                try:
                    structure_build.init_chain(cur_chain)
                except PDBConstructionException, message:
                    self._handle_builder_exception(message, r)

            # Create residue
            if r['name'] in AA_LIST: # Get residue type crudely since there is no HETATM / ATOM
                hetero_flag = ' '
            elif r['name'] == 'WAT' or r['name'] == 'HOH':
                hetero_flag = 'W'
            else:
                hetero_flag = 'H'
            
            # Some terminal atoms are added at residue 0. This residue has a small number of atoms.
            # Protonated non-terminal glycine has 7 atoms. Any of these residues is smaller.
            # HETATMs have only a couple of atoms (3 for water for example) and they are ok.
            
            if (len(r['atoms']) >= 7) or (hetero_flag != " "):
                try:
                    structure_build.init_residue(r['name'], hetero_flag, r['number'], r['icode'])
                except PDBConstructionException, message:
                    self._handle_builder_exception(message, r)
            
                # Create Atoms
                for atom in r['atoms']:
                    a = self._parse_atom(atom)

                    if not sum(a['coord']): # e.g. HG of metal bound CYS coords are 0,0,0.
                        continue
                        
                    try:
                        atom_counter += 1
                        # fullname = name; altloc is empty;
                        structure_build.init_atom(a['name'], a['coord'], a['bfactor'], a['occupancy'], ' ',
                                                    a['name'], atom_counter, a['element'],  hetero_flag)
                    except PDBConstructionException, message:
                        self._handle_builder_exception(message, r)      
            
            elif len(r['atoms']) < 7: # Terminal Residues
                                
                for atom in r['atoms']:
                    
                    a = self._parse_atom(atom)
                    
                    if not sum(a['coord']): # e.g. HG of metal bound CYS coords are 0,0,0.
                        continue

                    atom_counter += 1                    
                    ter_atom = Atom(a['name'], a['coord'], a['bfactor'], a['occupancy'], ' ',
                                    a['name'], atom_counter, a['element'], hetero_flag)
                    
                    if a['name'] in N_TERMINAL_ATOMS:
                        
                        inc_struct = self.structure_builder.get_structure()
                        for model in inc_struct:
                            for chain in model:
                                if chain.id == r['chain']:
                                    for residue in chain: # Find First residue matching name
                                        if residue.resname == r['name']:
                                            residue.add(ter_atom)
                                            break
                    
                    elif a['name'] in C_TERMINAL_ATOMS:

                        inc_struct = self.structure_builder.get_structure()
                        c_ter = None
                        for model in inc_struct:
                            for chain in model:
                                if chain.id == r['chain']:
                                    for residue in chain: # Find Last residue matching name
                                        if residue.resname == r['name']:
                                            c_ter = residue
                                    if c_ter:
                                        c_ter.add(ter_atom)
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)
114649
def merge_pdb_range_pairs(prs):
    '''
    '''
    new_prs = []
    sprs = [sorted((split_pdb_residue(p[0]), split_pdb_residue(p[1]))) for p in prs]
    sprs = sorted(sprs)
    merged = False
    x = 0
    from klab import colortext
    while x < len(sprs):
        newx = x + 1
        new_pair = list(sprs[x])
        for y in range(x + 1, len(sprs)):
            if new_pair[0] <= (sprs[y][0][0] - 1, sprs[y][0][1]) <= new_pair[1]:
                new_pair[0] = min(new_pair[0], sprs[y][0])
                new_pair[1] = max(new_pair[1], sprs[y][1])
                newx = y + 1
        if new_pair not in new_prs:
            new_prs.append(new_pair)
        x = newx
    return new_prs
546394
def characters(self):
        
        chars = 0
        for fragment in self.fragments:
            chars += fragment.characters
        return chars
838844
def decode_chain_list(in_bytes):
    """"""
    tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN
    out_strings = []
    for i in range(tot_strings):
        out_s = in_bytes[i * mmtf.utils.constants.CHAIN_LEN:i * mmtf.utils.constants.CHAIN_LEN + mmtf.utils.constants.CHAIN_LEN]
        out_strings.append(out_s.decode("ascii").strip(mmtf.utils.constants.NULL_BYTE))
    return out_strings
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]
376384
def pad_decr(ids):
  """"""
  if len(ids) < 1:
    return list(ids)
  if not any(ids):
    return []  # all padding.
  idx = -1
  while not ids[idx]:
    idx -= 1
  if idx == -1:
    ids = ids
  else:
    ids = ids[:idx + 1]
  return [i - 1 for i in ids]
1058036
def list_strip(list_, to_strip, left=True, right=True):
    
    import utool as ut
    flags = [item != to_strip for item in list_]
    flag_lists = []
    if right:
        rstrip_flags = ut.cumsum(flags[::-1])[::-1]
        flag_lists.append(rstrip_flags)
    if left:
        lstrip_flags = ut.cumsum(flags)
        flag_lists.append(lstrip_flags)
    strip_flags = ut.and_lists(*flag_lists)
    stripped_list = ut.compress(list_, strip_flags)
    return stripped_list
1033630
def p_const_vector_elem_list(p):
    
    if p[1] is None:
        return

    if not is_static(p[1]):
        if isinstance(p[1], symbols.UNARY):
            tmp = make_constexpr(p.lineno(1), p[1])
        else:
            api.errmsg.syntax_error_not_constant(p.lexer.lineno)
            p[0] = None
            return
    else:
        tmp = p[1]

    p[0] = [tmp]
826915
function _residuePredicates(dict) {
  var predicates = [];
  if (dict.rname !== undefined) {
    predicates.push(function(r) { return r.name() === dict.rname; });
  }
  if (dict.rnames !== undefined) {
    predicates.push(function(r) { 
    var n = r.name();
    for (var k = 0; k < dict.rnames.length; ++k) {
      if (n === dict.rnames[k]) {
          return true;
        }
      }
      return false;
    });
  }
  if (dict.rnums !== undefined) {
    var num_set = {};
    for (var i = 0; i < dict.rnums.length; ++i) {
      num_set[dict.rnums[i]] = true;
    }
    predicates.push(function(r) {
      var n = r.num();
      return num_set[n] === true;
    });
  }
  if (dict.rnum !== undefined) {
    predicates.push(function(r) {
      return r.num() === dict.rnum;
    });
  }
  if (dict.rtype !== undefined) {
    predicates.push(function(r) {
      return r.ss() === dict.rtype;
    });
  }
  return predicates;
}
634901
def from_string(cls, contents):
        
        mol = None
        charge = None
        spin_multiplicity = None
        params = dict()
        lines = contents.split('\n')
        parse_section = False
        section_name = None
        section_text = []
        ghost_atoms = None
        for line_num, line in enumerate(lines):
            l = line.strip().lower()

            if len(l) == 0:
                continue
            if (not parse_section) and (l == "$end" or not l.startswith("$")):
                raise ValueError("Format error, parsing failed")
            if parse_section and l != "$end":
                section_text.append(line)
            if l.startswith("$") and not parse_section:
                parse_section = True
                section_name = l[1:]
                available_sections = ["comment", "molecule", "rem"] + \
                    sorted(list(cls.optional_keywords_list))
                if section_name not in available_sections:
                    raise ValueError("Unrecognized keyword " + line.strip() +
                                     " at line " + str(line_num))
                if section_name in params:
                    raise ValueError("duplicated keyword " + line.strip() +
                                     "at line " + str(line_num))
            if parse_section and l == "$end":
                func_name = "_parse_" + section_name
                if func_name not in QcTask.__dict__:
                    raise Exception(func_name + " is not implemented yet, "
                                    "please implement it")
                parse_func = QcTask.__dict__[func_name].__get__(None, QcTask)
                if section_name == "molecule":
                    mol, charge, spin_multiplicity, ghost_atoms = parse_func(section_text)
                else:
                    d = parse_func(section_text)
                    params[section_name] = d
                parse_section = False
                section_name = None
                section_text = []
        if parse_section:
            raise ValueError("Format error. " + section_name + " is not "
                             "terminated")
        jobtype = params["rem"]["jobtype"]
        title = params.get("comment", None)
        exchange = params["rem"].get("exchange", "hf")
        method = params["rem"].get("method", None)
        correlation = params["rem"].get("correlation", None)
        basis_set = params["rem"]["basis"]
        aux_basis_set = params["rem"].get("aux_basis", None)
        ecp = params["rem"].get("ecp", None)
        optional_params = None
        op_keys = set(params.keys()) - {"comment", "rem"}
        if len(op_keys) > 0:
            optional_params = dict()
            for k in op_keys:
                optional_params[k] = params[k]
        return QcTask(molecule=mol, charge=charge,
                      spin_multiplicity=spin_multiplicity,
                      jobtype=jobtype, title=title,
                      exchange=exchange, correlation=correlation,
                      basis_set=basis_set, aux_basis_set=aux_basis_set,
                      ecp=ecp, rem_params=params["rem"],
                      optional_params=optional_params,
                      ghost_atoms=ghost_atoms,
                      method=method)
216389
public static String convertOneLetterCodeToThreeLetterCode(String oneLetterCode) {
        AminoAcid[] monomers = createAAs();
        for (int i = 0; i < monomers.length; i++) {
            if (monomers[i].getProperty(RESIDUE_NAME_SHORT).equals(oneLetterCode)) {
                return (String) monomers[i].getProperty(RESIDUE_NAME);
            }
        }
        return null;
    }
396438
def _find_pivot_addr(self, index):
        
        if not self.addresses or index.start == 0:
            return CharAddress('', self.tree, 'text', -1)  # string beginning
        if index.start > len(self.addresses):
            return self.addresses[-1]
        return self.addresses[index.start]