List of the side-chain atoms (R-group).

        Notes
        -----
        Returns empty list for glycine.

        Returns
        -------
        side_chain_atoms: list(`Atoms`)
198374
def side_chain(self):
        
        side_chain_atoms = []
        if self.mol_code != 'GLY':
            covalent_bond_graph = generate_covalent_bond_graph(
                find_covalent_bonds(self))
            try:
                subgraphs = generate_bond_subgraphs_from_break(
                    covalent_bond_graph, self['CA'], self['CB'])
                if len(subgraphs) == 1:
                    subgraphs = generate_bond_subgraphs_from_break(
                        subgraphs[0], self['CD'], self['N'])
                if len(subgraphs) == 2:
                    for g in subgraphs:
                        if self['CB'] in g:
                            side_chain_atoms = g.nodes()
                            break
            except:
                warning_message = "Malformed PDB for Residue {0}: {1}.".format(
                    self.id, self)
                if 'CB' in self.atoms.keys():
                    side_chain_atoms.append(self['CB'])
                    warning_message += " Side-chain is just the CB atom."
                else:
                    warning_message += " Empty side-chain."
                warnings.warn(warning_message, MalformedPDBWarning)
        return side_chain_atoms
148473
def get_reactions(columns='all', n_results=20, write_db=False, **kwargs):
    
    if write_db or columns == 'all':
        columns = all_columns['reactions']
    queries = {}
    for key, value in kwargs.items():
        key = map_column_names(key)
        if key == 'distinct':
            if value in [True, 'True', 'true']:
                queries.update({key: True})
                continue
        if isinstance(value, int) or isinstance(value, float):
            queries.update({key: value})
        else:
            queries.update({key: '{0}'.format(value)})

    subtables = []
    if write_db:
        subtables = ['reactionSystems', 'publication']
    else:
        subtables = []
    data = query(table='reactions', subtables=subtables,
                 columns=columns,
                 n_results=n_results, queries=queries)

    if not write_db:
        return data

    print('Writing result to Reactions.db')
    unique_ids = []
    for row in data['reactions']['edges']:
        with CathubSQLite('Reactions.db') as db:
            row = row['node']
            key_values = {}
            for key in all_columns['reactions']:
                v = row[key]
                # if isinstance(v, unicode):
                #    v = v.encode('utf-8')
                try:
                    v = json.loads(v)
                except BaseException:
                    pass
                key_values[convert(key)] = v
            ase_ids = {}
            energy_corrections = {}

            for row_rs in row['reactionSystems']:
                if row_rs['name'] == 'N/A':
                    continue
                ase_ids[row_rs['name']] = row_rs['aseId']
                energy_corrections[row_rs['name']] = row_rs['energyCorrection']

            if not ase_ids:
                ase_ids = None
                energy_corrections = None
            else:
                unique_ids += ase_ids.values()
            key_values['ase_ids'] = ase_ids
            key_values['energy_corrections'] = ase_ids

            # publications
            pub_key_values = {}
            row_p = row['publication']
            for key in all_columns['publications']:
                pub_key_values[convert(key)] = row_p[key]
            db.write_publication(pub_key_values)

            # reactions and reaction_systems
            id = db.check(key_values['chemical_composition'],
                          key_values['reaction_energy'])
            if id is None:
                id = db.write(key_values)
            else:
                db.update(id, key_values)

    if ase_ids is not None:
        # Ase structures
        with ase.db.connect('Reactions.db') as ase_db:
            con = ase_db.connection
            cur = con.cursor()
            cur.execute('SELECT unique_id from systems;')
            unique_ids0 = cur.fetchall()
            unique_ids0 = [un[0] for un in unique_ids0]
            unique_ids = [un for un in unique_ids if un not in unique_ids0]
            for unique_id in list(set(unique_ids)):
                # if ase_db.count('unique_id={}'.format(unique_id)) == 0:
                atomsrow = get_atomsrow_by_id(unique_id)
                ase_db.write(atomsrow)

    print('Writing complete!')

    return data
