code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
bb_poly = Polypeptide([x.backbone for x in self._monomers], self.id) return bb_poly
def backbone(self)
Returns a new `Polymer` containing only the backbone atoms. Notes ----- Metadata is not currently preserved from the parent object. Sequence data is retained, but only the main chain atoms are retained. Returns ------- bb_poly : Polypeptide Polymer c...
14.371967
8.467923
1.697225
# This import is here to prevent a circular import. from ampal.pdb_parser import convert_pdb_to_ampal polymer_bb = self.backbone if len(sequence) != len(polymer_bb): raise ValueError( 'Sequence length ({}) does not match Polymer length ({}).'.format( ...
def pack_new_sequence(self, sequence)
Packs a new sequence onto the polymer using Scwrl4. Parameters ---------- sequence : str String containing the amino acid sequence. This must be the same length as the Polymer Raises ------ ValueError Raised if the sequence length doe...
5.069227
4.371415
1.159631
seq = [x.mol_letter for x in self._monomers] return ''.join(seq)
def sequence(self)
Returns the sequence of the `Polymer` as a string. Returns ------- sequence : str String of the `Residue` sequence of the `Polypeptide`.
11.778305
12.5908
0.935469
bond_lengths = dict( n_ca=[distance(r['N'], r['CA']) for r in self.get_monomers(ligands=False)], ca_c=[distance(r['CA'], r['C']) for r in self.get_monomers(ligands=False)], c_o=[distance(r['C'], r['O']) for r in se...
def backbone_bond_lengths(self)
Dictionary containing backbone bond lengths as lists of floats. Returns ------- bond_lengths : dict Keys are `n_ca`, `ca_c`, `c_o` and `c_n`, referring to the N-CA, CA-C, C=O and C-N bonds respectively. Values are lists of floats : the bond lengths in Angstro...
2.421156
2.100629
1.152586
bond_angles = dict( n_ca_c=[angle_between_vectors(r['N'] - r['CA'], r['C'] - r['CA']) for r in self.get_monomers(ligands=False)], ca_c_o=[angle_between_vectors(r['CA'] - r['C'], r['O'] - r['C']) for r in self.get_monomers(ligands=False)], ...
def backbone_bond_angles(self)
Dictionary containing backbone bond angles as lists of floats. Returns ------- bond_angles : dict Keys are `n_ca_c`, `ca_c_o`, `ca_c_n` and `c_n_ca`, referring to the N-CA-C, CA-C=O, CA-C-N and C-N-CA angles respectively. Values are lists of floats : the bond...
1.974179
1.725897
1.143856
tagged = ['secondary_structure' in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: dssp_out = run_dssp(self.pdb, path=False) if dssp_out is None: return dssp_ss_list = extract_all_ss_dssp(dssp_out, path=...
def tag_secondary_structure(self, force=False)
Tags each `Residue` of the `Polypeptide` with secondary structure. Notes ----- DSSP must be available to call. Check by running `isambard.external_programs.dssp.test_dssp`. If DSSP is not available, please follow instruction here to add it: https://github.com/woolfson-gr...
3.365917
3.83031
0.878758
if tag_type: tag_type = tag_type else: tag_type = 'residue_solvent_accessibility' tagged = [tag_type in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: naccess_rsa_list, total = extract_residue_accessibility(run_naccess( ...
def tag_residue_solvent_accessibility(self, tag_type=False, tag_total=False, force=False, include_hetatms=False)
Tags `Residues` wirh relative residue solvent accessibility. Notes ----- THIS FUNCTIONALITY REQUIRES NACESS. This function tags the Monomer with the *relative* RSA of the *whole side chain*, i.e. column 2 of the .rsa file that NACCESS writes. References ...
3.714875
3.301848
1.125089
tagged = ['dssp_acc' in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: dssp_out = run_dssp(self.pdb, path=False) if dssp_out is None: return dssp_acc_list = extract_solvent_accessibility_dssp( dssp_out, p...
def tag_dssp_solvent_accessibility(self, force=False)
Tags each `Residues` Polymer with its solvent accessibility. Notes ----- For more about DSSP's solvent accessibilty metric, see: http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC References ---------- .. [1] Kabsch W, Sander C (1983) "Dictionary of prote...
3.110981
3.741321
0.831519
tagged = ['chi_angles' in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: for monomer in self._monomers: chi_angles = measure_sidechain_torsion_angles( monomer, verbose=False) monomer.tags['chi_angles'] = chi_...
def tag_sidechain_dihedrals(self, force=False)
Tags each monomer with side-chain dihedral angles force: bool, optional If `True` the tag will be run even if `Residues` are already tagged.
4.209532
4.189197
1.004854
tagged = ['omega' in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: tas = measure_torsion_angles(self._monomers) for monomer, (omega, phi, psi) in zip(self._monomers, tas): monomer.tags['omega'] = omega monomer.tags[...
def tag_torsion_angles(self, force=False)
Tags each Monomer of the Polymer with its omega, phi and psi torsion angle. Parameters ---------- force : bool, optional If `True` the tag will be run even if `Residues` are already tagged.
2.95103
3.131382
0.942405
tagged = ['rise_per_residue' in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: # Assign tags None if Polymer is too short to have a primitive. if len(self) < 7: rprs = [None] * len(self) rocs = [None] * len(self) ...
def tag_ca_geometry(self, force=False, reference_axis=None, reference_axis_name='ref_axis')
Tags each `Residue` with rise_per_residue, radius_of_curvature and residues_per_turn. Parameters ---------- force : bool, optional If `True` the tag will be run even if `Residues` are already tagged. reference_axis : list(numpy.array or tuple or list), optional ...
3.420789
3.089817
1.107117
bond_lengths = self.backbone_bond_lengths a1 = numpy.allclose(bond_lengths['n_ca'], [ideal_backbone_bond_lengths['n_ca']] * len(self), atol=atol) a2 = numpy.allclose(bond_lengths['ca_c'], [ideal_backbone...
def valid_backbone_bond_lengths(self, atol=0.1)
True if all backbone bonds are within atol Angstroms of the expected distance. Notes ----- Ideal bond lengths taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of Protein Structure. New York: Springer-Verlag, 1979. ...
1.779915
1.8781
0.947721
bond_angles = self.backbone_bond_angles omegas = [x[0] for x in measure_torsion_angles(self)] trans = ['trans' if (omega is None) or ( abs(omega) >= 90) else 'cis' for omega in omegas] ideal_n_ca_c = [ideal_backbone_bond_angles[x]['n_ca_c'] for x in trans] id...
def valid_backbone_bond_angles(self, atol=20)
True if all backbone bond angles are within atol degrees of their expected values. Notes ----- Ideal bond angles taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of Protein Structure. New York: Springer-Verlag, 197...
1.99051
2.010446
0.990084
if n_cap == 'acetyl': methylacetamide = Ligand( atoms=None, mol_code='UNK', is_hetero=True) atoms = OrderedDict() atoms['C'] = Atom([0.9500, -0.2290, 0.5090], 'C', res_label='C') atoms['CA'] = Atom([0.7450, -0.9430, 1.8040], 'C', res_label...
def n_cap(self, n_cap='acetyl', cap_dihedral=None)
Adds an N-terminal acetamide cap. Notes ----- Default behaviour is to duplicate the dihedral angle of the succeeding residues such that the orientation of the carbonyl of the acetyl will resemble that of the first residue. This can be adjusted by supplying a cap_dihedral...
2.717876
2.762019
0.984018
try: backbone = OrderedDict([('N', self.atoms['N']), ('CA', self.atoms['CA']), ('C', self.atoms['C']), ('O', self.atoms['O'])]) except KeyError: missing_atoms = fi...
def backbone(self)
Returns a new `Residue` containing only the backbone atoms. Returns ------- bb_monomer : Residue `Residue` containing only the backbone atoms of the original `Monomer`. Raises ------ IndexError Raise if the `atoms` dict does not conta...
3.550658
2.865533
1.239092
if self.is_hetero: if self.mol_code == 'HOH': hetero_flag = 'W' else: hetero_flag = 'H_{0}'.format(self.mol_code) else: hetero_flag = ' ' return self.ampal_parent.id, (hetero_flag, self.id, self.insertion_code)
def unique_id(self)
Generates a tuple that uniquely identifies a `Monomer` in an `Assembly`. Notes ----- The unique_id will uniquely identify each monomer within a polymer. If each polymer in an assembly has a distinct id, it will uniquely identify each monomer within the assembly. The het...
5.551728
3.200047
1.734889
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[...
def side_chain(self)
List of the side-chain atoms (R-group). Notes ----- Returns empty list for glycine. Returns ------- side_chain_atoms: list(`Atoms`)
3.420607
3.387313
1.009829
if self.mol_code == 'GLY': return [self] side_chain_dict = {x: {y: self.states[x][y] for y in self.states[x] if self.states[x][y] in self.side_chain} for x in self.states} side_chain_monomer = Monomer( ...
def side_chain_environment(self, cutoff=4, include_neighbours=True, inter_chain=True, include_ligands=False, include_solvent=False)
Finds `Residues` with any atom within the cutoff distance of side-chain. Notes ----- Includes the parent residue in the list. Parameters ---------- cutoff : float, optional Maximum inter-atom distance for residue to be included. Defaults to 4. ...
3.019514
2.987959
1.010561
with open(settings_path, 'r') as settings_f: global global_settings settings_json = json.loads(settings_f.read()) if global_settings is None: global_settings = settings_json global_settings[u'package_path'] = package_dir else: for k, v in sett...
def load_global_settings()
Loads settings file containing paths to dependencies and other optional configuration elements.
2.512728
2.456903
1.022722
for i in range(2): self._molecules.append( self.make_helix(self.aas[i], self.axis_distances[i], self.z_shifts[i], self.phis[i], self.splays[i], self.off_plane[i])) return
def build(self)
Builds a `HelixPair` using the defined attributes.
9.421941
7.72483
1.219696
start = numpy.array([axis_distance, 0 + z_shift, 0]) end = numpy.array([axis_distance, (aa * 1.52) + z_shift, 0]) mid = (start + end) / 2 helix = Helix.from_start_and_end(start, end, aa=aa) helix.rotate(splay, (0, 0, 1), mid) helix.rotate(off_plane, (1, 0, 0), m...
def make_helix(aa, axis_distance, z_shift, phi, splay, off_plane)
Builds a helix for a given set of parameters.
3.071264
3.069071
1.000715
self._molecules = [] if self.handedness == 'l': handedness = -1 else: handedness = 1 rot_ang = self.rot_ang * handedness for i in range(self.num_of_repeats): dup_unit = copy.deepcopy(self.repeat_unit) z = (self.rise * i) * ...
def build(self)
Builds a Solenoid using the defined attributes.
4.296381
4.42118
0.971772
start = numpy.array(start) end = numpy.array(end) instance = cls(sequence, helix_type=helix_type, phos_3_prime=phos_3_prime) instance.move_to(start=start, end=end) return instance
def from_start_and_end(cls, start, end, sequence, helix_type='b_dna', phos_3_prime=False)
Generates a helical `Polynucleotide` that is built along an axis. Parameters ---------- start: [float, float, float] Start of the build axis. end: [float, float, float] End of build axis. sequence: str The nucleotide sequence of the nucleic ac...
2.332003
2.785656
0.837147
ang_per_res = (2 * numpy.pi) / self.nucleotides_per_turn atom_offset_coords = _backbone_properties[self.helix_type]['atoms'] if self.handedness == 'l': handedness = -1 else: handedness = 1 base_atom_labels = _backbone_properties[self.helix_type]['...
def build(self)
Build single DNA strand along z-axis, starting with P on x-axis
3.237669
3.170991
1.021027
start = numpy.array(start) end = numpy.array(end) if numpy.allclose(start, end): raise ValueError('start and end must NOT be identical') translation, angle, axis, point = find_transformations( self.helix_start, self.helix_end, start, end) if not n...
def move_to(self, start, end)
Moves the `Polynucleotide` to lie on the `start` and `end` vector. Parameters ---------- start : 3D Vector (tuple or list or numpy.array) The coordinate of the start of the helix primitive. end : 3D Vector (tuple or list or numpy.array) The coordinate of the end ...
3.670373
4.165922
0.881047
crangles = [x if x > 0 else 360 + x for x in crangles] hept_p = [x * (360.0 / 7.0) + ((360.0 / 7.0) / 2.0) for x in range(7)] ideal_crangs = [ hept_p[0], hept_p[2], hept_p[4], hept_p[6], hept_p[1], hept_p[3], hept_p[5] ] full_hept = len(cr...
def fit_heptad_register(crangles)
Attempts to fit a heptad repeat to a set of Crick angles. Parameters ---------- crangles: [float] A list of average Crick angles for the coiled coil. Returns ------- fit_data: [(float, float, float)] Sorted list of fits for each heptad position.
3.154261
3.204457
0.984335
for i in range(len(self.cc[0])): layer_radii = [x[i].tags['distance_to_ref_axis'] for x in self.cc] self.radii_layers.append(layer_radii) layer_alpha = [x[i].tags['alpha_angle_ref_axis'] for x in self.cc] self.alpha_layers.append(layer_alpha) ...
def gather_layer_info(self)
Extracts the tagged coiled-coil parameters for each layer.
3.055619
2.771696
1.102437
mean_layers = [numpy.mean(x) if x[0] else 0 for x in parameter_layers] overall_mean = numpy.mean([x for x in mean_layers if x]) return mean_layers, overall_mean
def calc_average_parameters(parameter_layers)
Takes a group of equal length lists and averages them across each index. Returns ------- mean_layers: [float] List of values averaged by index overall_mean: float Mean of the averaged values.
4.388934
3.375774
1.300127
base_reg = 'abcdefg' exp_base = base_reg * (self.cc_len//7+2) ave_ca_layers = self.calc_average_parameters(self.ca_layers)[0][:-1] reg_fit = fit_heptad_register(ave_ca_layers) hep_pos = reg_fit[0][0] return exp_base[hep_pos:hep_pos+self.cc_len], reg_fit[0][1:]
def heptad_register(self)
Returns the calculated register of the coiled coil and the fit quality.
7.268418
6.641702
1.094361
# Find register lines = ['Register Assignment\n-------------------'] register, fit = self.heptad_register() lines.append('{}\n{}\n'.format(register, '\n'.join(self.cc.sequences))) lines.append('Fit Quality - Mean Angular Discrepancy = {:3.2f} (Std Dev = {:3.2f})\n'.forma...
def generate_report(self)
Generates a report on the coiled coil parameters. Returns ------- report: str A string detailing the register and parameters of the coiled coil.
2.494396
2.449216
1.018447
instance = cls(specification, sequences, parameters, build_fn=default_build, eval_fn=buff_interaction_eval, **kwargs) return instance
def buff_interaction_eval(cls, specification, sequences, parameters, **kwargs)
Creates optimizer with default build and BUFF interaction eval. Notes ----- Any keyword arguments will be propagated down to BaseOptimizer. Parameters ---------- specification : ampal.assembly.specification Any assembly level specification. sequences...
4.932362
5.931829
0.831508
eval_fn = make_rmsd_eval(reference_ampal) instance = cls(specification, sequences, parameters, build_fn=default_build, eval_fn=eval_fn, mp_disabled=True, **k...
def rmsd_eval(cls, specification, sequences, parameters, reference_ampal, **kwargs)
Creates optimizer with default build and RMSD eval. Notes ----- Any keyword arguments will be propagated down to BaseOptimizer. RMSD eval is restricted to a single core only, due to restrictions on closure pickling. Parameters ---------- specification :...
4.766307
5.187248
0.918851
scaled_ind = [] for i in range(len(self.value_means)): scaled_ind.append(self.value_means[i] + ( individual[i] * self.value_ranges[i])) fullpars = list(self.arrangement) for k in range(len(self.variable_parameters)): for j in range(len(ful...
def parse_individual(self, individual)
Converts a deap individual into a full list of parameters. Parameters ---------- individual: deap individual from optimization Details vary according to type of optimization, but parameters within deap individual are always between -1 and 1. This function con...
3.437322
3.330067
1.032208
self._cores = cores self._store_params = store_params self.parameter_log = [] self._model_count = 0 self.halloffame = tools.HallOfFame(1) self.stats = tools.Statistics(lambda thing: thing.fitness.values) self.stats.register("avg", numpy.mean) self...
def run_opt(self, pop_size, generations, cores=1, plot=False, log=False, log_path=None, run_id=None, store_params=True, **kwargs)
Runs the optimizer. Parameters ---------- pop_size: int Size of the population each generation. generation: int Number of generations in optimisation. cores: int, optional Number of CPU cores used to run the optimisation. If the 'm...
2.244651
2.204338
1.018288
self.value_means = [] self.value_ranges = [] self.arrangement = [] self.variable_parameters = [] current_var = 0 for parameter in self.parameters: if parameter.type == ParameterType.DYNAMIC: self.value_means.append(parameter.value[0]) ...
def _make_parameters(self)
Converts a list of Parameters into DEAP format.
3.002408
2.920882
1.027912
self._evals = len(targets) px_parameters = zip([self.specification] * len(targets), [self.sequences] * len(targets), [self.parse_individual(x) for x in targets]) if (self._cores == 1) or (self.mp_disabled): models = map...
def assign_fitnesses(self, targets)
Assigns fitnesses to parameters. Notes ----- Uses `self.eval_fn` to evaluate each member of target. Parameters --------- targets Parameter values for each member of the population.
3.571732
3.556023
1.004418
best_ind = self.halloffame[0] model_params = self.parse_individual( best_ind) # need to change name of 'params' if output_path is None: output_path = os.getcwd() if run_id is None: run_id = '{:%Y%m%d-%H%M%S}'.format( datetime....
def log_results(self, output_path=None, run_id=None)
Saves files for the minimization. Notes ----- Currently saves a logfile with best individual and a pdb of the best model.
2.405211
2.318341
1.037471
if not hasattr(self, 'halloffame'): raise AttributeError( 'No best model found, have you ran the optimiser?') model = self.build_fn( (self.specification, self.sequences, self.parse_individual(self.halloffame[0]) )) ...
def best_model(self)
Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a name error if the optimiser has not been run.
10.841172
8.198507
1.322335
return cls(label, ParameterType.DYNAMIC, (val_mean, val_range))
def dynamic(cls, label, val_mean, val_range)
Creates a static parameter. Parameters ---------- label : str A human-readable label for the parameter. val_mean : float The mean value of the parameter. val_range : float The minimum and maximum variance from the mean allowed for ...
6.705026
7.578835
0.884704
if path: with open(pdb, 'r') as inf: pdb = inf.read() pdb = pdb.encode() sequence = sequence.encode() try: with tempfile.NamedTemporaryFile(delete=False) as scwrl_tmp,\ tempfile.NamedTemporaryFile(delete=False) as scwrl_seq,\ tempfile.Name...
def run_scwrl(pdb, sequence, path=True)
Runs SCWRL on input PDB strong or path to PDB and a sequence string. Parameters ---------- pdb : str PDB string or a path to a PDB file. sequence : str Amino acid sequence for SCWRL to pack in single-letter code. path : bool, optional True if pdb is a path. Returns ...
1.97723
1.870254
1.057198
score = re.findall( r'Total minimal energy of the graph = ([-0-9.]+)', scwrl_std_out)[0] # Add temperature factors to SCWRL out split_scwrl = scwrl_pdb.splitlines() fixed_scwrl = [] for line in split_scwrl: if len(line) < 80: line += ' ' * (80 - len(line)) if...
def parse_scwrl_out(scwrl_std_out, scwrl_pdb)
Parses SCWRL output and returns PDB and SCWRL score. Parameters ---------- scwrl_std_out : str Std out from SCWRL. scwrl_pdb : str String of packed SCWRL PDB. Returns ------- fixed_scwrl_str : str String of packed SCWRL PDB, with correct PDB format. score : floa...
3.493031
3.357742
1.040292
scwrl_std_out, scwrl_pdb = run_scwrl(pdb, sequence, path=path) return parse_scwrl_out(scwrl_std_out, scwrl_pdb)
def pack_sidechains(pdb, sequence, path=False)
Packs sidechains onto a given PDB file or string. Parameters ---------- pdb : str PDB string or a path to a PDB file. sequence : str Amino acid sequence for SCWRL to pack in single-letter code. path : bool, optional True if pdb is a path. Returns ------- scwrl_p...
3.773519
3.716628
1.015307
self.pdb_parse_tree = {'info': {}, 'data': { self.state: {}} } try: for line in self.pdb_lines: self.current_line = line record_name = line[:6].strip() ...
def parse_pdb_file(self)
Runs the PDB parser.
4.160862
4.06298
1.024091
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] ...
def proc_atom(self)
Processes an "ATOM" or "HETATM" record.
2.654623
2.572671
1.031855
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...
def proc_line_coordinate(self, line)
Extracts data from columns in ATOM/HETATM record.
1.858721
1.809087
1.027436
data = self.pdb_parse_tree['data'] if len(data) > 1: ac = AmpalContainer(id=self.id) for state, chains in sorted(data.items()): if chains: ac.append(self.proc_state(chains, self.id + '_stat...
def make_ampal(self)
Generates an AMPAL object from the parse tree. Notes ----- Will create an `Assembly` if there is a single state in the parese tree or an `AmpalContainer` if there is more than one.
4.758408
4.122173
1.154345
assembly = Assembly(assembly_id=state_id) for k, chain in sorted(state_data.items()): assembly._molecules.append(self.proc_chain(chain, assembly)) return assembly
def proc_state(self, state_data, state_id)
Processes a state into an `Assembly`. Parameters ---------- state_data : dict Contains information about the state, including all the per line structural data. state_id : str ID given to `Assembly` that represents the state.
6.618598
7.190119
0.920513
hetatom_filters = { 'nc_aas': self.check_for_non_canonical } polymer = False chain_labels, chain_data = chain_info chain_label = list(chain_labels)[0] monomer_types = {x[2] for x in chain_labels if x[2]} if ('P' in monomer_types) and ('N' in ...
def proc_chain(self, chain_info, parent)
Converts a chain into a `Polymer` type object. Parameters ---------- chain_info : (set, OrderedDict) Contains a set of chain labels and atom records. parent : ampal.Assembly `Assembly` used to assign `ampal_parent` on created `Polymer`. Raise...
3.670835
3.482665
1.054031
monomer_labels, monomer_data = monomer_info if len(monomer_labels) > 1: raise ValueError( 'Malformed PDB, single monomer id with ' 'multiple labels. {}'.format(monomer_labels)) else: monomer_label = list(monomer_labels)[0] ...
def proc_monomer(self, monomer_info, parent, mon_cls=False)
Processes a records into a `Monomer`. Parameters ---------- monomer_info : (set, OrderedDict) Labels and data for a monomer. parent : ampal.Polymer `Polymer` used to assign `ampal_parent` on created `Monomer`. mon_cls : `Monomer class or subcl...
3.330962
3.075725
1.082984
dna_antisense = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C' } antisense = [dna_antisense[x] for x in sequence[::-1]] return ''.join(antisense)
def generate_antisense_sequence(sequence)
Creates the antisense sequence of a DNA strand.
2.276459
2.070004
1.099737
strand1 = NucleicAcidStrand(sequence, phos_3_prime=phos_3_prime) duplex = cls(strand1) return duplex
def from_sequence(cls, sequence, phos_3_prime=False)
Creates a DNA duplex from a nucleotide sequence. Parameters ---------- sequence: str Nucleotide sequence. phos_3_prime: bool, optional If false the 5' and the 3' phosphor will be omitted.
4.273412
5.055422
0.845313
strand1 = NucleicAcidStrand.from_start_and_end( start, end, sequence, phos_3_prime=phos_3_prime) duplex = cls(strand1) return duplex
def from_start_and_end(cls, start, end, sequence, phos_3_prime=False)
Creates a DNA duplex from a start and end point. Parameters ---------- start: [float, float, float] Start of the build axis. end: [float, float, float] End of build axis. sequence: str Nucleotide sequence. ...
3.338124
4.947863
0.67466
rise_adjust = ( strand1.rise_per_nucleotide * strand1.axis.unit_tangent) * 2 strand2 = NucleicAcidStrand.from_start_and_end( strand1.helix_end - rise_adjust, strand1.helix_start - rise_adjust, generate_antisense_sequence(strand1.base_sequence), ph...
def generate_complementary_strand(strand1)
Takes a SingleStrandHelix and creates the antisense strand.
6.122128
5.776129
1.059901
if path: with open(in_rsa, 'r') as inf: rsa = inf.read() else: rsa = in_rsa[:] all_atoms, side_chains, main_chain, non_polar, polar = [ float(x) for x in rsa.splitlines()[-1].split()[1:]] return all_atoms, side_chains, main_chain, non_polar, polar
def total_accessibility(in_rsa, path=True)
Parses rsa file for the total surface accessibility data. Parameters ---------- in_rsa : str Path to naccess rsa file. path : bool Indicates if in_rsa is a path or a string. Returns ------- dssp_residues : 5-tuple(float) Total accessibility values for: [0] a...
3.435905
2.64034
1.301312
if path: with open(in_rsa, 'r') as inf: rsa = inf.read() else: rsa = in_rsa[:] residue_list = [x for x in rsa.splitlines()] rel_solv_acc_all_atoms = [ float(x[22:28]) for x in residue_list if x[0:3] == "RES" or x[0:3] == "HEM"] if get_total...
def extract_residue_accessibility(in_rsa, path=True, get_total=False)
Parses rsa file for solvent accessibility for each residue. Parameters ---------- in_rsa : str Path to naccess rsa file path : bool Indicates if in_rsa is a path or a string get_total : bool Indicates if the total accessibility from the file needs to be extracted. Co...
3.718338
3.222173
1.153985
aa_code = None if aa_letter != 'X': for key, val in standard_amino_acids.items(): if key == aa_letter: aa_code = val return aa_code
def get_aa_code(aa_letter)
Get three-letter aa code if possible. If not, return None. If three-letter code is None, will have to find this later from the filesystem. Parameters ---------- aa_letter : str One-letter amino acid code. Returns ------- aa_code : str, or None Three-letter aa code.
2.641123
3.544969
0.745034
aa_letter = 'X' for key, val in standard_amino_acids.items(): if val == aa_code: aa_letter = key return aa_letter
def get_aa_letter(aa_code)
Get one-letter version of aa_code if possible. If not, return 'X'. Parameters ---------- aa_code : str Three-letter amino acid code. Returns ------- aa_letter : str One-letter aa code. Default value is 'X'.
2.713205
3.95822
0.685461
letter = 'X' # Try to get content from PDBE. url_string = 'http://www.ebi.ac.uk/pdbe-srv/pdbechem/chemicalCompound/show/{0}'.format(code) r = requests.get(url_string) # Raise error if content not obtained. if not r.ok: raise IOError("Could not get to url {0}".format(url_string)) ...
def get_aa_info(code)
Get dictionary of information relating to a new amino acid code not currently in the database. Notes ----- Use this function to get a dictionary that is then to be sent to the function add_amino_acid_to_json(). use to fill in rows of amino_acid table for new amino acid code. Parameters -------...
4.706158
4.284837
1.098328
# If code is already in the dictionary, raise an error if (not force_add) and code in amino_acids_dict.keys(): raise IOError("{0} is already in the amino_acids dictionary, with values: {1}".format( code, amino_acids_dict[code])) # Prepare data to be added. add_code = code a...
def add_amino_acid_to_json(code, description, letter='X', modified=None, force_add=False)
Add an amino acid to the amino_acids.json file used to populate the amino_acid table. Parameters ---------- code : str New code to be added to amino acid table. description : str Description of the amino acid, e.g. 'amidated terminal carboxy group'. letter : str, optional On...
2.971246
2.915183
1.019232
n = len(polymers) instance = cls(n=n, auto_build=False) instance.major_radii = [x.major_radius for x in polymers] instance.major_pitches = [x.major_pitch for x in polymers] instance.major_handedness = [x.major_handedness for x in polymers] instance.aas = [x.num_m...
def from_polymers(cls, polymers)
Creates a `CoiledCoil` from a list of `HelicalHelices`. Parameters ---------- polymers : [HelicalHelix] List of `HelicalHelices`.
2.789082
2.734731
1.019874
instance = cls(n=n, auto_build=False) instance.aas = [aa] * n instance.phi_c_alphas = [phi_c_alpha] * n instance.minor_helix_types = [minor_helix_type] * n if major_pitch is not None: instance.major_pitches = [major_pitch] * n if major_radius is not N...
def from_parameters(cls, n, aa=28, major_radius=None, major_pitch=None, phi_c_alpha=26.42, minor_helix_type='alpha', auto_build=True)
Creates a `CoiledCoil` from defined super-helical parameters. Parameters ---------- n : int Oligomeric state aa : int, optional Number of amino acids per minor helix. major_radius : float, optional Radius of super helix. major_pitch : ...
1.689476
1.956615
0.863469
instance = cls.from_parameters( n=3, aa=aa, major_radius=major_radius, major_pitch=major_pitch, phi_c_alpha=0.0, minor_helix_type='collagen', auto_build=False) instance.major_handedness = ['r'] * 3 # default z-shifts taken from rise_per_residue of collagen helix ...
def tropocollagen( cls, aa=28, major_radius=5.0, major_pitch=85.0, auto_build=True)
Creates a model of a collagen triple helix. Parameters ---------- aa : int, optional Number of amino acids per minor helix. major_radius : float, optional Radius of super helix. major_pitch : float, optional Pitch of super helix. auto_...
5.851264
6.526417
0.896551
monomers = [HelicalHelix(major_pitch=self.major_pitches[i], major_radius=self.major_radii[i], major_handedness=self.major_handedness[i], aa=self.aas[i], minor_helix_type=s...
def build(self)
Builds a model of a coiled coil protein using input parameters.
4.066449
3.91022
1.039954
max_rad = 0 max_npnp = 0 for res, atoms in self.items(): if res != 'KEY': for atom, ff_params in self[res].items(): if max_rad < ff_params[1]: max_rad = ff_params[1] if max_npnp < ff_params[4]: ...
def find_max_rad_npnp(self)
Finds the maximum radius and npnp in the force field. Returns ------- (max_rad, max_npnp): (float, float) Maximum radius and npnp distance in the loaded force field.
2.987628
2.705401
1.10432
if self._parameter_struct_dict is None: self._parameter_struct_dict = self._make_ff_params_dict() elif self.auto_update_f_params: new_hash = hash( tuple([tuple(item) for sublist in self.values() for item in su...
def parameter_struct_dict(self)
Dictionary containing PyAtomData structs for the force field.
3.172491
2.980116
1.064553
if path: input_path = Path(input_file) if not input_path.exists(): print('No file found at', path) return None, None else: pathf = tempfile.NamedTemporaryFile() encoded_input = input_file.encode() pathf.write(encoded_input) pathf.seek(...
def run_reduce(input_file, path=True)
Runs reduce on a pdb or mmol file at the specified path. Notes ----- Runs Reduce programme to add missing protons to a PDB file. Parameters ---------- input_file : str Path to file to add protons to or structure in mmol/pdb format. path : bool, optional True if input_file i...
3.81107
3.467925
1.098948
if not path: if not pdb_name: raise NameError( "Cannot save an output for a temporary file without a PDB" "code specified") pdb_name = pdb_name.lower() output_path = Path(global_settings['structural_database']['path'], ...
def reduce_output_path(path=None, pdb_name=None)
Defines location of Reduce output files relative to input files.
3.180715
3.174959
1.001813
if path: output_path = reduce_output_path(path=input_file) else: output_path = reduce_output_path(pdb_name=pdb_name) if output_path.exists() and not force: return output_path reduce_mmol, reduce_message = run_reduce(input_file, path=path) if not reduce_mmol: retu...
def output_reduce(input_file, path=True, pdb_name=None, force=False)
Runs Reduce on a pdb or mmol file and creates a new file with the output. Parameters ---------- input_file : str or pathlib.Path Path to file to run Reduce on. path : bool True if input_file is a path. pdb_name : str PDB ID of protein. Required if providing string not path. ...
2.619364
2.486634
1.053377
output_paths = [] for path in path_list: output_path = output_reduce(path, force=force) if output_path: output_paths.append(output_path) return output_paths
def output_reduce_list(path_list, force=False)
Generates structure file with protons from a list of structure files.
1.98386
2.127195
0.932618
from ampal.pdb_parser import convert_pdb_to_ampal if path: input_path = Path(input_file) if not pdb_name: pdb_name = input_path.stem[:4] reduced_path = reduce_output_path(path=input_path) if reduced_path.exists() and not save_output and not force_save: ...
def assembly_plus_protons(input_file, path=True, pdb_name=None, save_output=False, force_save=False)
Returns an Assembly with protons added by Reduce. Notes ----- Looks for a pre-existing Reduce output in the standard location before running Reduce. If the protein contains oligosaccharides or glycans, use reduce_correct_carbohydrates. Parameters ---------- input_file : str or pathlib....
2.711999
2.540331
1.067577
start = numpy.array(start) end = numpy.array(end) if aa is None: rise_per_residue = _helix_parameters[helix_type][1] aa = int((numpy.linalg.norm(end - start) / rise_per_residue) + 1) instance = cls(aa=aa, helix_type=helix_type) instance.move_to(st...
def from_start_and_end(cls, start, end, aa=None, helix_type='alpha')
Creates a `Helix` between `start` and `end`. Parameters ---------- start : 3D Vector (tuple or list or numpy.array) The coordinate of the start of the helix primitive. end : 3D Vector (tuple or list or numpy.array) The coordinate of the end of the helix primitive...
3.346899
2.882899
1.160949
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...
def build(self)
Build straight helix along z-axis, starting with CA1 on x-axis
3.419156
3.203091
1.067455
start = numpy.array(start) end = numpy.array(end) if aa is None: minor_rise_per_residue = _helix_parameters[minor_helix_type][1] aa = int((numpy.linalg.norm(end - start) / minor_rise_per_residue) + 1) instance = cls( aa=a...
def from_start_and_end(cls, start, end, aa=None, major_pitch=225.8, major_radius=5.07, major_handedness='l', minor_helix_type='alpha', orientation=1, phi_c_alpha=0.0, minor_repeat=None)
Creates a `HelicalHelix` between a `start` and `end` point.
2.265069
2.145262
1.055847
return HelicalCurve.pitch_and_radius( self.major_pitch, self.major_radius, handedness=self.major_handedness)
def curve(self)
Curve of the super helix.
11.570708
10.813416
1.070033
curve = self.curve curve.axis_start = self.helix_start curve.axis_end = self.helix_end coords = curve.get_coords( n_points=(self.num_monomers + 1), spacing=self.minor_rise_per_residue) if self.orientation == -1: coords.reverse() return Pri...
def curve_primitive(self)
`Primitive` of the super-helical curve.
6.698062
5.576032
1.201224
return numpy.cos(numpy.deg2rad(self.curve.alpha)) * self.minor_rise_per_residue
def major_rise_per_monomer(self)
Rise along super-helical axis per monomer.
11.315506
8.874648
1.275037
if minor_repeat is None: minor_rpt = _helix_parameters[self.minor_helix_type][0] else: # precession angle in radians precession = self.curve.t_from_arc_length( minor_repeat * self.minor_rise_per_residue) if self.orientation == -1: ...
def minor_residues_per_turn(self, minor_repeat=None)
Calculates the number of residues per turn of the minor helix. Parameters ---------- minor_repeat : float, optional Hydrophobic repeat of the minor helix. Returns ------- minor_rpt : float Residues per turn of the minor helix.
4.801777
4.526391
1.06084
helical_helix = Polypeptide() primitive_coords = self.curve_primitive.coordinates helices = [Helix.from_start_and_end(start=primitive_coords[i], end=primitive_coords[i + 1], helix_type=self.minor_hel...
def build(self)
Builds the `HelicalHelix`.
3.709542
3.555718
1.043261
if (monomer_index < len(self)) and monomer_index != -1: adjacent_index = monomer_index + 1 elif (monomer_index == len(self)) or monomer_index == -1: adjacent_index = monomer_index - 1 else: raise ValueError( "centred_index ({0}) cannot...
def get_orient_angle(self, reference_point=numpy.array([0, 0, 0]), monomer_index=0, res_label='CA', radians=False)
Angle between reference_point and self[monomer_index][res_label]. Notes ----- Angle is calculated using the dihedral angle, with the second and third points coming from the curve_primitive. Parameters ---------- reference_point : list, tuple or numpy.array of l...
2.686847
2.358678
1.139133
if radians: angle = numpy.rad2deg(angle) for i in range(len(self.primitive) - 1): axis = self.primitive[i + 1]['CA'] - self.primitive[i]['CA'] point = self.primitive[i]['CA']._vector self[i].rotate(angle=angle, axis=axis, point=point) retu...
def rotate_monomers(self, angle, radians=False)
Rotates each Residue in the Polypeptide. Notes ----- Each monomer is rotated about the axis formed between its corresponding primitive `PseudoAtom` and that of the subsequent `Monomer`. Parameters ---------- angle : float Angle by which to r...
3.683799
3.739482
0.985109
if masses: elts = set([x.element for x in assembly.get_atoms()]) masses_dict = {e: element_data[e]['atomic mass'] for e in elts} pseudo_monomers = [] for chain in assembly: if isinstance(chain, Polypeptide): centres = OrderedDict() for r in chain.get_mono...
def side_chain_centres(assembly, masses=False)
PseudoGroup containing side_chain centres of each Residue in each Polypeptide in Assembly. Notes ----- Each PseudoAtom is a side-chain centre. There is one PseudoMonomer per chain in ampal (each containing len(chain) PseudoAtoms). The PseudoGroup has len(ampal) PseudoMonomers. Parameters -...
3.829701
3.321228
1.153098
condensed_distance_matrix = [] for h1, h2 in itertools.combinations(helices, 2): md = minimal_distance_between_lines(h1[0]['CA']._vector, h1[-1]['CA']._vector, h2[0]['CA']._vector, h2[-1]['CA']._vector, segments=True) condensed_distance_matrix.app...
def cluster_helices(helices, cluster_distance=12.0)
Clusters helices according to the minimum distance between the line segments representing their backbone. Notes ----- Each helix is represented as a line segement joining the CA of its first Residue to the CA if its final Residue. The minimal distance between pairwise line segments is calculated and st...
2.386075
2.174364
1.097367
pseudo_group = side_chain_centres(assembly=assembly, masses=False) pairs = itertools.permutations(pseudo_group, 2) kihs = [] for pp_1, pp_2 in pairs: for r in pp_1: close_atoms = pp_2.is_within(cutoff, r) # kihs occur between residue and (hole_size) closest side-chai...
def find_kihs(assembly, hole_size=4, cutoff=7.0)
KnobIntoHoles between residues of different chains in assembly. Notes ----- A KnobIntoHole is a found when the side-chain centre of a Residue a chain is close than (cutoff) Angstroms from at least (hole_size) side-chain centres of Residues of a different chain. Parameters ---------- assemb...
4.829885
4.266218
1.132123
segments = Assembly(assembly_id=polypeptide.ampal_parent.id) residues_in_polypeptide = list(sorted(residues.intersection(set(polypeptide.get_monomers())), key=lambda x: int(x.id))) if not residues_in_polypeptide: return segments # residue_pots conta...
def find_contiguous_packing_segments(polypeptide, residues, max_dist=10.0)
Assembly containing segments of polypeptide, divided according to separation of contiguous residues. Parameters ---------- polypeptide : Polypeptide residues : iterable containing Residues max_dist : float Separation beyond which splitting of Polymer occurs. Returns ------- seg...
2.674743
2.669248
1.002059
coords = [numpy.array(chains[0].primitive.coordinates)] orient_vector = polypeptide_vector(chains[0]) # Append the coordinates for the remaining chains, reversing the direction in antiparallel arrangements. for i, c in enumerate(chains[1:]): if is_acute(polypeptide_vector(c), orient_vector)...
def start_and_end_of_reference_axis(chains)
Get start and end coordinates that approximate the reference axis for a collection of chains (not necessarily all the same length). Parameters ---------- chains : [Polypeptide] Returns ------- start, end : numpy.array 3D start and end coordinates for defining the reference axis.
3.734079
3.559446
1.049062
prim = polypeptide.primitive q = find_foot(a=start, b=end, p=prim.coordinates[0]) ax = Axis(start=q, end=end) # flip axis if antiparallel to polypeptide_vector if not is_acute(polypeptide_vector(polypeptide), ax.unit_tangent): ax = Axis(start=end, end=q) arc_length = 0 points = ...
def gen_reference_primitive(polypeptide, start, end)
Generates a reference Primitive for a Polypeptide given start and end coordinates. Notes ----- Uses the rise_per_residue of the Polypeptide primitive to define the separation of points on the line joining start and end. Parameters ---------- polypeptide : Polypeptide start : numpy.arra...
5.430253
4.647195
1.168501
base_reg = 'abcdefg' start, end = start_and_end_of_reference_axis(helices) for h in helices: ref_axis = gen_reference_primitive(h, start=start, end=end) crangles = crick_angles(h, reference_axis=ref_axis, tag=False)[:-1] reg_fit = fit_heptad_register(crangles) exp_base =...
def tag_residues_with_heptad_register(helices)
tags Residues in input helices with heptad register. (Helices not required to be the same length). Parameters ---------- helices : [Polypeptide] Returns ------- None
5.771972
5.994874
0.962818
cutoff = float(cutoff) helices = Assembly([x for x in assembly.helices if len(x) >= min_helix_length]) if len(helices) <= 1: return None # reassign ampal_parents helices.relabel_polymers([x.ampal_parent.id for x in helices]) for i, h in enumerate(heli...
def from_helices(cls, assembly, cutoff=7.0, min_helix_length=8)
Generate KnobGroup from the helices in the assembly - classic socket functionality. Notes ----- Socket identifies knobs-into-holes (KIHs) packing motifs in protein structures. The following resources can provide more information: The socket webserver: http://coiledcoils.chm.bris...
3.635145
3.537827
1.027508
if cutoff > self.cutoff: raise ValueError("cutoff supplied ({0}) cannot be greater than self.cutoff ({1})".format(cutoff, self.cutoff)) return KnobGroup(monomers=[x for x in self.get...
def knob_subgroup(self, cutoff=7.0)
KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff.
5.716937
4.178782
1.368087
g = networkx.MultiDiGraph() edge_list = [(x.knob_helix, x.hole_helix, x.id, {'kih': x}) for x in self.get_monomers()] g.add_edges_from(edge_list) return g
def graph(self)
Returns MultiDiGraph from kihs. Nodes are helices and edges are kihs.
8.163834
5.073932
1.608976
edge_list = [e for e in g.edges(keys=True, data=True) if e[3]['kih'].max_kh_distance <= cutoff] if min_kihs > 0: c = Counter([(e[0], e[1]) for e in edge_list]) # list of nodes that share > min_kihs edges with at least one other node. node_list = set(list(iter...
def filter_graph(g, cutoff=7.0, min_kihs=2)
Get subgraph formed from edges that have max_kh_distance < cutoff. Parameters ---------- g : MultiDiGraph representing KIHs g is the output from graph_from_protein cutoff : float Socket cutoff in Angstroms. Default is 7.0. min_kihs : int ...
2.842443
2.504294
1.135028
g = self.filter_graph(self.graph, cutoff=cutoff, min_kihs=min_kihs) ccs = sorted(networkx.connected_component_subgraphs(g, copy=True), key=lambda x: len(x.nodes()), reverse=True) cc = ccs[cc_number] helices = [x for x in g.nodes() if x.number in ...
def get_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2)
Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles.
4.482304
4.140564
1.082535
g = networkx.DiGraph() for x in self.get_monomers(): for h in x.hole: g.add_edge(x.knob, h) return g
def daisy_chain_graph(self)
Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self.
5.810529
3.932915
1.47741
if max_path_length is None: max_path_length = len(self.ampal_parent) g = self.daisy_chain_graph paths = networkx.all_simple_paths(g, source=kih.knob, target=kih.knob, cutoff=max_path_length) return paths
def daisy_chains(self, kih, max_path_length=None)
Generator for daisy chains (complementary kihs) associated with a knob. Notes ----- Daisy chain graph is the directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self. Given a KnobIntoHole, the daisy chains are non-trivial paths in this grap...
4.255733
2.783479
1.528926
side_chain_atoms = self.knob_residue.side_chain if not side_chain_atoms: return self.knob_residue['CA'] distances = [distance(self.knob_residue['CB'], x) for x in side_chain_atoms] max_d = max(distances) knob_end_atoms = [atom for atom, d in zip(side_chain_at...
def knob_end(self)
Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom. Returns CA coordinates for GLY.
2.809347
2.503354
1.122233
try: knob_vector = self.knob_residue['CB'] - self.knob_residue['CA'] # exception for GLY residues (with no CB atom). except KeyError: return None hole_vector = self.hole_residues[2]['CA'] - self.hole_residues[1]['CA'] return angle_between_vectors(...
def packing_angle(self)
Angle between CA-CB of knob and CA(h1)-CA(h2). Returns None if knob is GLY.
5.558683
3.611986
1.538955
return max([distance(self.knob_end, h) for h in self.hole])
def max_knob_end_distance(self)
Maximum distance between knob_end and each of the hole side-chain centres.
9.291797
6.634243
1.400581
# scwrl scwrl = {} print('{BOLD}{HEADER}Generating configuration files for ISAMBARD.{END_C}\n' 'All required input can use tab completion for paths.\n' '{BOLD}Setting up SCWRL 4.0 (Recommended){END_C}'.format(**text_colours)) scwrl_path = get_user_path('Please provide a path to ...
def base_install()
Generates configuration setting for required functionality of ISAMBARD.
4.032086
3.739304
1.078299
# reduce print('{BOLD}Setting up Reduce (optional){END_C}'.format(**text_colours)) reduce = {} reduce_path = get_user_path('Please provide a path to your reduce executable.', required=False) reduce['path'] = str(reduce_path) reduce['folder'] = str(reduce_path.parent) if reduce_path else '' ...
def optional_install()
Generates configuration settings for optional functionality of ISAMBARD.
2.661107
2.64756
1.005117
pdb_str = write_pdb( [self], ' ' if not self.tags['chain_id'] else self.tags['chain_id']) return pdb_str
def pdb(self)
Generates a PDB string for the `PseudoMonomer`.
8.897793
6.344894
1.402355