code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def calc_average_parameters(parameter_layers): 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
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.
def heptad_register(self): 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...
Returns the calculated register of the coiled coil and the fit quality.
def buff_interaction_eval(cls, specification, sequences, parameters, **kwargs): instance = cls(specification, sequences, parameters, build_fn=default_build, eval_fn=buff_interaction...
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...
def rmsd_eval(cls, specification, sequences, parameters, reference_ampal, **kwargs): eval_fn = make_rmsd_eval(reference_ampal) instance = cls(specification, sequences, parameters, build_fn=default_build, ...
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 :...
def parse_individual(self, individual): 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_paramete...
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...
def _make_parameters(self): 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...
Converts a list of Parameters into DEAP format.
def assign_fitnesses(self, targets): 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.m...
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.
def log_results(self, output_path=None, run_id=None): 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 ...
Saves files for the minimization. Notes ----- Currently saves a logfile with best individual and a pdb of the best model.
def best_model(self): 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...
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.
def dynamic(cls, label, val_mean, val_range): return cls(label, ParameterType.DYNAMIC, (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 ...
def parse_scwrl_out(scwrl_std_out, scwrl_pdb): 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: ...
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...
def pack_sidechains(pdb, sequence, path=False): scwrl_std_out, scwrl_pdb = run_scwrl(pdb, sequence, path=path) return parse_scwrl_out(scwrl_std_out, scwrl_pdb)
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...
def parse_pdb_file(self): self.pdb_parse_tree = {'info': {}, 'data': { self.state: {}} } try: for line in self.pdb_lines: self.current_line = line record_...
Runs the PDB parser.
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['d...
Processes an "ATOM" or "HETATM" record.
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...
Extracts data from columns in ATOM/HETATM record.
def make_ampal(self): 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 + ...
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.
def proc_state(self, state_data, state_id): assembly = Assembly(assembly_id=state_id) for k, chain in sorted(state_data.items()): assembly._molecules.append(self.proc_chain(chain, assembly)) return assembly
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.
def proc_monomer(self, monomer_info, parent, mon_cls=False): 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:...
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...
def generate_antisense_sequence(sequence): dna_antisense = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C' } antisense = [dna_antisense[x] for x in sequence[::-1]] return ''.join(antisense)
Creates the antisense sequence of a DNA strand.
def from_sequence(cls, sequence, phos_3_prime=False): strand1 = NucleicAcidStrand(sequence, phos_3_prime=phos_3_prime) duplex = cls(strand1) return duplex
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.
def from_start_and_end(cls, start, end, sequence, phos_3_prime=False): strand1 = NucleicAcidStrand.from_start_and_end( start, end, sequence, phos_3_prime=phos_3_prime) duplex = cls(strand1) return duplex
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. ...
def generate_complementary_strand(strand1): 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_seq...
Takes a SingleStrandHelix and creates the antisense strand.
def total_accessibility(in_rsa, path=True): 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, ...
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...
def extract_residue_accessibility(in_rsa, path=True, get_total=False): 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 residu...
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...
def get_aa_code(aa_letter): 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
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.
def get_aa_letter(aa_code): aa_letter = 'X' for key, val in standard_amino_acids.items(): if val == aa_code: aa_letter = key return aa_letter
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'.
def get_aa_info(code): 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}"....
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 -------...
def add_amino_acid_to_json(code, description, letter='X', modified=None, force_add=False): # 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( ...
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...
def from_polymers(cls, polymers): 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 polymer...
Creates a `CoiledCoil` from a list of `HelicalHelices`. Parameters ---------- polymers : [HelicalHelix] List of `HelicalHelices`.
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): instance = cls(n=n, auto_build=False) instance.aas = [aa] * n instance.phi_c_alphas = [phi_c_alpha] * n ...
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 : ...
def tropocollagen( cls, aa=28, major_radius=5.0, major_pitch=85.0, auto_build=True): 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...
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_...
def build(self): monomers = [HelicalHelix(major_pitch=self.major_pitches[i], major_radius=self.major_radii[i], major_handedness=self.major_handedness[i], aa=self.aas[i], m...
Builds a model of a coiled coil protein using input parameters.
def find_max_rad_npnp(self): 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] ...
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.
def parameter_struct_dict(self): 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() ...
Dictionary containing PyAtomData structs for the force field.
def reduce_output_path(path=None, pdb_name=None): 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['struc...
Defines location of Reduce output files relative to input files.
def output_reduce(input_file, path=True, pdb_name=None, force=False): 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 = ...
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. ...
def output_reduce_list(path_list, force=False): 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
Generates structure file with protons from a list of structure files.
def assembly_plus_protons(input_file, path=True, pdb_name=None, save_output=False, force_save=False): 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] reduc...
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....
def from_start_and_end(cls, start, end, aa=None, helix_type='alpha'): 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) in...
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...
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_off...
Build straight helix along z-axis, starting with CA1 on x-axis
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): start = numpy.array(start) ...
Creates a `HelicalHelix` between a `start` and `end` point.
def curve(self): return HelicalCurve.pitch_and_radius( self.major_pitch, self.major_radius, handedness=self.major_handedness)
Curve of the super helix.
def curve_primitive(self): 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.r...
`Primitive` of the super-helical curve.
def major_rise_per_monomer(self): return numpy.cos(numpy.deg2rad(self.curve.alpha)) * self.minor_rise_per_residue
Rise along super-helical axis per monomer.
def minor_residues_per_turn(self, minor_repeat=None): 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_ris...
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.
def get_orient_angle(self, reference_point=numpy.array([0, 0, 0]), monomer_index=0, res_label='CA', radians=False): if (monomer_index < len(self)) and monomer_index != -1: adjacent_index = monomer_index + 1 elif (monomer_index == len(self)) or monomer_index ...
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...
def rotate_monomers(self, angle, radians=False): 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(...
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...
def side_chain_centres(assembly, masses=False): 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 = O...
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 -...
def cluster_helices(helices, cluster_distance=12.0): 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,...
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...
def find_kihs(assembly, hole_size=4, cutoff=7.0): 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...
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...
def find_contiguous_packing_segments(polypeptide, residues, max_dist=10.0): 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 n...
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...
def start_and_end_of_reference_axis(chains): 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 i...
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.
def gen_reference_primitive(polypeptide, start, end): 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 = A...
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...
def tag_residues_with_heptad_register(helices): 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 = ...
tags Residues in input helices with heptad register. (Helices not required to be the same length). Parameters ---------- helices : [Polypeptide] Returns ------- None
def knob_subgroup(self, cutoff=7.0): if cutoff > self.cutoff: raise ValueError("cutoff supplied ({0}) cannot be greater than self.cutoff ({1})".format(cutoff, self.cutoff)) return Kn...
KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff.
def graph(self): 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
Returns MultiDiGraph from kihs. Nodes are helices and edges are kihs.
def filter_graph(g, cutoff=7.0, min_kihs=2): 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 othe...
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 ...
def get_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2): 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 = ...
Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles.
def daisy_chain_graph(self): g = networkx.DiGraph() for x in self.get_monomers(): for h in x.hole: g.add_edge(x.knob, h) return g
Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self.
def daisy_chains(self, kih, max_path_length=None): 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
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...
def knob_end(self): 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 ...
Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom. Returns CA coordinates for GLY.
def packing_angle(self): 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'] retu...
Angle between CA-CB of knob and CA(h1)-CA(h2). Returns None if knob is GLY.
def max_knob_end_distance(self): return max([distance(self.knob_end, h) for h in self.hole])
Maximum distance between knob_end and each of the hole side-chain centres.
def base_install(): # 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('Pleas...
Generates configuration setting for required functionality of ISAMBARD.
def optional_install(): # 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)...
Generates configuration settings for optional functionality of ISAMBARD.
def pdb(self): pdb_str = write_pdb( [self], ' ' if not self.tags['chain_id'] else self.tags['chain_id']) return pdb_str
Generates a PDB string for the `PseudoMonomer`.
def from_coordinates(cls, coordinates): prim = cls() for coord in coordinates: pm = PseudoMonomer(ampal_parent=prim) pa = PseudoAtom(coord, ampal_parent=pm) pm.atoms = OrderedDict([('CA', pa)]) prim.append(pm) prim.relabel_all() re...
Creates a `Primitive` from a list of coordinates.
def rise_per_residue(self): rprs = [distance(self[i]['CA'], self[i + 1]['CA']) for i in range(len(self) - 1)] rprs.append(None) return rprs
The rise per residue at each point on the Primitive. Notes ----- Each element of the returned list is the rise per residue, at a point on the Primitive. Element i is the distance between primitive[i] and primitive[i + 1]. The final value is None.
def radii_of_curvature(self): rocs = [] for i in range(len(self)): if 0 < i < len(self) - 1: rocs.append(radius_of_circumcircle( self[i - 1]['CA'], self[i]['CA'], self[i + 1]['CA'])) else: rocs.append(None) retu...
The radius of curvature at each point on the Polymer primitive. Notes ----- Each element of the returned list is the radius of curvature, at a point on the Polymer primitive. Element i is the radius of the circumcircle formed from indices [i-1, i, i+1] of the primitve. T...
def sequence(self): seq = [x.mol_code for x in self._monomers] return ' '.join(seq)
Returns the sequence of the `Polynucleotide` as a string. Returns ------- sequence : str String of the monomer sequence of the `Polynucleotide`.
def run_dssp(pdb, path=True, outfile=None): if not path: if type(pdb) == str: pdb = pdb.encode() try: temp_pdb = tempfile.NamedTemporaryFile(delete=False) temp_pdb.write(pdb) temp_pdb.seek(0) dssp_out = subprocess.check_output( ...
Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters ---------- pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. outfile : str, optional Filepath for storing the dssp output. Returns ...
def extract_solvent_accessibility_dssp(in_dssp, path=True): if path: with open(in_dssp, 'r') as inf: dssp_out = inf.read() else: dssp_out = in_dssp[:] dssp_residues = [] go = False for line in dssp_out.splitlines(): if go: try: res...
Uses DSSP to extract solvent accessibilty information on every residue. Notes ----- For more information on the solvent accessibility metrics used in dssp, see: http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC In the dssp files value is labeled 'ACC'. Parameters ---------- in_dssp...
def extract_helices_dssp(in_pdb): from ampal.pdb_parser import split_pdb_lines dssp_out = subprocess.check_output( [global_settings['dssp']['path'], in_pdb]) helix = 0 helices = [] h_on = False for line in dssp_out.splitlines(): dssp_line = line.split() try: ...
Uses DSSP to find alpha-helices and extracts helices from a pdb file. Returns a length 3 list with a helix id, the chain id and a dict containing the coordinates of each residues CA. Parameters ---------- in_pdb : string Path to a PDB file.
def find_ss_regions(dssp_residues): loops = [' ', 'B', 'S', 'T'] current_ele = None fragment = [] fragments = [] first = True for ele in dssp_residues: if first: first = False fragment.append(ele) elif current_ele in loops: if ele[1] in l...
Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered into a separate list, and so on. Parameters ---------- dssp_residues :...
def memory(): mem_info = {} if platform.linux_distribution()[0]: with open('/proc/meminfo') as file: c = 0 for line in file: lst = line.split() if str(lst[0]) == 'MemTotal:': mem_info['total'] = int(lst[1]) ...
Determine the machine's memory specifications. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system.
def get_chunk_size(N, n): mem_free = memory()['free'] if mem_free > 60000000: chunks_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunks_size elif mem_free > 40000000: chunks_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunks_size ...
Given a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimension of a two-dimensional array. n : int The number of times an 'N' by 'chunks_size' array can fit in memory. Return...
def all_floating_ips(self): if self.api_version == 2: json = self.request('/floating_ips') return json['floating_ips'] else: raise DoError(v2_api_required_str)
Lists all of the Floating IPs available on the account.
def new_floating_ip(self, **kwargs): droplet_id = kwargs.get('droplet_id') region = kwargs.get('region') if self.api_version == 2: if droplet_id is not None and region is not None: raise DoError('Only one of droplet_id and region is required to create a Floa...
Creates a Floating IP and assigns it to a Droplet or reserves it to a region.
def destroy_floating_ip(self, ip_addr): if self.api_version == 2: self.request('/floating_ips/' + ip_addr, method='DELETE') else: raise DoError(v2_api_required_str)
Deletes a Floating IP and removes it from the account.
def assign_floating_ip(self, ip_addr, droplet_id): if self.api_version == 2: params = {'type': 'assign','droplet_id': droplet_id} json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST') return json['action'] else: ...
Assigns a Floating IP to a Droplet.
def unassign_floating_ip(self, ip_addr): if self.api_version == 2: params = {'type': 'unassign'} json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST') return json['action'] else: raise DoError(v2_api_required_...
Unassign a Floating IP from a Droplet. The Floating IP will be reserved in the region but not assigned to a Droplet.
def list_floating_ip_actions(self, ip_addr): if self.api_version == 2: json = self.request('/floating_ips/' + ip_addr + '/actions') return json['actions'] else: raise DoError(v2_api_required_str)
Retrieve a list of all actions that have been executed on a Floating IP.
def get_floating_ip_action(self, ip_addr, action_id): if self.api_version == 2: json = self.request('/floating_ips/' + ip_addr + '/actions/' + action_id) return json['action'] else: raise DoError(v2_api_required_str)
Retrieve the status of a Floating IP action.
def raw_sign(message, secret): digest = hmac.new(secret, message, hashlib.sha256).digest() return base64.b64encode(digest)
Sign a message.
def http_signature(message, key_id, signature): template = ('Signature keyId="%(keyId)s",algorithm="hmac-sha256",' 'headers="%(headers)s",signature="%(signature)s"') headers = ['(request-target)', 'host', 'accept', 'date'] return template % { 'keyId': key_id, 'signature'...
Return a tuple (message signature, HTTP header message signature).
def get_signature_from_signature_string(self, signature): match = self.SIGNATURE_RE.search(signature) if not match: return None return match.group(1)
Return the signature from the signature header or None.
def get_headers_from_signature(self, signature): match = self.SIGNATURE_HEADERS_RE.search(signature) if not match: return ['date'] headers_string = match.group(1) return headers_string.split()
Returns a list of headers fields to sign. According to http://tools.ietf.org/html/draft-cavage-http-signatures-03 section 2.1.3, the headers are optional. If not specified, the single value of "Date" must be used.
def header_canonical(self, header_name): # Translate as stated in the docs: # https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META header_name = header_name.lower() if header_name == 'content-type': return 'CONTENT-TYPE' el...
Translate HTTP headers to Django header names.
def build_dict_to_sign(self, request, signature_headers): d = {} for header in signature_headers: if header == '(request-target)': continue d[header] = request.META.get(self.header_canonical(header)) return d
Build a dict with headers and values used in the signature. "signature_headers" is a list of lowercase header names.
def build_signature(self, user_api_key, user_secret, request): path = request.get_full_path() sent_signature = request.META.get( self.header_canonical('Authorization')) signature_headers = self.get_headers_from_signature(sent_signature) unsigned = self.build_dict_to_...
Return the signature for the request.
def camel_to_snake_case(string): s = _1.sub(r'\1_\2', string) return _2.sub(r'\1_\2', s).lower()
Converts 'string' presented in camel case to snake case. e.g.: CamelCase => snake_case
def url_assembler(query_string, no_redirect=0, no_html=0, skip_disambig=0): params = [('q', query_string.encode("utf-8")), ('format', 'json')] if no_redirect: params.append(('no_redirect', 1)) if no_html: params.append(('no_html', 1)) if skip_disambig: params.append(('skip_...
Assembler of parameters for building request query. Args: query_string: Query to be passed to DuckDuckGo API. no_redirect: Skip HTTP redirects (for !bang commands). Default - False. no_html: Remove HTML from text, e.g. bold and italics. Default - False. skip_disambig: Skip disambigu...
def _import(module, cls): global Scanner try: cls = str(cls) mod = __import__(str(module), globals(), locals(), [cls], 1) Scanner = getattr(mod, cls) except ImportError: pass
A messy way to import library-specific classes. TODO: I should really make a factory class or something, but I'm lazy. Plus, factories remind me a lot of java...
def create(type_dict, *type_parameters): assert len(type_parameters) == 1 klazz = TypeFactory.new(type_dict, *type_parameters[0]) assert isclass(klazz) assert issubclass(klazz, Object) return TypeMetaclass('%sList' % klazz.__name__, (ListContainer,), {'TYPE': klazz})
Construct a List containing type 'klazz'.
def load_file(filename): "Runs the given scent.py file." mod_name = '.'.join(os.path.basename(filename).split('.')[:-1]) mod_path = os.path.dirname(filename) if mod_name in sys.modules: del sys.modules[mod_name] if mod_path not in set(sys.modules.keys()): sys.path.insert(0, mod_path...
Runs the given scent.py file.
def exec_from_dir(dirname=None, scent="scent.py"): if dirname is None: dirname = os.getcwd() files = os.listdir(dirname) if scent not in files: return None return load_file(os.path.join(dirname, scent))
Runs the scent.py file from the given directory (cwd if None given). Returns module if loaded a scent, None otherwise.
def new(type_dict, type_factory, *type_parameters): type_tuple = (type_factory,) + type_parameters if type_tuple not in type_dict: factory = TypeFactory.get_factory(type_factory) reified_type = factory.create(type_dict, *type_parameters) type_dict[type_tuple] = reified_type return typ...
Create a fully reified type from a type schema.
def load(type_tuple, into=None): type_dict = {} TypeFactory.new(type_dict, *type_tuple) deposit = into if (into is not None and isinstance(into, dict)) else {} for reified_type in type_dict.values(): deposit[reified_type.__name__] = reified_type return deposit
Determine all types touched by loading the type and deposit them into the particular namespace.
def load_json(json_list, into=None): def l2t(obj): if isinstance(obj, list): return tuple(l2t(L) for L in obj) elif isinstance(obj, dict): return frozendict(obj) else: return obj return TypeFactory.load(l2t(json_list), into=into)
Determine all types touched by loading the type and deposit them into the particular namespace.
def create(type_dict, *type_parameters): name, values = type_parameters assert isinstance(values, (list, tuple)) for value in values: assert isinstance(value, Compatibility.stringy) return TypeMetaclass(str(name), (EnumContainer,), { 'VALUES': values })
EnumFactory.create(*type_parameters) expects: enumeration name, (enumeration values)