1291851
def strip_to_chains(self, chains, break_at_endmdl = True):
        ''''''
        if chains:
            chains = set(chains)

            # Remove any structure lines not associated with the chains
            self.lines = [l for l in self.lines if not(l.startswith('ATOM  ') or l.startswith('HETATM') or l.startswith('ANISOU') or l.startswith('TER')) or l[21] in chains]

            # For some Rosetta protocols, only one NMR model should be kept
            if break_at_endmdl:
                new_lines = []
                for l in self.lines:
                    if l.startswith('ENDMDL'):
                        new_lines.append(l)
                        break
                    new_lines.append(l)
                self.lines = new_lines

            self._update_structure_lines()
            # todo: this logic should be fine if no other member elements rely on these lines e.g. residue mappings otherwise we need to update or clear those elements here
        else:
            raise Exception('The chains argument needs to be supplied.')
709214
def _get_bonds(self, mol):
        
        num_atoms = len(mol)
        # index starting from 0
        if self.ignore_ionic_bond:
            covalent_atoms = [i for i in range(num_atoms) if mol.species[i].symbol not in self.ionic_element_list]
        else:
            covalent_atoms = list(range(num_atoms))
        all_pairs = list(itertools.combinations(covalent_atoms, 2))
        pair_dists = [mol.get_distance(*p) for p in all_pairs]
        elements = mol.composition.as_dict().keys()
        unavailable_elements = list(set(elements) -
                                    set(self.covalent_radius.keys()))
        if len(unavailable_elements) > 0:
            raise ValueError("The covalent radius for element {} is not "
                             "available".format(unavailable_elements))
        bond_13 = self.get_13_bonds(self.priority_bonds)
        max_length = [(self.covalent_radius[mol.sites[p[0]].specie.symbol] +
                       self.covalent_radius[mol.sites[p[1]].specie.symbol]) *
                      (1 + (self.priority_cap if p in self.priority_bonds
                            else (self.bond_length_cap if p not in bond_13
                                  else self.bond_13_cap))) *
                      (0.1 if (self.ignore_halogen_self_bond and p not in self.priority_bonds and
                               mol.sites[p[0]].specie.symbol in self.halogen_list and
                               mol.sites[p[1]].specie.symbol in self.halogen_list)
                       else 1.0)
                      for p in all_pairs]

        bonds = [bond
                 for bond, dist, cap in zip(all_pairs, pair_dists, max_length)
                 if dist <= cap]
        return bonds
580332
def sequences(self):
        
        seqs = [x.sequence for x in self._molecules if hasattr(x, 'sequence')]
        return seqs
1035181
def get_counts(self):
        """"""

        hbondsback = len([hb for hb in self.hbonds if not hb.sidechain])
        counts = {'hydrophobics': len(self.hydrophobics), 'hbonds': len(self.hbonds),
                  'wbridges': len(self.wbridges), 'sbridges': len(self.sbridges), 'pistacks': len(self.pi_stacks),
                  'pications': len(self.pi_cations), 'halogens': len(self.halogens), 'metal': len(self.metal_complexes),
                  'hbond_back': hbondsback, 'hbond_nonback': (len(self.hbonds) - hbondsback)}
        counts['total'] = counts['hydrophobics'] + counts['hbonds'] + counts['wbridges'] + \
            counts['sbridges'] + counts['pistacks'] + counts['pications'] + counts['halogens'] + counts['metal']
        return counts
673884
def build(self):
        """"""
        ang_per_res = (2 * numpy.pi) / self.residues_per_turn
        atom_offsets = _atom_offsets[self.helix_type]
        if self.handedness == 'l':
            handedness = -1
        else:
            handedness = 1

        atom_labels = ['N', 'CA', 'C', 'O']
        if all([x in atom_offsets.keys() for x in atom_labels]):
            res_label = 'GLY'
        else:
            res_label = 'UNK'

        monomers = []
        for i in range(self.num_monomers):
            residue = Residue(mol_code=res_label, ampal_parent=self)
            atoms_dict = OrderedDict()
            for atom_label in atom_labels:
                r, zeta, z_shift = atom_offsets[atom_label]
                rot_ang = ((i * ang_per_res) + zeta) * handedness
                z = (self.rise_per_residue * i) + z_shift
                coords = cylindrical_to_cartesian(
                    radius=r, azimuth=rot_ang, z=z, radians=True)
                atom = Atom(
                    coordinates=coords, element=atom_label[0],
                    ampal_parent=residue, res_label=atom_label)
                atoms_dict[atom_label] = atom
            residue.atoms = atoms_dict
            monomers.append(residue)
        self._monomers = monomers
        self.relabel_monomers()
        self.relabel_atoms()
        return
1238867
def getpeptides(self, chain):
        
        all_from_chain = [o for o in pybel.ob.OBResidueIter(
            self.proteincomplex.OBMol) if o.GetChain() == chain]  # All residues from chain
        if len(all_from_chain) == 0:
            return None
        else:
            non_water = [o for o in all_from_chain if not o.GetResidueProperty(9)]
            ligand = self.extract_ligand(non_water)
            return ligand
1309137
def _get_side2KerningGroups(self):
        
        found = {}
        for name, contents in self.items():
            if name.startswith("public.kern2."):
                found[name] = contents
        return found
1264514
def _update_structure_lines(self):
        ''''''
        structure_lines = []
        atom_chain_order = []
        chain_atoms = {}

        for line in self.lines:
            linetype = line[0:6]
            if linetype == 'ATOM  ' or linetype == 'HETATM' or linetype == 'TER   ':
                chain_id = line[21]
                self.residue_types.add(line[17:20].strip())
                if missing_chain_ids.get(self.pdb_id):
                    chain_id = missing_chain_ids[self.pdb_id]
                structure_lines.append(line)
                if (chain_id not in atom_chain_order) and (chain_id != ' '):
                    atom_chain_order.append(chain_id)
                if linetype == 'ATOM  ':
                    atom_type = line[12:16].strip()
                    if atom_type:
                        chain_atoms[chain_id] = chain_atoms.get(chain_id, set())
                        chain_atoms[chain_id].add(atom_type)
            if linetype == 'ENDMDL':
                colortext.warning("ENDMDL detected: Breaking out early. We do not currently handle NMR structures properly.")
                break

        self.structure_lines = structure_lines
        self.atom_chain_order = atom_chain_order
        self.chain_atoms = chain_atoms
250662
private List<List<Atom[]>> getMatchedAtomsOfLinkages(
			ModificationCondition condition, Map<Component, Set<Group>> mapCompGroups) {
		List<ModificationLinkage> linkages = condition.getLinkages();
		int nLink = linkages.size();

		List<List<Atom[]>> matchedAtomsOfLinkages =
				new ArrayList<List<Atom[]>>(nLink);

		for (int iLink=0; iLink<nLink; iLink++) {
			ModificationLinkage linkage = linkages.get(iLink);
			Component comp1 = linkage.getComponent1();
			Component comp2 = linkage.getComponent2();

//			boolean isAA1 = comp1.;
//			boolean isAA2 = comp2.getType()==true;

			Set<Group> groups1 = mapCompGroups.get(comp1);
			Set<Group> groups2 = mapCompGroups.get(comp2);

			List<Atom[]> list = new ArrayList<Atom[]>();

			List<String> potentialNamesOfAtomOnGroup1 = linkage.getPDBNameOfPotentialAtomsOnComponent1();
			for (String name : potentialNamesOfAtomOnGroup1) {
				if (name.equals("*")) {
					// wildcard
					potentialNamesOfAtomOnGroup1 = null; // search all atoms
					break;
				}
			}

			List<String> potentialNamesOfAtomOnGroup2 = linkage.getPDBNameOfPotentialAtomsOnComponent2();
			for (String name : potentialNamesOfAtomOnGroup2) {
				if (name.equals("*")) {
					// wildcard
					potentialNamesOfAtomOnGroup2 = null; // search all atoms
					break;
				}
			}

			for (Group g1 : groups1) {
				for (Group g2 : groups2) {
					if (g1.equals(g2)) {
						continue;
					}

					// only for wildcard match of two residues
					boolean ignoreNCLinkage =
						potentialNamesOfAtomOnGroup1 == null &&
						potentialNamesOfAtomOnGroup2 == null &&
						residues.contains(g1) &&
						residues.contains(g2);

					Atom[] atoms = StructureUtil.findNearestAtomLinkage(
							g1, g2,
							potentialNamesOfAtomOnGroup1,
							potentialNamesOfAtomOnGroup2,
							ignoreNCLinkage,
							bondLengthTolerance);
					if (atoms!=null) {
						list.add(atoms);
					}
				}
			}

			if (list.isEmpty()) {
				// broken linkage
				break;
			}

			matchedAtomsOfLinkages.add(list);
		}

		return matchedAtomsOfLinkages;
	}
1277879
def _get_valences(self):
        
        try:
            bv = BVAnalyzer()
            self._structure = bv.get_oxi_state_decorated_structure(
                self._structure)
            valences = bv.get_valences(self._structure)
        except:
            try:
                bv = BVAnalyzer(symm_tol=0.0)
                self._structure = bv.get_oxi_state_decorated_structure(
                    self._structure)
                valences = bv.get_valences(self._structure)
            except:
                valences = []
                for site in self._structure.sites:
                    if len(site.specie.common_oxidation_states) > 0:
                        valences.append(site.specie.common_oxidation_states[0])
                    # Handle noble gas species
                    # which have no entries in common_oxidation_states.
                    else:
                        valences.append(0)
                if sum(valences):
                    valences = [0] * self._structure.num_sites
                else:
                    self._structure.add_oxidation_state_by_site(valences)
                # raise

        # el = [site.specie.symbol for site in self._structure.sites]
        # el = [site.species_string for site in self._structure.sites]
        # el = [site.specie for site in self._structure.sites]
        # valence_dict = dict(zip(el, valences))
        # print valence_dict
        return valences
1031608
def proc_atom(self):
        """"""
        atom_data = self.proc_line_coordinate(self.current_line)
        (at_type, at_ser, at_name, alt_loc, res_name, chain_id, res_seq,
         i_code, x, y, z, occupancy, temp_factor, element, charge) = atom_data
        # currently active state
        a_state = self.pdb_parse_tree['data'][self.state]
        res_id = (res_seq, i_code)
        if chain_id not in a_state:
            a_state[chain_id] = (set(), OrderedDict())
        if res_id not in a_state[chain_id][1]:
            a_state[chain_id][1][res_id] = (set(), OrderedDict())
        if at_type == 'ATOM':
            if res_name in standard_amino_acids.values():
                poly = 'P'
            else:
                poly = 'N'
        else:
            poly = 'H'
        a_state[chain_id][0].add((chain_id, at_type, poly))
        a_state[chain_id][1][res_id][0].add(
            (at_type, res_seq, res_name, i_code))
        if at_ser not in a_state[chain_id][1][res_id][1]:
            a_state[chain_id][1][res_id][1][at_ser] = [atom_data]
        else:
            a_state[chain_id][1][res_id][1][at_ser].append(atom_data)
        return
228239
def neighbor_atoms(self, atom_symbol=None):
        
        if not atom_symbol:
            return self.neighbors
        else:
            return [atom for atom in self.neighbors if atom['atom_symbol'] == atom_symbol]
447501
def assign_per_atom_sasa(self):
		""""""
		atom_names= [atom.name for atom in self.topology_data.universe.ligand_noH.atoms]
		sasa_dict = {}
		for atom in range(0,self.topology_data.universe.ligand_noH.n_atoms):
			sasa_dict[atom_names[atom]]=[self.sasa[i][atom] for i in range(len(self.sasa))]
		return sasa_dict
70614
def invariants(mol):
    """"""
    atom_ids = {}
    for a in mol.atoms:
        components = []
        components.append(a.number)
        components.append(len(a.oatoms))
        components.append(a.hcount)
        components.append(a.charge)
        components.append(a.mass)
        if len(a.rings) > 0:
            components.append(1)

        atom_ids[a.index] = gen_hash(components)

    return atom_ids
270822
public static Atom[] getAtomCAArray(Structure s) {

		List<Atom> atoms = new ArrayList<Atom>();

		for (Chain c : s.getChains()) {
			for (Group g : c.getAtomGroups()) {
				if (g.hasAtom(CA_ATOM_NAME)
						&& g.getAtom(CA_ATOM_NAME).getElement() == Element.C) {
					atoms.add(g.getAtom(CA_ATOM_NAME));
				}
			}
		}

		return atoms.toArray(new Atom[atoms.size()]);
	}