text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Updates the population according to crossover and fitness criteria. <END_TASK> <USER_TASK:> Description: def update_pop(self): """Updates the population according to crossover and fitness criteria. """
candidates = [] for ind in self.population: candidates.append(self.crossover(ind)) self._params['model_count'] += len(candidates) self.assign_fitnesses(candidates) for i in range(len(self.population)): if candidates[i].fitness > self.population[i].fitness: self.population[i] = candidates[i]
<SYSTEM_TASK:> Generates initial population with random positions and speeds. <END_TASK> <USER_TASK:> Description: def initialize_pop(self): """Generates initial population with random positions and speeds."""
self.population = self.toolbox.swarm(n=self._params['popsize']) if self._params['neighbours']: for i in range(len(self.population)): self.population[i].ident = i self.population[i].neighbours = list( set( [(i - x) % len(self.population) for x in range(1, self._params['neighbours'] + 1)] + [i] + [(i + x) % len(self.population) for x in range(1, self._params['neighbours'] + 1)] )) else: for i in range(len(self.population)): self.population[i].ident = i self.population[i].neighbours = [ x for x in range(len(self.population))] self.assign_fitnesses(self.population) for part in self.population: part.best = creator.Particle(part) part.best.fitness.values = part.fitness.values
<SYSTEM_TASK:> Assigns initial fitnesses. <END_TASK> <USER_TASK:> Description: def initialize_pop(self): """Assigns initial fitnesses."""
self.toolbox.register("individual", self.generate) self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual) self.population = self.toolbox.population(n=self._params['popsize']) self.assign_fitnesses(self.population) self._params['model_count'] += len(self.population)
<SYSTEM_TASK:> Creates a randomly the proposed value. <END_TASK> <USER_TASK:> Description: def randomise_proposed_value(self): """Creates a randomly the proposed value. Raises ------ TypeError Raised if this method is called on a static value. TypeError Raised if the parameter type is unknown. """
if self.parameter_type is MMCParameterType.UNIFORM_DIST: (a, b) = self.static_dist_or_list self.proposed_value = random.uniform(a, b) elif self.parameter_type is MMCParameterType.NORMAL_DIST: (mu, sigma) = self.static_dist_or_list self.proposed_value = random.normalvariate(mu, sigma) elif self.parameter_type is MMCParameterType.DISCRETE_RANGE: (min_v, max_v, step) = self.static_dist_or_list self.proposed_value = random.choice( numpy.arange(min_v, max_v, step)) elif self.parameter_type is MMCParameterType.LIST: self.proposed_value = random.choice(self.static_dist_or_list) elif self.parameter_type is MMCParameterType.STATIC_VALUE: raise TypeError('This value is static, it cannot be mutated.') else: raise TypeError( 'Cannot randomise this parameter, unknown parameter type.') return
<SYSTEM_TASK:> Changes the current value to the proposed value. <END_TASK> <USER_TASK:> Description: def accept_proposed_value(self): """Changes the current value to the proposed value."""
if self.proposed_value is not None: self.current_value = self.proposed_value self.proposed_value = None return
<SYSTEM_TASK:> Begin the optimisation run. <END_TASK> <USER_TASK:> Description: def start_optimisation(self, rounds, temp=298.15): """Begin the optimisation run. Parameters ---------- rounds : int The number of rounds of optimisation to perform. temp : float, optional The temperature (in K) used during the optimisation. """
self._generate_initial_model() self._mmc_loop(rounds, temp=temp) return
<SYSTEM_TASK:> Creates the initial model for the optimistation. <END_TASK> <USER_TASK:> Description: def _generate_initial_model(self): """Creates the initial model for the optimistation. Raises ------ TypeError Raised if the model failed to build. This could be due to parameters being passed to the specification in the wrong format. """
initial_parameters = [p.current_value for p in self.current_parameters] try: initial_model = self.specification(*initial_parameters) except TypeError: raise TypeError( 'Failed to build initial model. Make sure that the input ' 'parameters match the number and order of arguements ' 'expected by the input specification.') initial_model.pack_new_sequences(self.sequences) self.current_energy = self.eval_function(initial_model) self.best_energy = copy.deepcopy(self.current_energy) self.best_parameters = copy.deepcopy(self.current_parameters) self.best_model = initial_model return
<SYSTEM_TASK:> The main MMC loop. <END_TASK> <USER_TASK:> Description: def _mmc_loop(self, rounds, temp=298.15, verbose=True): """The main MMC loop. Parameters ---------- rounds : int The number of rounds of optimisation to perform. temp : float, optional The temperature (in K) used during the optimisation. verbose : bool, optional If true, prints information about the run to std out. """
# TODO add weighted randomisation of altered variable current_round = 0 while current_round < rounds: modifiable = list(filter( lambda p: p.parameter_type is not MMCParameterType.STATIC_VALUE, self.current_parameters)) chosen_parameter = random.choice(modifiable) if chosen_parameter.parameter_type is MMCParameterType.UNIFORM_DIST: chosen_parameter.randomise_proposed_value() else: chosen_parameter.randomise_proposed_value() proposed_parameters = [ p.current_value if p.proposed_value is None else p.proposed_value for p in self.current_parameters] model = self.specification(*proposed_parameters) model.pack_new_sequences(self.sequences) proposed_energy = self.eval_function(model) # TODO Add proper logging if verbose: sys.stdout.write( '\rRound: {}, Current energy: {}, Proposed energy: {} ' '(best {}), {}. ' .format(current_round, float_f(self.current_energy), float_f(proposed_energy), float_f( self.best_energy), "ACCEPTED" if self.check_move( proposed_energy, self.current_energy, t=temp) else "DECLINED" )) sys.stdout.flush() if self.check_move(proposed_energy, self.current_energy, t=temp): for p in self.current_parameters: p.accept_proposed_value() self.current_energy = proposed_energy if self.current_energy < self.best_energy: self.best_energy = copy.deepcopy(self.current_energy) self.best_parameters = copy.deepcopy( self.current_parameters) self.best_model = model else: for p in self.current_parameters: p.reject_proposed_value() current_round += 1 return
<SYSTEM_TASK:> Used by the evolution process to generate a new individual. <END_TASK> <USER_TASK:> Description: def _crossover(self, ind): """Used by the evolution process to generate a new individual. Notes ----- This is a tweaked version of the classical DE crossover algorithm, the main difference that candidate parameters are generated using a lognormal distribution. Bound handling is achieved by resampling where the candidate solution exceeds +/-1 Parameters ---------- ind : deap individual Returns ------- y : deap individual An individual representing a candidate solution, to be assigned a fitness. """
if self.neighbours: a, b, c = random.sample([self.population[i] for i in ind.neighbours], 3) else: a, b, c = random.sample(self.population, 3) y = self.toolbox.clone(a) y.ident = ind.ident y.neighbours = ind.neighbours del y.fitness.values # y should now be a copy of ind with the vector elements from a ident = random.randrange(len(self.value_means)) for i, value in enumerate(y): if i == ident or random.random() < self.cxpb: entry = a[i] + random.lognormvariate(-1.2, 0.5) * \ self.diff_weight * (b[i] - c[i]) tries = 0 while abs(entry) > 1.0: tries += 1 entry = a[i] + random.lognormvariate(-1.2, 0.5) * \ self.diff_weight * (b[i] - c[i]) if tries > 10000: entry = a[i] y[i] = entry return y
<SYSTEM_TASK:> Generates a particle using the creator function. <END_TASK> <USER_TASK:> Description: def _generate(self): """Generates a particle using the creator function. Notes ----- Position and speed are uniformly randomly seeded within allowed bounds. The particle also has speed limit settings taken from global values. Returns ------- part : particle object A particle used during optimisation. """
part = creator.Particle( [random.uniform(-1, 1) for _ in range(len(self.value_means))]) part.speed = [ random.uniform(-self.max_speed, self.max_speed) for _ in range(len(self.value_means))] part.smin = -self.max_speed part.smax = self.max_speed part.ident = None part.neighbours = None return part
<SYSTEM_TASK:> Constriction factor update particle method. <END_TASK> <USER_TASK:> Description: def update_particle(self, part, chi=0.729843788, c=2.05): """Constriction factor update particle method. Notes ----- Looks for a list of neighbours attached to a particle and uses the particle's best position and that of the best neighbour. """
neighbour_pool = [self.population[i] for i in part.neighbours] best_neighbour = max(neighbour_pool, key=lambda x: x.best.fitness) ce1 = (c * random.uniform(0, 1) for _ in range(len(part))) ce2 = (c * random.uniform(0, 1) for _ in range(len(part))) ce1_p = map(operator.mul, ce1, map(operator.sub, part.best, part)) ce2_g = map(operator.mul, ce2, map( operator.sub, best_neighbour.best, part)) chi_list = [chi] * len(part) chi_list2 = [1 - chi] * len(part) a = map(operator.sub, map(operator.mul, chi_list, map(operator.add, ce1_p, ce2_g)), map(operator.mul, chi_list2, part.speed)) part.speed = list(map(operator.add, part.speed, a)) for i, speed in enumerate(part.speed): if speed < part.smin: part.speed[i] = part.smin elif speed > part.smax: part.speed[i] = part.smax part[:] = list(map(operator.add, part, part.speed)) return
<SYSTEM_TASK:> Makes an individual particle. <END_TASK> <USER_TASK:> Description: def _make_individual(self, paramlist): """Makes an individual particle."""
part = creator.Individual(paramlist) part.ident = None return part
<SYSTEM_TASK:> Number of .mmol files associated with code in the PDBE. <END_TASK> <USER_TASK:> Description: def number_of_mmols(code): """ Number of .mmol files associated with code in the PDBE. Notes ----- This function makes a series of calls to the PDBE website using the requests module. This can make it slow! Parameters ---------- code : str PDB code. Returns ------- num_mmols : int Raises ------ ValueError If no .mmol files are found at all. Could be due to erroneous input argument, or a problem with connecting to the PDBE. """
# If num_mmols is already known, return it if mmols_numbers: if code in mmols_numbers.keys(): mmol = mmols_numbers[code][0] return mmol counter = 1 while True: pdbe_url = "http://www.ebi.ac.uk/pdbe/static/entry/download/{0}-assembly-{1}.cif.gz".format(code, counter) r = requests.get(pdbe_url) if r.status_code == 200: counter += 1 else: break if counter == 1: while True: pdb_url = "http://www.rcsb.org/pdb/files/{0}.pdb{1}.gz".format(code.upper(), counter) r = requests.get(pdb_url) if r.status_code == 200 and r.encoding is None: counter += 1 else: break if counter == 1: pdb_url = "http://files.rcsb.org/download/{0}.pdb".format(code.upper()) r = requests.get(pdb_url) if r.status_code == 200: counter += 1 num_mmols = counter - 1 if num_mmols == 0: raise ValueError('Could not access ANY .mmol files for {0}'.format(code)) return num_mmols
<SYSTEM_TASK:> Get mmol file from PDBe and return its content as a string. Write to file if outfile given. <END_TASK> <USER_TASK:> Description: def get_mmol(code, mmol_number=None, outfile=None): """ Get mmol file from PDBe and return its content as a string. Write to file if outfile given. Parameters ---------- code : str PDB code. mmol_number : int mmol number (biological assembly number) of file to download. Numbers from PDBe. If None, defaults to the preferred biological assembly listed for code on the PDBe. outfile : str Filepath. Writes returned value to this file. Returns ------- mmol_string : str, or None Content of the mmol file as a string. None if there are no pdbe files to download, as determined by pdbe_status_code(). None if unable to download the mmol_file from the pdbe site. Raises ------ ValueError If the number of mmols for code is stored in mmols_numbers and if mmol_number is larger than this value. """
if not mmol_number: try: mmol_number = preferred_mmol(code=code) except (ValueError, TypeError, IOError): print("No mmols for {0}".format(code)) return None # sanity check if mmols_numbers: if code in mmols_numbers.keys(): num_mmols = mmols_numbers[code][0] if mmol_number > num_mmols: raise ValueError('There are only {0} mmols for code {1}. mmol_number {2} is too big' .format(num_mmols, code, mmol_number)) # Download mmol file from the PDBE webserver. pdbe_url = "http://www.ebi.ac.uk/pdbe/entry-files/download/{0}_{1}.mmol".format(code, mmol_number) r = requests.get(pdbe_url) if r.status_code == 200: mmol_string = r.text else: # Download gz pdb file from the PDB. pdb_url = "http://www.rcsb.org/pdb/files/{0}.pdb{1}.gz".format(code.upper(), mmol_number) r = requests.get(pdb_url) if r.status_code == 200: temp_gz = tempfile.NamedTemporaryFile() temp_gz.write(r.content) with gzip.open(temp_gz.name, 'rb') as foo: mmol_string = foo.read().decode() else: print("Could not download mmol file for {0}.\n Got requests status_code {1}".format(code, r.status_code)) return None # Write to file if outfile and mmol_string: with open(outfile, 'w') as foo: foo.write(mmol_string) return mmol_string
<SYSTEM_TASK:> Get mmcif file associated with code from PDBE. <END_TASK> <USER_TASK:> Description: def get_mmcif(code, outfile=None): """ Get mmcif file associated with code from PDBE. Parameters ---------- code : str PDB code. outfile : str Filepath. Writes returned value to this file. Returns ------- mmcif_file : str Filepath to the mmcif file. """
pdbe_url = "http://www.ebi.ac.uk/pdbe/entry-files/download/{0}.cif".format(code) r = requests.get(pdbe_url) if r.status_code == 200: mmcif_string = r.text else: print("Could not download mmcif file for {0}".format(code)) mmcif_string = None # Write to file. if outfile and mmcif_string: with open(outfile, 'w') as foo: foo.write(mmcif_string) return mmcif_string
<SYSTEM_TASK:> Get mmol number of preferred biological assembly as listed in the PDBe. <END_TASK> <USER_TASK:> Description: def preferred_mmol(code): """ Get mmol number of preferred biological assembly as listed in the PDBe. Notes ----- First checks for code in mmols.json. If code not yet in this json dictionary, uses requests module to scrape the PDBE for the preferred mmol number. Parameters ---------- code : str A PDB code. Returns ------- mmol : int mmol number of preferred assembly. Raises ------ TypeError If 'mmol number' scraped is not an integer. """
# If preferred mmol number is already known, return it if code in mmols_numbers.keys(): mmol = mmols_numbers[code][1] return mmol elif is_obsolete(code): raise ValueError('Obsolete PDB code {0}'.format(code)) # Otherwise, use requests to scrape the PDBE. else: url_string = "http://www.ebi.ac.uk/pdbe/entry/pdb/{0}/analysis".format(code) r = requests.get(url_string) if not r.ok: raise IOError("Could not get to url {0}".format(url_string)) r_content = r.text ass = re.findall('Assembly\s\d+\s\(preferred\)', r_content) if len(ass) != 1: # To catch a strange error in the pdbe where preferred assembly is not numbered. See for example # http://www.ebi.ac.uk/pdbe/entry/pdb/7msi/analysis ass = re.findall('Assembly\s+\(preferred\)', r_content) if len(ass) == 1: return 1 obs = re.findall('Entry has been obsoleted and replaced by another entry \(OBS\)', r_content) if len(obs) == 1: rep = re.findall('by entry <a href="/pdbe/entry/pdb/\w{4}', r_content) if len(rep) == 1: rep = rep[0][-4:] raise IOError("{0} is obsolete and has been replaced by {1}.".format(code, rep)) raise ValueError("More than one match to preferred assembly") mmol = ass[0].split()[1] try: mmol = int(mmol) except TypeError: raise TypeError("Unexpected match: non-integer mmol") return mmol
<SYSTEM_TASK:> Get list of all PDB codes currently listed in the PDB. <END_TASK> <USER_TASK:> Description: def current_codes_from_pdb(): """ Get list of all PDB codes currently listed in the PDB. Returns ------- pdb_codes : list(str) List of PDB codes (in lower case). """
url = 'http://www.rcsb.org/pdb/rest/getCurrent' r = requests.get(url) if r.status_code == 200: pdb_codes = [x.lower() for x in r.text.split('"') if len(x) == 4] else: print('Request for {0} failed with status code {1}'.format(url, r.status_code)) return return pdb_codes
<SYSTEM_TASK:> Dict of filepaths for all mmol files associated with code. <END_TASK> <USER_TASK:> Description: def mmols(self): """ Dict of filepaths for all mmol files associated with code. Notes ----- Downloads mmol files if not already present. Returns ------- mmols_dict : dict, or None. Keys : int mmol number Values : str Filepath for the corresponding mmol file. """
mmols_dict = {} mmol_dir = os.path.join(self.parent_dir, 'structures') if not os.path.exists(mmol_dir): os.makedirs(mmol_dir) mmol_file_names = ['{0}_{1}.mmol'.format(self.code, i) for i in range(1, self.number_of_mmols + 1)] mmol_files = [os.path.join(mmol_dir, x) for x in mmol_file_names] for i, mmol_file in enumerate(mmol_files): mmols_dict[i + 1] = mmol_file # If file does not exist yet, download the mmol and write to mmol_file. if not os.path.exists(mmol_file): get_mmol(self.code, mmol_number=i + 1, outfile=mmol_file) return mmols_dict
<SYSTEM_TASK:> Dict of filepaths for all dssp files associated with code. <END_TASK> <USER_TASK:> Description: def dssps(self): """ Dict of filepaths for all dssp files associated with code. Notes ----- Runs dssp and stores writes output to files if not already present. Also downloads mmol files if not already present. Calls isambard.external_programs.dssp and so needs dssp to be installed. Returns ------- dssps_dict : dict, or None. Keys : int mmol number Values : str Filepath for the corresponding dssp file. Raises ------ Warning If any of the dssp files are empty. """
dssps_dict = {} dssp_dir = os.path.join(self.parent_dir, 'dssp') if not os.path.exists(dssp_dir): os.makedirs(dssp_dir) for i, mmol_file in self.mmols.items(): dssp_file_name = '{0}.dssp'.format(os.path.basename(mmol_file)) dssp_file = os.path.join(dssp_dir, dssp_file_name) if not os.path.exists(dssp_file): dssp_out = run_dssp(pdb=mmol_file, path=True, outfile=dssp_file) if len(dssp_out) == 0: raise Warning("dssp file {0} is empty".format(dssp_file)) dssps_dict[i] = dssp_file return dssps_dict
<SYSTEM_TASK:> Dict of filepaths for all fasta files associated with code. <END_TASK> <USER_TASK:> Description: def fastas(self, download=False): """ Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False - this is definitely the recommended behaviour. Notes ----- Calls self.mmols, and so downloads mmol files if not already present. See .fasta property of isambard.ampal.base_ampal.Protein for more information. Returns ------- fastas_dict : dict, or None. Keys : int mmol number Values : str Filepath for the corresponding fasta file. """
fastas_dict = {} fasta_dir = os.path.join(self.parent_dir, 'fasta') if not os.path.exists(fasta_dir): os.makedirs(fasta_dir) for i, mmol_file in self.mmols.items(): mmol_name = os.path.basename(mmol_file) fasta_file_name = '{0}.fasta'.format(mmol_name) fasta_file = os.path.join(fasta_dir, fasta_file_name) if not os.path.exists(fasta_file): if download: pdb_url = "http://www.rcsb.org/pdb/files/fasta.txt?structureIdList={0}".format(self.code.upper()) r = requests.get(pdb_url) if r.status_code == 200: fasta_string = r.text else: fasta_string = None else: a = convert_pdb_to_ampal(mmol_file) # take first object if AmpalContainer (i.e. NMR structure). if type(a) == AmpalContainer: a = a[0] fasta_string = a.fasta with open(fasta_file, 'w') as foo: foo.write(fasta_string) fastas_dict[i] = fasta_file return fastas_dict
<SYSTEM_TASK:> Filepath for mmcif file associated with code. <END_TASK> <USER_TASK:> Description: def mmcif(self): """ Filepath for mmcif file associated with code. Notes ----- Downloads mmcif file if not already present. Returns ------- mmcif_file : str Filepath for the mmcif file. """
mmcif_dir = os.path.join(self.parent_dir, 'mmcif') if not os.path.exists(mmcif_dir): os.makedirs(mmcif_dir) mmcif_file_name = '{0}.cif'.format(self.code) mmcif_file = os.path.join(mmcif_dir, mmcif_file_name) if not os.path.exists(mmcif_file): get_mmcif(code=self.code, outfile=mmcif_file) return mmcif_file
<SYSTEM_TASK:> Returns the number of categories in `categories`. <END_TASK> <USER_TASK:> Description: def category_count(self): """Returns the number of categories in `categories`."""
category_dict = self.categories count_dict = {category: len( category_dict[category]) for category in category_dict} return count_dict
<SYSTEM_TASK:> Returns the molecular weight of the polypeptide sequence. <END_TASK> <USER_TASK:> Description: def sequence_molecular_weight(seq): """Returns the molecular weight of the polypeptide sequence. Notes ----- Units = Daltons Parameters ---------- seq : str Sequence of amino acids. """
if 'X' in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) return sum( [residue_mwt[aa] * n for aa, n in Counter(seq).items()]) + water_mass
<SYSTEM_TASK:> Returns the molar extinction coefficient of the sequence at 280 nm. <END_TASK> <USER_TASK:> Description: def sequence_molar_extinction_280(seq): """Returns the molar extinction coefficient of the sequence at 280 nm. Notes ----- Units = M/cm Parameters ---------- seq : str Sequence of amino acids. """
if 'X' in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) return sum([residue_ext_280[aa] * n for aa, n in Counter(seq).items()])
<SYSTEM_TASK:> Calculates the partial charge of the amino acid. <END_TASK> <USER_TASK:> Description: def partial_charge(aa, pH): """Calculates the partial charge of the amino acid. Parameters ---------- aa : str Amino acid single-letter code. pH : float pH of interest. """
difference = pH - residue_pka[aa] if residue_charge[aa] > 0: difference *= -1 ratio = (10 ** difference) / (1 + 10 ** difference) return ratio
<SYSTEM_TASK:> Calculates the total charge of the input polypeptide sequence. <END_TASK> <USER_TASK:> Description: def sequence_charge(seq, pH=7.4): """Calculates the total charge of the input polypeptide sequence. Parameters ---------- seq : str Sequence of amino acids. pH : float pH of interest. """
if 'X' in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) adj_protein_charge = sum( [partial_charge(aa, pH) * residue_charge[aa] * n for aa, n in Counter(seq).items()]) adj_protein_charge += ( partial_charge('N-term', pH) * residue_charge['N-term']) adj_protein_charge += ( partial_charge('C-term', pH) * residue_charge['C-term']) return adj_protein_charge
<SYSTEM_TASK:> Calculates the charge for pH 1-13. <END_TASK> <USER_TASK:> Description: def charge_series(seq, granularity=0.1): """Calculates the charge for pH 1-13. Parameters ---------- seq : str Sequence of amino acids. granularity : float, optional Granularity of pH values i.e. if 0.1 pH = [1.0, 1.1, 1.2...] """
if 'X' in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) ph_range = numpy.arange(1, 13, granularity) charge_at_ph = [sequence_charge(seq, ph) for ph in ph_range] return ph_range, charge_at_ph
<SYSTEM_TASK:> Calculates the isoelectric point of the sequence for ph 1-13. <END_TASK> <USER_TASK:> Description: def sequence_isoelectric_point(seq, granularity=0.1): """Calculates the isoelectric point of the sequence for ph 1-13. Parameters ---------- seq : str Sequence of amino acids. granularity : float, optional Granularity of pH values i.e. if 0.1 pH = [1.0, 1.1, 1.2...] """
if 'X' in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) ph_range, charge_at_ph = charge_series(seq, granularity) abs_charge_at_ph = [abs(ch) for ch in charge_at_ph] pi_index = min(enumerate(abs_charge_at_ph), key=lambda x: x[1])[0] return ph_range[pi_index]
<SYSTEM_TASK:> Calculates sidechain dihedral angles for a residue <END_TASK> <USER_TASK:> Description: def measure_sidechain_torsion_angles(residue, verbose=True): """Calculates sidechain dihedral angles for a residue Parameters ---------- residue : [ampal.Residue] `Residue` object. verbose : bool, optional If `true`, tells you when a residue does not have any known dihedral angles to measure. Returns ------- chi_angles: [float] Length depends on residue type, in range [-pi, pi] [0] = chi1 [if applicable] [1] = chi2 [if applicable] [2] = chi3 [if applicable] [3] = chi4 [if applicable] """
chi_angles = [] aa = residue.mol_code if aa not in side_chain_dihedrals: if verbose: print("Amino acid {} has no known side-chain dihedral".format(aa)) else: for set_atoms in side_chain_dihedrals[aa]: required_for_dihedral = set_atoms[0:4] try: angle = dihedral( residue[required_for_dihedral[0]]._vector, residue[required_for_dihedral[1]]._vector, residue[required_for_dihedral[2]]._vector, residue[required_for_dihedral[3]]._vector) chi_angles.append(angle) except KeyError as k: print("{0} atom missing from residue {1} {2} " "- can't assign dihedral".format( k, residue.mol_code, residue.id)) chi_angles.append(None) return chi_angles
<SYSTEM_TASK:> Calculates the dihedral angles for a list of backbone atoms. <END_TASK> <USER_TASK:> Description: def measure_torsion_angles(residues): """Calculates the dihedral angles for a list of backbone atoms. Parameters ---------- residues : [ampal.Residue] List of `Residue` objects. Returns ------- torsion_angles : (float, float, float) One triple for each residue, containing torsion angles in the range [-pi, pi]. [0] omega [1] phi [2] psi For the first residue, omega and phi are not defined. For the final residue, psi is not defined. Raises ------ ValueError If the number of input residues is less than 2. """
if len(residues) < 2: torsion_angles = [(None, None, None)] * len(residues) else: torsion_angles = [] for i in range(len(residues)): if i == 0: res1 = residues[i] res2 = residues[i + 1] omega = None phi = None try: psi = dihedral( res1['N']._vector, res1['CA']._vector, res1['C']._vector, res2['N']._vector) except KeyError as k: print("{0} atom missing - can't assign psi".format(k)) psi = None torsion_angles.append((omega, phi, psi)) elif i == len(residues) - 1: res1 = residues[i - 1] res2 = residues[i] try: omega = dihedral( res1['CA']._vector, res1['C']._vector, res2['N']._vector, res2['CA']._vector) except KeyError as k: print("{0} atom missing - can't assign omega".format(k)) omega = None try: phi = dihedral( res1['C']._vector, res2['N']._vector, res2['CA']._vector, res2['C']._vector) except KeyError as k: print("{0} atom missing - can't assign phi".format(k)) phi = None psi = None torsion_angles.append((omega, phi, psi)) else: res1 = residues[i - 1] res2 = residues[i] res3 = residues[i + 1] try: omega = dihedral( res1['CA']._vector, res1['C']._vector, res2['N']._vector, res2['CA']._vector) except KeyError as k: print("{0} atom missing - can't assign omega".format(k)) omega = None try: phi = dihedral( res1['C']._vector, res2['N']._vector, res2['CA']._vector, res2['C']._vector) except KeyError as k: print("{0} atom missing - can't assign phi".format(k)) phi = None try: psi = dihedral( res2['N']._vector, res2['CA']._vector, res2['C']._vector, res3['N']._vector) except KeyError as k: print("{0} atom missing - can't assign psi".format(k)) psi = None torsion_angles.append((omega, phi, psi)) return torsion_angles
<SYSTEM_TASK:> Returns local parameters for an oligomeric assembly. <END_TASK> <USER_TASK:> Description: def cc_to_local_params(pitch, radius, oligo): """Returns local parameters for an oligomeric assembly. Parameters ---------- pitch : float Pitch of assembly radius : float Radius of assembly oligo : int Oligomeric state of assembly Returns ------- pitchloc : float Local pitch of assembly (between 2 adjacent component helices) rloc : float Local radius of assembly alphaloc : float Local pitch-angle of assembly """
rloc = numpy.sin(numpy.pi / oligo) * radius alpha = numpy.arctan((2 * numpy.pi * radius) / pitch) alphaloc = numpy.cos((numpy.pi / 2) - ((numpy.pi) / oligo)) * alpha pitchloc = (2 * numpy.pi * rloc) / numpy.tan(alphaloc) return pitchloc, rloc, numpy.rad2deg(alphaloc)
<SYSTEM_TASK:> The number of residues per turn at each Monomer in the Polymer. <END_TASK> <USER_TASK:> Description: def residues_per_turn(p): """ The number of residues per turn at each Monomer in the Polymer. Notes ----- Each element of the returned list is the number of residues per turn, at a point on the Polymer primitive. Calculated using the relative positions of the CA atoms and the primitive of the Polymer. Element i is the calculated from the dihedral angle using the CA atoms of the Monomers with indices [i, i+1] and the corresponding atoms of the primitive. The final value is None. Parameters ---------- p : ampal.Polypeptide `Polypeptide` from which residues per turn will be calculated. Returns ------- rpts : [float] Residue per turn values. """
cas = p.get_reference_coords() prim_cas = p.primitive.coordinates dhs = [abs(dihedral(cas[i], prim_cas[i], prim_cas[i + 1], cas[i + 1])) for i in range(len(prim_cas) - 1)] rpts = [360.0 / dh for dh in dhs] rpts.append(None) return rpts
<SYSTEM_TASK:> Returns distances between the primitive of a Polymer and a reference_axis. <END_TASK> <USER_TASK:> Description: def polymer_to_reference_axis_distances(p, reference_axis, tag=True, reference_axis_name='ref_axis'): """Returns distances between the primitive of a Polymer and a reference_axis. Notes ----- Distances are calculated between each point of the Polymer primitive and the corresponding point in reference_axis. In the special case of the helical barrel, if the Polymer is a helix and the reference_axis represents the centre of the barrel, then this function returns the radius of the barrel at each point on the helix primitive. The points of the primitive and the reference_axis are run through in the same order, so take care with the relative orientation of the reference axis when defining it. Parameters ---------- p : ampal.Polymer reference_axis : list(numpy.array or tuple or list) Length of reference_axis must equal length of the Polymer. Each element of reference_axis represents a point in R^3. tag : bool, optional If True, tags the Chain with the reference axis coordinates and each Residue with its distance to the ref axis. Distances are stored at the Residue level, but refer to distances from the CA atom. reference_axis_name : str, optional Used to name the keys in tags at Chain and Residue level. Returns ------- distances : list(float) Distance values between corresponding points on the reference axis and the `Polymer` `Primitive`. Raises ------ ValueError If the Polymer and the reference_axis have unequal length. """
if not len(p) == len(reference_axis): raise ValueError( "The reference axis must contain the same number of points " "as the Polymer primitive.") prim_cas = p.primitive.coordinates ref_points = reference_axis.coordinates distances = [distance(prim_cas[i], ref_points[i]) for i in range(len(prim_cas))] if tag: p.tags[reference_axis_name] = reference_axis monomer_tag_name = 'distance_to_{0}'.format(reference_axis_name) for m, d in zip(p._monomers, distances): m.tags[monomer_tag_name] = d return distances
<SYSTEM_TASK:> Returns the Crick angle for each CA atom in the `Polymer`. <END_TASK> <USER_TASK:> Description: def crick_angles(p, reference_axis, tag=True, reference_axis_name='ref_axis'): """Returns the Crick angle for each CA atom in the `Polymer`. Notes ----- The final value is in the returned list is `None`, since the angle calculation requires pairs of points on both the primitive and reference_axis. Parameters ---------- p : ampal.Polymer Reference `Polymer`. reference_axis : list(numpy.array or tuple or list) Length of reference_axis must equal length of the Polymer. Each element of reference_axis represents a point in R^3. tag : bool, optional If `True`, tags the `Polymer` with the reference axis coordinates and each Residue with its Crick angle. Crick angles are stored at the Residue level, but are calculated using the CA atom. reference_axis_name : str, optional Used to name the keys in tags at Chain and Residue level. Returns ------- cr_angles : list(float) The crick angles in degrees for each CA atom of the Polymer. Raises ------ ValueError If the Polymer and the reference_axis have unequal length. """
if not len(p) == len(reference_axis): raise ValueError( "The reference axis must contain the same number of points" " as the Polymer primitive.") prim_cas = p.primitive.coordinates p_cas = p.get_reference_coords() ref_points = reference_axis.coordinates cr_angles = [ dihedral(ref_points[i], prim_cas[i], prim_cas[i + 1], p_cas[i]) for i in range(len(prim_cas) - 1)] cr_angles.append(None) if tag: p.tags[reference_axis_name] = reference_axis monomer_tag_name = 'crick_angle_{0}'.format(reference_axis_name) for m, c in zip(p._monomers, cr_angles): m.tags[monomer_tag_name] = c return cr_angles
<SYSTEM_TASK:> Alpha angle calculated using points on the primitive of helix and axis. <END_TASK> <USER_TASK:> Description: def alpha_angles(p, reference_axis, tag=True, reference_axis_name='ref_axis'): """Alpha angle calculated using points on the primitive of helix and axis. Notes ----- The final value is None, since the angle calculation requires pairs of points along the primitive and axis. This is a generalisation of the calculation used to measure the tilt of a helix in a coiled-coil with respect to the central axis of the coiled coil. Parameters ---------- p : ampal.Polymer Reference `Polymer`. reference_axis : list(numpy.array or tuple or list) Length of reference_axis must equal length of the Polymer. Each element of reference_axis represents a point in R^3. tag : bool, optional If `True`, tags the Chain with the reference axis coordinates and each Residue with its alpha angle. Alpha angles are stored at the Residue level, but are calculated using the CA atom. reference_axis_name : str, optional Used to name the keys in tags at Chain and Residue level. Returns ------- alphas : list of float The alpha angle for the Polymer at each point of its primitive, in degrees. Raises ------ ValueError If the Polymer and the reference_axis have unequal length. """
if not len(p) == len(reference_axis): raise ValueError( "The reference axis must contain the same number of points " "as the Polymer primitive.") prim_cas = p.primitive.coordinates ref_points = reference_axis.coordinates alphas = [abs(dihedral(ref_points[i + 1], ref_points[i], prim_cas[i], prim_cas[i + 1])) for i in range(len(prim_cas) - 1)] alphas.append(None) if tag: p.tags[reference_axis_name] = reference_axis monomer_tag_name = 'alpha_angle_{0}'.format(reference_axis_name) for m, a in zip(p._monomers, alphas): m.tags[monomer_tag_name] = a return alphas
<SYSTEM_TASK:> Average coordinates from a set of primitives calculated from Chains. <END_TASK> <USER_TASK:> Description: def reference_axis_from_chains(chains): """Average coordinates from a set of primitives calculated from Chains. Parameters ---------- chains : list(Chain) Returns ------- reference_axis : numpy.array The averaged (x, y, z) coordinates of the primitives for the list of Chains. In the case of a coiled coil barrel, this would give the central axis for calculating e.g. Crick angles. Raises ------ ValueError : If the Chains are not all of the same length. """
if not len(set([len(x) for x in chains])) == 1: raise ValueError("All chains must be of the same length") # First array in coords is the primitive coordinates of the first chain. # The orientation of the first chain orients the reference_axis. 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): coords.append(numpy.array(c.primitive.coordinates)) else: coords.append(numpy.flipud(numpy.array(c.primitive.coordinates))) # Average across the x, y and z coordinates to get the reference_axis # coordinates reference_axis = numpy.mean(numpy.array(coords), axis=0) return Primitive.from_coordinates(reference_axis)
<SYSTEM_TASK:> Flips reference axis if direction opposes the direction of the `Polymer`. <END_TASK> <USER_TASK:> Description: def flip_reference_axis_if_antiparallel( p, reference_axis, start_index=0, end_index=-1): """Flips reference axis if direction opposes the direction of the `Polymer`. Notes ----- If the angle between the vector for the Polymer and the vector for the reference_axis is > 90 degrees, then the reference axis is reversed. This is useful to run before running polymer_to_reference_axis_distances, crick_angles, or alpha_angles. For more information on the start and end indices, see chain_vector. Parameters ---------- p : ampal.Polymer Reference `Polymer`. reference_axis : list(numpy.array or tuple or list) Length of reference_axis must equal length of the Polymer. Each element of reference_axis represents a point in R^3. start_index : int, optional Default is 0 (start at the N-terminus of the Polymer) end_index : int, optional Default is -1 (start at the C-terminus of the Polymer) Returns ------- reference_axis : list(numpy.array or tuple or list) """
p_vector = polypeptide_vector( p, start_index=start_index, end_index=end_index) if is_acute(p_vector, reference_axis[end_index] - reference_axis[start_index]): reference_axis = numpy.flipud(reference_axis) return reference_axis
<SYSTEM_TASK:> Calculates running average of cas_coords with a fixed averaging window_length. <END_TASK> <USER_TASK:> Description: def make_primitive(cas_coords, window_length=3): """Calculates running average of cas_coords with a fixed averaging window_length. Parameters ---------- cas_coords : list(numpy.array or float or tuple) Each element of the list must have length 3. window_length : int, optional The number of coordinate sets to average each time. Returns ------- s_primitive : list(numpy.array) Each array has length 3. Raises ------ ValueError If the length of cas_coords is smaller than the window_length. """
if len(cas_coords) >= window_length: primitive = [] count = 0 for _ in cas_coords[:-(window_length - 1)]: group = cas_coords[count:count + window_length] average_x = sum([x[0] for x in group]) / window_length average_y = sum([y[1] for y in group]) / window_length average_z = sum([z[2] for z in group]) / window_length primitive.append(numpy.array([average_x, average_y, average_z])) count += 1 else: raise ValueError( 'A primitive cannot be generated for {0} atoms using a (too large) ' 'averaging window_length of {1}.'.format( len(cas_coords), window_length)) return primitive
<SYSTEM_TASK:> Generates smoothed primitive from a list of coordinates. <END_TASK> <USER_TASK:> Description: def make_primitive_smoothed(cas_coords, smoothing_level=2): """ Generates smoothed primitive from a list of coordinates. Parameters ---------- cas_coords : list(numpy.array or float or tuple) Each element of the list must have length 3. smoothing_level : int, optional Number of times to run the averaging. Returns ------- s_primitive : list(numpy.array) Each array has length 3. Raises ------ ValueError If the smoothing level is too great compared to the length of cas_coords. """
try: s_primitive = make_primitive(cas_coords) for x in range(smoothing_level): s_primitive = make_primitive(s_primitive) except ValueError: raise ValueError( 'Smoothing level {0} too high, try reducing the number of rounds' ' or give a longer Chain (curent length = {1}).'.format( smoothing_level, len(cas_coords))) return s_primitive
<SYSTEM_TASK:> Generates smoothed helix primitives and extrapolates lost ends. <END_TASK> <USER_TASK:> Description: def make_primitive_extrapolate_ends(cas_coords, smoothing_level=2): """Generates smoothed helix primitives and extrapolates lost ends. Notes ----- From an input list of CA coordinates, the running average is calculated to form a primitive. The smoothing_level dictates how many times to calculate the running average. A higher smoothing_level generates a 'smoother' primitive - i.e. the points on the primitive more closely fit a smooth curve in R^3. Each time the smoothing level is increased by 1, a point is lost from either end of the primitive. To correct for this, the primitive is extrapolated at the ends to approximate the lost values. There is a trade-off then between the smoothness of the primitive and its accuracy at the ends. Parameters ---------- cas_coords : list(numpy.array or float or tuple) Each element of the list must have length 3. smoothing_level : int Number of times to run the averaging. Returns ------- final_primitive : list(numpy.array) Each array has length 3. """
try: smoothed_primitive = make_primitive_smoothed( cas_coords, smoothing_level=smoothing_level) except ValueError: smoothed_primitive = make_primitive_smoothed( cas_coords, smoothing_level=smoothing_level - 1) # if returned smoothed primitive is too short, lower the smoothing # level and try again. if len(smoothed_primitive) < 3: smoothed_primitive = make_primitive_smoothed( cas_coords, smoothing_level=smoothing_level - 1) final_primitive = [] for ca in cas_coords: prim_dists = [distance(ca, p) for p in smoothed_primitive] closest_indices = sorted([x[0] for x in sorted( enumerate(prim_dists), key=lambda k: k[1])[:3]]) a, b, c = [smoothed_primitive[x] for x in closest_indices] ab_foot = find_foot(a, b, ca) bc_foot = find_foot(b, c, ca) ca_foot = (ab_foot + bc_foot) / 2 final_primitive.append(ca_foot) return final_primitive
<SYSTEM_TASK:> Extends an `AmpalContainer` with another `AmpalContainer`. <END_TASK> <USER_TASK:> Description: def extend(self, ampal_container): """Extends an `AmpalContainer` with another `AmpalContainer`."""
if isinstance(ampal_container, AmpalContainer): self._ampal_objects.extend(ampal_container) else: raise TypeError( 'Only AmpalContainer objects may be merged with ' 'an AmpalContainer.') return
<SYSTEM_TASK:> Compiles the PDB strings for each state into a single file. <END_TASK> <USER_TASK:> Description: def pdb(self): """Compiles the PDB strings for each state into a single file."""
header_title = '{:<80}\n'.format('HEADER {}'.format(self.id)) data_type = '{:<80}\n'.format('EXPDTA ISAMBARD Model') pdb_strs = [] for ampal in self: if isinstance(ampal, Assembly): pdb_str = ampal.make_pdb(header=False, footer=False) else: pdb_str = ampal.make_pdb() pdb_strs.append(pdb_str) merged_strs = 'ENDMDL\n'.join(pdb_strs) + 'ENDMDL\n' merged_pdb = ''.join([header_title, data_type, merged_strs]) return merged_pdb
<SYSTEM_TASK:> Sorts the `AmpalContainer` by a tag on the component objects. <END_TASK> <USER_TASK:> Description: def sort_by_tag(self, tag): """Sorts the `AmpalContainer` by a tag on the component objects. Parameters ---------- tag : str Key of tag used for sorting. """
return AmpalContainer(sorted(self, key=lambda x: x.tags[tag]))
<SYSTEM_TASK:> Adds a `Polymer` to the `Assembly`. <END_TASK> <USER_TASK:> Description: def append(self, item): """Adds a `Polymer` to the `Assembly`. Raises ------ TypeError Raised if other is any type other than `Polymer`. """
if isinstance(item, Polymer): self._molecules.append(item) else: raise TypeError( 'Only Polymer objects can be appended to an Assembly.') return
<SYSTEM_TASK:> Extends the `Assembly` with the contents of another `Assembly`. <END_TASK> <USER_TASK:> Description: def extend(self, assembly): """Extends the `Assembly` with the contents of another `Assembly`. Raises ------ TypeError Raised if other is any type other than `Assembly`. """
if isinstance(assembly, Assembly): self._molecules.extend(assembly) else: raise TypeError( 'Only Assembly objects may be merged with an Assembly.') return
<SYSTEM_TASK:> Retrieves all the `Monomers` from the `Assembly` object. <END_TASK> <USER_TASK:> Description: def get_monomers(self, ligands=True, pseudo_group=False): """Retrieves all the `Monomers` from the `Assembly` object. Parameters ---------- ligands : bool, optional If `true`, will include ligand `Monomers`. pseudo_group : bool, optional If `True`, will include pseudo atoms. """
base_filters = dict(ligands=ligands, pseudo_group=pseudo_group) restricted_mol_types = [x[0] for x in base_filters.items() if not x[1]] in_groups = [x for x in self.filter_mol_types(restricted_mol_types)] monomers = itertools.chain( *(p.get_monomers(ligands=ligands) for p in in_groups)) return monomers
<SYSTEM_TASK:> Retrieves all ligands from the `Assembly`. <END_TASK> <USER_TASK:> Description: def get_ligands(self, solvent=True): """Retrieves all ligands from the `Assembly`. Parameters ---------- solvent : bool, optional If `True`, solvent molecules will be included. """
if solvent: ligand_list = [x for x in self.get_monomers() if isinstance(x, Ligand)] else: ligand_list = [x for x in self.get_monomers() if isinstance( x, Ligand) and not x.is_solvent] return LigandGroup(monomers=ligand_list)
<SYSTEM_TASK:> Flat list of all the `Atoms` in the `Assembly`. <END_TASK> <USER_TASK:> Description: def get_atoms(self, ligands=True, pseudo_group=False, inc_alt_states=False): """ Flat list of all the `Atoms` in the `Assembly`. Parameters ---------- ligands : bool, optional Include ligand `Atoms`. pseudo_group : bool, optional Include pseudo_group `Atoms`. inc_alt_states : bool, optional Include alternate sidechain conformations. Returns ------- atoms : itertools.chain All the `Atoms` as a iterator. """
atoms = itertools.chain( *(list(m.get_atoms(inc_alt_states=inc_alt_states)) for m in self.get_monomers(ligands=ligands, pseudo_group=pseudo_group))) return atoms
<SYSTEM_TASK:> Returns all atoms in AMPAL object within `cut-off` distance from the `point`. <END_TASK> <USER_TASK:> Description: def is_within(self, cutoff_dist, point, ligands=True): """Returns all atoms in AMPAL object within `cut-off` distance from the `point`."""
return find_atoms_within_distance(self.get_atoms(ligands=ligands), cutoff_dist, point)
<SYSTEM_TASK:> Relabels the component Polymers either in alphabetical order or using a list of labels. <END_TASK> <USER_TASK:> Description: def relabel_polymers(self, labels=None): """Relabels the component Polymers either in alphabetical order or using a list of labels. Parameters ---------- labels : list, optional A list of new labels. Raises ------ ValueError Raised if the number of labels does not match the number of component Polymer objects. """
if labels: if len(self._molecules) == len(labels): for polymer, label in zip(self._molecules, labels): polymer.id = label else: raise ValueError('Number of polymers ({}) and number of labels ({}) must be equal.'.format( len(self._molecules), len(labels))) else: for i, polymer in enumerate(self._molecules): polymer.id = chr(i + 65) return
<SYSTEM_TASK:> Relabels all Atoms in numerical order, offset by the start parameter. <END_TASK> <USER_TASK:> Description: def relabel_atoms(self, start=1): """Relabels all Atoms in numerical order, offset by the start parameter. Parameters ---------- start : int, optional Defines an offset for the labelling. """
counter = start for atom in self.get_atoms(ligands=True): atom.id = counter counter += 1 return
<SYSTEM_TASK:> Generates a PDB string for the Assembly. <END_TASK> <USER_TASK:> Description: def make_pdb(self, ligands=True, alt_states=False, pseudo_group=False, header=True, footer=True): """Generates a PDB string for the Assembly. Parameters ---------- ligands : bool, optional If `True`, will include ligands in the output. alt_states : bool, optional If `True`, will include alternate conformations in the output. pseudo_group : bool, optional If `True`, will include pseudo atoms in the output. header : bool, optional If `True` will write a header for output. footer : bool, optional If `True` will write a footer for output. Returns ------- pdb_str : str String of the pdb for the Assembly. Generated by collating Polymer().pdb calls for the component Polymers. """
base_filters = dict(ligands=ligands, pseudo_group=pseudo_group) restricted_mol_types = [x[0] for x in base_filters.items() if not x[1]] in_groups = [x for x in self.filter_mol_types(restricted_mol_types)] pdb_header = 'HEADER {:<80}\n'.format( 'ISAMBARD Model {}'.format(self.id)) if header else '' pdb_body = ''.join([x.make_pdb( alt_states=alt_states, inc_ligands=ligands) + '{:<80}\n'.format('TER') for x in in_groups]) pdb_footer = '{:<80}\n'.format('END') if footer else '' pdb_str = ''.join([pdb_header, pdb_body, pdb_footer]) return pdb_str
<SYSTEM_TASK:> Generates a new `Assembly` containing only the backbone atoms. <END_TASK> <USER_TASK:> Description: def backbone(self): """Generates a new `Assembly` 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_assembly : ampal.Protein `Assembly` containing only the backbone atoms of the original `Assembly`. """
bb_molecules = [ p.backbone for p in self._molecules if hasattr(p, 'backbone')] bb_assembly = Assembly(bb_molecules, assembly_id=self.id) return bb_assembly
<SYSTEM_TASK:> Generates a new `Assembly` containing the primitives of each Polymer. <END_TASK> <USER_TASK:> Description: def primitives(self): """Generates a new `Assembly` containing the primitives of each Polymer. Notes ----- Metadata is not currently preserved from the parent object. Returns ------- prim_assembly : ampal.Protein `Assembly` containing only the primitives of the `Polymers` in the original `Assembly`. """
prim_molecules = [ p.primitive for p in self._molecules if hasattr(p, 'primitive')] prim_assembly = Assembly(molecules=prim_molecules, assembly_id=self.id) return prim_assembly
<SYSTEM_TASK:> Returns the sequence of each `Polymer` in the `Assembly` as a list. <END_TASK> <USER_TASK:> Description: def sequences(self): """Returns the sequence of each `Polymer` in the `Assembly` as a list. Returns ------- sequences : [str] List of sequences. """
seqs = [x.sequence for x in self._molecules if hasattr(x, 'sequence')] return seqs
<SYSTEM_TASK:> Generates a FASTA string for the `Assembly`. <END_TASK> <USER_TASK:> Description: def fasta(self): """Generates a FASTA string for the `Assembly`. Notes ----- Explanation of FASTA format: https://en.wikipedia.org/wiki/FASTA_format Recommendation that all lines of text be shorter than 80 characters is adhered to. Format of PDBID|CHAIN|SEQUENCE is consistent with files downloaded from the PDB. Uppercase PDBID used for consistency with files downloaded from the PDB. Useful for feeding into cdhit and then running sequence clustering. Returns ------- fasta_str : str String of the fasta file for the `Assembly`. """
fasta_str = '' max_line_length = 79 for p in self._molecules: if hasattr(p, 'sequence'): fasta_str += '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n'.format( self.id.upper(), p.id) seq = p.sequence split_seq = [seq[i: i + max_line_length] for i in range(0, len(seq), max_line_length)] for seq_part in split_seq: fasta_str += '{0}\n'.format(seq_part) return fasta_str
<SYSTEM_TASK:> Calculates the interaction energy of the AMPAL object. <END_TASK> <USER_TASK:> Description: def get_interaction_energy(self, assign_ff=True, ff=None, mol2=False, force_ff_assign=False): """Calculates the interaction energy of the AMPAL object. Parameters ---------- assign_ff: bool, optional If true the force field will be updated if required. ff: BuffForceField, optional The force field to be used for scoring. mol2: bool, optional If true, mol2 style labels will also be used. force_ff_assign: bool, optional If true, the force field will be completely reassigned, ignoring the cached parameters. Returns ------- buff_score: buff.BUFFScore A BUFFScore object with information about each of the interactions and the `Atoms` involved. Raises ------ AttributeError Raise if a component molecule does not have an `update_ff` method. """
if not ff: ff = global_settings['buff']['force_field'] if assign_ff: for molecule in self._molecules: if hasattr(molecule, 'update_ff'): molecule.update_ff( ff, mol2=mol2, force_ff_assign=force_ff_assign) else: raise AttributeError( 'The following molecule does not have a update_ff' 'method:\n{}\nIf this is a custom molecule type it' 'should inherit from BaseAmpal:'.format(molecule)) interactions = find_inter_ampal(self, ff.distance_cutoff) buff_score = score_interactions(interactions, ff) return buff_score
<SYSTEM_TASK:> Packs a new sequence onto each Polymer in the Assembly using Scwrl4. <END_TASK> <USER_TASK:> Description: def pack_new_sequences(self, sequences): """Packs a new sequence onto each Polymer in the Assembly using Scwrl4. Notes ----- The Scwrl packing score is saved in `Assembly.tags['scwrl_score']` for reference. Scwrl must be available to call. Check by running `isambard.external_programs.scwrl.test_scwrl`. If Scwrl is not available, please follow instruction here to add it: https://github.com/woolfson-group/isambard#external-programs For more information on Scwrl see [1]. References ---------- .. [1] Krivov GG, Shapovalov MV, and Dunbrack Jr RL (2009) "Improved prediction of protein side-chain conformations with SCWRL4.", Proteins. Parameters ---------- sequences : [str] A list of strings containing the amino acid sequence of each corresponding `Polymer`. These must be the same length as the `Polymer`. Raises ------ ValueError Raised if the sequence length does not match the number of monomers in the `Polymer`. """
from ampal.pdb_parser import convert_pdb_to_ampal assembly_bb = self.backbone total_seq_len = sum([len(x) for x in sequences]) total_aa_len = sum([len(x) for x in assembly_bb]) if total_seq_len != total_aa_len: raise ValueError('Total sequence length ({}) does not match ' 'total Polymer length ({}).'.format( total_seq_len, total_aa_len)) scwrl_out = pack_sidechains(self.backbone.pdb, ''.join(sequences)) if scwrl_out is None: return else: packed_structure, scwrl_score = scwrl_out new_assembly = convert_pdb_to_ampal(packed_structure, path=False) self._molecules = new_assembly._molecules[:] self.assign_force_field(global_settings[u'buff'][u'force_field']) self.tags['scwrl_score'] = scwrl_score return
<SYSTEM_TASK:> Repacks the side chains of all Polymers in the Assembly. <END_TASK> <USER_TASK:> Description: def repack_all(self): """Repacks the side chains of all Polymers in the Assembly."""
non_na_sequences = [s for s in self.sequences if ' ' not in s] self.pack_new_sequences(non_na_sequences) return
<SYSTEM_TASK:> Tags each `Monomer` in the `Assembly` with it's secondary structure. <END_TASK> <USER_TASK:> Description: def tag_secondary_structure(self, force=False): """Tags each `Monomer` in the `Assembly` with it's 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-group/isambard#external-programs For more information on DSSP see [1]. References ---------- .. [1] Kabsch W, Sander C (1983) "Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features", Biopolymers, 22, 2577-637. Parameters ---------- force : bool, optional If True the tag will be run even if `Monomers` are already tagged """
for polymer in self._molecules: if polymer.molecule_type == 'protein': polymer.tag_secondary_structure(force=force) return
<SYSTEM_TASK:> Tags each `Monomer` in the Assembly with its solvent accessibility. <END_TASK> <USER_TASK:> Description: def tag_dssp_solvent_accessibility(self, force=False): """Tags each `Monomer` in the Assembly 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 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-group/isambard#external-programs For more information on DSSP see [1]. References ---------- .. [1] Kabsch W, Sander C (1983) "Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features", Biopolymers, 22, 2577-637. Parameters ---------- force : bool, optional If True the tag will be run even if Monomers are already tagged """
for polymer in self._molecules: polymer.tag_dssp_solvent_accessibility(force=force) return
<SYSTEM_TASK:> Tags each `Monomer` in the `Assembly` with its torsion angles. <END_TASK> <USER_TASK:> Description: def tag_torsion_angles(self, force=False): """Tags each `Monomer` in the `Assembly` with its torsion angles. Parameters ---------- force : bool, optional If `True`, the tag will be run even if `Monomers` are already tagged. """
for polymer in self._molecules: if polymer.molecule_type == 'protein': polymer.tag_torsion_angles(force=force) return
<SYSTEM_TASK:> Tags each `Monomer` in the `Assembly` with its helical geometry. <END_TASK> <USER_TASK:> Description: def tag_ca_geometry(self, force=False, reference_axis=None, reference_axis_name='ref_axis'): """Tags each `Monomer` in the `Assembly` with its helical geometry. Parameters ---------- force : bool, optional If True the tag will be run even if `Monomers` are already tagged. reference_axis : list(numpy.array or tuple or list), optional Coordinates to feed to geometry functions that depend on having a reference axis. reference_axis_name : str, optional Used to name the keys in tags at `Chain` and `Residue` level. """
for polymer in self._molecules: if polymer.molecule_type == 'protein': polymer.tag_ca_geometry( force=force, reference_axis=reference_axis, reference_axis_name=reference_axis_name) return
<SYSTEM_TASK:> Tags each Atom in the Assembly with its unique_id. <END_TASK> <USER_TASK:> Description: def tag_atoms_unique_ids(self, force=False): """ Tags each Atom in the Assembly with its unique_id. Notes ----- The unique_id for each atom is a tuple (a double). `unique_id[0]` is the unique_id for its parent `Monomer` (see `Monomer.unique_id` for more information). `unique_id[1]` is the atom_type in the `Assembly` as a string, e.g. 'CA', 'CD2'. Parameters ---------- force : bool, optional If True the tag will be run even if Atoms are already tagged. If False, only runs if at least one Atom is not tagged. """
tagged = ['unique_id' in x.tags.keys() for x in self.get_atoms()] if (not all(tagged)) or force: for m in self.get_monomers(): for atom_type, atom in m.atoms.items(): atom.tags['unique_id'] = (m.unique_id, atom_type) return
<SYSTEM_TASK:> Converts a pro residue to a hydroxypro residue. <END_TASK> <USER_TASK:> Description: def convert_pro_to_hyp(pro): """Converts a pro residue to a hydroxypro residue. All metadata associated with the original pro will be lost i.e. tags. As a consequence, it is advisable to relabel all atoms in the structure in order to make them contiguous. Parameters ---------- pro: ampal.Residue The proline residue to be mutated to hydroxyproline. Examples -------- We can create a collagen model using isambard and convert every third residue to hydroxyproline: >>> import isambard >>> col = isambard.specifications.CoiledCoil.tropocollagen(aa=21) >>> col.pack_new_sequences(['GPPGPPGPPGPPGPPGPPGPP']*3) >>> to_convert = [ ... res for (i, res) in enumerate(col.get_monomers()) ... if not (i + 1) % 3] >>> for pro in to_convert: ... isambard.ampal.non_canonical.convert_pro_to_hyp(pro) >>> col.sequences ['GPXGPXGPXGPXGPXGPXGPX', 'GPXGPXGPXGPXGPXGPXGPX', 'GPXGPXGPXGPXGPXGPXGPX'] """
with open(str(REF_PATH / 'hydroxyproline_ref_1bkv_0_6.pickle'), 'rb') as inf: hyp_ref = pickle.load(inf) align_nab(hyp_ref, pro) to_remove = ['CB', 'CG', 'CD'] for (label, atom) in pro.atoms.items(): if atom.element == 'H': to_remove.append(label) for label in to_remove: del pro.atoms[label] for key, val in hyp_ref.atoms.items(): if key not in pro.atoms.keys(): pro.atoms[key] = val pro.mol_code = 'HYP' pro.mol_letter = 'X' pro.is_hetero = True pro.tags = {} pro.states = {'A': pro.atoms} pro.active_state = 'A' for atom in pro.get_atoms(): atom.ampal_parent = pro atom.tags = {'bfactor': 1.0, 'charge': ' ', 'occupancy': 1.0, 'state': 'A'} return
<SYSTEM_TASK:> Aligns the N-CA and CA-CB vector of the target monomer. <END_TASK> <USER_TASK:> Description: def align_nab(tar, ref): """Aligns the N-CA and CA-CB vector of the target monomer. Parameters ---------- tar: ampal.Residue The residue that will be aligned to the reference. ref: ampal.Residue The reference residue for the alignment. """
rot_trans_1 = find_transformations( tar['N'].array, tar['CA'].array, ref['N'].array, ref['CA'].array) apply_trans_rot(tar, *rot_trans_1) rot_ang_ca_cb = dihedral(tar['CB'], ref['CA'], ref['N'], ref['CB']) tar.rotate(rot_ang_ca_cb, ref['N'].array - ref['CA'].array, ref['N'].array) return
<SYSTEM_TASK:> Applies a translation and rotation to an AMPAL object. <END_TASK> <USER_TASK:> Description: def apply_trans_rot(ampal, translation, angle, axis, point, radians=False): """Applies a translation and rotation to an AMPAL object."""
if not numpy.isclose(angle, 0.0): ampal.rotate(angle=angle, axis=axis, point=point, radians=radians) ampal.translate(vector=translation) return
<SYSTEM_TASK:> Returns an `Assembly` of regions tagged as secondary structure. <END_TASK> <USER_TASK:> Description: def find_ss_regions_polymer(polymer, ss): """Returns an `Assembly` of regions tagged as secondary structure. Parameters ---------- polymer : Polypeptide `Polymer` object to be searched secondary structure regions. ss : list List of secondary structure tags to be separate i.e. ['H'] would return helices, ['H', 'E'] would return helices and strands. Returns ------- fragments : Assembly `Assembly` containing a `Polymer` for each region of specified secondary structure. """
if isinstance(ss, str): ss = [ss[:]] tag_key = 'secondary_structure' monomers = [x for x in polymer if tag_key in x.tags.keys()] if len(monomers) == 0: return Assembly() if (len(ss) == 1) and (all([m.tags[tag_key] == ss[0] for m in monomers])): return Assembly(polymer) previous_monomer = None fragment = Polypeptide(ampal_parent=polymer) fragments = Assembly() poly_id = 0 for monomer in monomers: current_monomer = monomer.tags[tag_key] if (current_monomer == previous_monomer) or (not previous_monomer): fragment.append(monomer) else: if previous_monomer in ss: fragment.tags[tag_key] = monomer.tags[tag_key] fragment.id = chr(poly_id + 65) fragments.append(fragment) poly_id += 1 fragment = Polypeptide(ampal_parent=polymer) fragment.append(monomer) previous_monomer = monomer.tags[tag_key] return fragments
<SYSTEM_TASK:> Takes a flat list of atomic coordinates and converts it to a `Polymer`. <END_TASK> <USER_TASK:> Description: def flat_list_to_polymer(atom_list, atom_group_s=4): """Takes a flat list of atomic coordinates and converts it to a `Polymer`. Parameters ---------- atom_list : [Atom] Flat list of coordinates. atom_group_s : int, optional Size of atom groups. Returns ------- polymer : Polypeptide `Polymer` object containing atom coords converted `Monomers`. Raises ------ ValueError Raised if `atom_group_s` != 4 or 5 """
atom_labels = ['N', 'CA', 'C', 'O', 'CB'] atom_elements = ['N', 'C', 'C', 'O', 'C'] atoms_coords = [atom_list[x:x + atom_group_s] for x in range(0, len(atom_list), atom_group_s)] atoms = [[Atom(x[0], x[1]) for x in zip(y, atom_elements)] for y in atoms_coords] if atom_group_s == 5: monomers = [Residue(OrderedDict(zip(atom_labels, x)), 'ALA') for x in atoms] elif atom_group_s == 4: monomers = [Residue(OrderedDict(zip(atom_labels, x)), 'GLY') for x in atoms] else: raise ValueError( 'Parameter atom_group_s must be 4 or 5 so atoms can be labeled correctly.') polymer = Polypeptide(monomers=monomers) return polymer
<SYSTEM_TASK:> Returns a new `Polymer` containing only the backbone atoms. <END_TASK> <USER_TASK:> Description: 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 containing only the backbone atoms of the original Polymer. """
bb_poly = Polypeptide([x.backbone for x in self._monomers], self.id) return bb_poly
<SYSTEM_TASK:> Packs a new sequence onto the polymer using Scwrl4. <END_TASK> <USER_TASK:> Description: 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 does not match the number of monomers in the Polymer. """
# 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( len(sequence), len(polymer_bb))) scwrl_out = pack_sidechains(self.backbone.pdb, sequence) if scwrl_out is None: return else: packed_structure, scwrl_score = scwrl_out new_assembly = convert_pdb_to_ampal(packed_structure, path=False) self._monomers = new_assembly[0]._monomers[:] self.tags['scwrl_score'] = scwrl_score self.assign_force_field(global_settings['buff']['force_field']) return
<SYSTEM_TASK:> Returns the sequence of the `Polymer` as a string. <END_TASK> <USER_TASK:> Description: def sequence(self): """Returns the sequence of the `Polymer` as a string. Returns ------- sequence : str String of the `Residue` sequence of the `Polypeptide`. """
seq = [x.mol_letter for x in self._monomers] return ''.join(seq)
<SYSTEM_TASK:> Dictionary containing backbone bond lengths as lists of floats. <END_TASK> <USER_TASK:> Description: 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 Angstroms. The lists of n_ca, ca_c and c_o are of length k for a Polypeptide containing k Residues. The list of c_n bonds is of length k-1 for a Polypeptide containing k Residues (C-N formed between successive `Residue` pairs). """
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 self.get_monomers(ligands=False)], c_n=[distance(r1['C'], r2['N']) for r1, r2 in [ (self[i], self[i + 1]) for i in range(len(self) - 1)]], ) return bond_lengths
<SYSTEM_TASK:> Dictionary containing backbone bond angles as lists of floats. <END_TASK> <USER_TASK:> Description: 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 angles in degrees. The lists of n_ca_c, ca_c_o are of length k for a `Polypeptide` containing k `Residues`. The list of ca_c_n and c_n_ca are of length k-1 for a `Polypeptide` containing k `Residues` (These angles are across the peptide bond, and are therefore formed between successive `Residue` pairs). """
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)], ca_c_n=[angle_between_vectors(r1['CA'] - r1['C'], r2['N'] - r1['C']) for r1, r2 in [(self[i], self[i + 1]) for i in range(len(self) - 1)]], c_n_ca=[angle_between_vectors(r1['C'] - r2['N'], r2['CA'] - r2['N']) for r1, r2 in [(self[i], self[i + 1]) for i in range(len(self) - 1)]], ) return bond_angles
<SYSTEM_TASK:> Tags each `Residue` of the `Polypeptide` with secondary structure. <END_TASK> <USER_TASK:> Description: 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-group/isambard#external-programs For more information on DSSP see [1]. References ---------- .. [1] Kabsch W, Sander C (1983) "Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features", Biopolymers, 22, 2577-637. Parameters ---------- force : bool, optional If `True` the tag will be run even if `Residues` are already tagged. """
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=False) for monomer, dssp_ss in zip(self._monomers, dssp_ss_list): monomer.tags['secondary_structure'] = dssp_ss[1] return
<SYSTEM_TASK:> Tags `Residues` wirh relative residue solvent accessibility. <END_TASK> <USER_TASK:> Description: 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 ---------- .. [1] Hubbard,S.J. & Thornton, J.M. (1993), 'NACCESS', Computer Program, Department of Biochemistry and Molecular Biology, University College London. Parameters ---------- force : bool, optional If `True`, the ta will be run even if `Residues` are already tagged. tag_type : str, optional Specifies the name of the tag. Defaults to 'residue_solvent_accessibility'. Useful for specifying more than one tag, e.g. if the Polymer is part of an Assembly. tag_total : bool, optional If True then the total rsa of the Polymer will be tagged in the 'total accessibility' tag. include_hetatms:bool, optional If true then NACCESS will run with the -h flag and will include heteroatom solvent accessibility where it can. Helpful if your file has MSE residues that you don't convert to MET, but best check if they are there before using the flag. """
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( self.pdb, mode='rsa', path=False, include_hetatms=include_hetatms), path=False, get_total=tag_total) for monomer, naccess_rsa in zip(self._monomers, naccess_rsa_list): monomer.tags[tag_type] = naccess_rsa if tag_total: self.tags['total_polymer_accessibility'] = total return
<SYSTEM_TASK:> Tags each `Residues` Polymer with its solvent accessibility. <END_TASK> <USER_TASK:> Description: 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 protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features", Biopolymers, 22, 2577-637. Parameters ---------- force : bool, optional If `True` the tag will be run even if `Residues` are already tagged. """
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, path=False) for monomer, dssp_acc in zip(self._monomers, dssp_acc_list): monomer.tags['dssp_acc'] = dssp_acc[-1] return
<SYSTEM_TASK:> Tags each monomer with side-chain dihedral angles <END_TASK> <USER_TASK:> Description: 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. """
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_angles return
<SYSTEM_TASK:> Tags each Monomer of the Polymer with its omega, phi and psi torsion angle. <END_TASK> <USER_TASK:> Description: 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. """
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['phi'] = phi monomer.tags['psi'] = psi monomer.tags['tas'] = (omega, phi, psi) return
<SYSTEM_TASK:> Tags each `Residue` with rise_per_residue, radius_of_curvature and residues_per_turn. <END_TASK> <USER_TASK:> Description: 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 Coordinates to feed to geometry functions that depend on having a reference axis. reference_axis_name : str, optional Used to name the keys in tags at `Polypeptide` and `Residue` level. """
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) rpts = [None] * len(self) else: rprs = self.rise_per_residue() rocs = self.radii_of_curvature() rpts = residues_per_turn(self) for monomer, rpr, roc, rpt in zip(self._monomers, rprs, rocs, rpts): monomer.tags['rise_per_residue'] = rpr monomer.tags['radius_of_curvature'] = roc monomer.tags['residues_per_turn'] = rpt # Functions that require a reference_axis. if (reference_axis is not None) and (len(reference_axis) == len(self)): # Set up arguments to pass to functions. ref_axis_args = dict(p=self, reference_axis=reference_axis, tag=True, reference_axis_name=reference_axis_name) # Run the functions. polymer_to_reference_axis_distances(**ref_axis_args) crick_angles(**ref_axis_args) alpha_angles(**ref_axis_args) return
<SYSTEM_TASK:> True if all backbone bonds are within atol Angstroms of the expected distance. <END_TASK> <USER_TASK:> Description: 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. Parameters ---------- atol : float, optional Tolerance value in Angstoms for the absolute deviation away from ideal backbone bond lengths. """
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_bond_lengths['ca_c']] * len(self), atol=atol) a3 = numpy.allclose(bond_lengths['c_o'], [ideal_backbone_bond_lengths['c_o']] * len(self), atol=atol) a4 = numpy.allclose(bond_lengths['c_n'], [ideal_backbone_bond_lengths['c_n']] * (len(self) - 1), atol=atol) return all([a1, a2, a3, a4])
<SYSTEM_TASK:> True if all backbone bond angles are within atol degrees of their expected values. <END_TASK> <USER_TASK:> Description: 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, 1979. Parameters ---------- atol : float, optional Tolerance value in degrees for the absolute deviation away from ideal backbone bond angles. """
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] ideal_ca_c_o = [ideal_backbone_bond_angles[trans[i + 1]] ['ca_c_o'] for i in range(len(trans) - 1)] ideal_ca_c_o.append(ideal_backbone_bond_angles['trans']['ca_c_o']) ideal_ca_c_n = [ideal_backbone_bond_angles[x]['ca_c_n'] for x in trans[1:]] ideal_c_n_ca = [ideal_backbone_bond_angles[x]['c_n_ca'] for x in trans[1:]] a1 = numpy.allclose(bond_angles['n_ca_c'], [ideal_n_ca_c], atol=atol) a2 = numpy.allclose(bond_angles['ca_c_o'], [ideal_ca_c_o], atol=atol) a3 = numpy.allclose(bond_angles['ca_c_n'], [ideal_ca_c_n], atol=atol) a4 = numpy.allclose(bond_angles['c_n_ca'], [ideal_c_n_ca], atol=atol) return all([a1, a2, a3, a4])
<SYSTEM_TASK:> Returns a new `Residue` containing only the backbone atoms. <END_TASK> <USER_TASK:> Description: 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 contain the backbone atoms (N, CA, C, O). """
try: backbone = OrderedDict([('N', self.atoms['N']), ('CA', self.atoms['CA']), ('C', self.atoms['C']), ('O', self.atoms['O'])]) except KeyError: missing_atoms = filter(lambda x: x not in self.atoms.keys(), ('N', 'CA', 'C', 'O') ) raise KeyError('Error in residue {} {} {}, missing ({}) atoms. ' '`atoms` must be an `OrderedDict` with coordinates ' 'defined for the backbone (N, CA, C, O) atoms.' .format(self.ampal_parent.id, self.mol_code, self.id, ', '.join(missing_atoms))) bb_monomer = Residue(backbone, self.mol_code, monomer_id=self.id, insertion_code=self.insertion_code, is_hetero=self.is_hetero) return bb_monomer
<SYSTEM_TASK:> Generates a tuple that uniquely identifies a `Monomer` in an `Assembly`. <END_TASK> <USER_TASK:> Description: 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 hetero-flag is defined as in Biopython as a string that is either a single whitespace in the case of a non-hetero atom, or 'H_' plus the name of the hetero-residue (e.g. 'H_GLC' in the case of a glucose molecule), or 'W' in the case of a water molecule. For more information, see the Biopython documentation or this Biopython wiki page: http://biopython.org/wiki/The_Biopython_Structural_Bioinformatics_FAQ Returns ------- unique_id : tuple unique_id[0] is the polymer_id unique_id[1] is a triple of the hetero-flag, the monomer id (residue number) and the insertion code. """
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)
<SYSTEM_TASK:> Finds `Residues` with any atom within the cutoff distance of side-chain. <END_TASK> <USER_TASK:> Description: 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. include_neighbours : bool, optional If `false`, does not return `Residue` at i-1, i+1 positions in same chain as `Residue`. inter_chain : bool, optional If `false`, only includes nearby `Residue` in the same chain as the `Residue`. include_ligands : bool, optional If `true`, `Residue` classed as ligands but not identified as solvent will be included in the environment. include_solvent : bool, optional If `true`, Monomers classed as categorised as solvent will be included in the environment. Returns ------- sc_environment : list List of monomers within cutoff distance of side-chain. """
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( atoms=side_chain_dict, monomer_id=self.id, ampal_parent=self.ampal_parent) sc_environment = side_chain_monomer.environment( cutoff=cutoff, include_ligands=include_ligands, include_neighbours=include_neighbours, include_solvent=include_solvent, inter_chain=inter_chain) return sc_environment
<SYSTEM_TASK:> Loads settings file containing paths to dependencies and other optional configuration elements. <END_TASK> <USER_TASK:> Description: def load_global_settings(): """Loads settings file containing paths to dependencies and other optional configuration elements."""
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 settings_json.items(): if type(v) == dict: global_settings[k].update(v) else: global_settings[k] = v
<SYSTEM_TASK:> Builds a `HelixPair` using the defined attributes. <END_TASK> <USER_TASK:> Description: def build(self): """Builds a `HelixPair` using the defined attributes."""
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
<SYSTEM_TASK:> Builds a helix for a given set of parameters. <END_TASK> <USER_TASK:> Description: def make_helix(aa, axis_distance, z_shift, phi, splay, off_plane): """Builds a helix for a given set of parameters."""
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), mid) helix.rotate(phi, helix.axis.unit_tangent, helix.helix_start) return helix
<SYSTEM_TASK:> Builds a Solenoid using the defined attributes. <END_TASK> <USER_TASK:> Description: def build(self): """Builds a Solenoid using the defined attributes."""
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) * numpy.array([0, 0, 1]) dup_unit.translate(z) dup_unit.rotate(rot_ang * i, [0, 0, 1]) self.extend(dup_unit) self.relabel_all() return
<SYSTEM_TASK:> Generates a helical `Polynucleotide` that is built along an axis. <END_TASK> <USER_TASK:> Description: 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 acid. helix_type: str The type of nucleic acid helix to generate. phos_3_prime: bool If false the 5' and the 3' phosphor will be omitted. """
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
<SYSTEM_TASK:> Moves the `Polynucleotide` to lie on the `start` and `end` vector. <END_TASK> <USER_TASK:> Description: 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 of the helix primitive. Raises ------ ValueError Raised if `start` and `end` are very close together. """
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 numpy.isclose(angle, 0.0): self.rotate(angle=angle, axis=axis, point=point, radians=False) self.translate(vector=translation) return
<SYSTEM_TASK:> Attempts to fit a heptad repeat to a set of Crick angles. <END_TASK> <USER_TASK:> Description: 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. """
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(crangles) // 7 ideal_crang_list = ideal_crangs * (full_hept + 2) # This is dirty, too long but trimmed with zip fitting = [] for i in range(7): ang_pairs = zip(crangles, ideal_crang_list[i:]) ang_diffs = [abs(y - x) for x, y in ang_pairs] fitting.append((i, numpy.mean(ang_diffs), numpy.std(ang_diffs))) return sorted(fitting, key=lambda x: x[1])
<SYSTEM_TASK:> Extracts the tagged coiled-coil parameters for each layer. <END_TASK> <USER_TASK:> Description: def gather_layer_info(self): """Extracts the tagged coiled-coil parameters for each layer."""
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) layer_ca = [x[i].tags['crick_angle_ref_axis'] for x in self.cc] self.ca_layers.append(layer_ca) return
<SYSTEM_TASK:> Takes a group of equal length lists and averages them across each index. <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Returns the calculated register of the coiled coil and the fit quality. <END_TASK> <USER_TASK:> Description: def heptad_register(self): """Returns the calculated register of the coiled coil and the fit quality."""
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:]
<SYSTEM_TASK:> Generates a report on the coiled coil parameters. <END_TASK> <USER_TASK:> Description: 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. """
# 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'.format(*fit)) # Find coiled coil parameters lines.append('Coiled Coil Parameters\n----------------------') layer_info = (self.radii_layers, self.alpha_layers, self.ca_layers) r_layer_aves, a_layer_aves, c_layer_aves = [self.calc_average_parameters(x) for x in layer_info] start_line = ['Res#'.rjust(5), 'Radius'.rjust(9), 'Alpha'.rjust(9), 'CrAngle'.rjust(9)] lines.append(''.join(start_line)) for i in range(len(r_layer_aves[0])): residue = '{:>5}'.format(i+1) average_r = '{:+3.3f}'.format(r_layer_aves[0][i]).rjust(9) average_a = '{:+3.3f}'.format(a_layer_aves[0][i]).rjust(9) average_c = '{:+3.3f}'.format(c_layer_aves[0][i]).rjust(9) line = [residue, average_r, average_a, average_c] lines.append(''.join(line)) # Average for assembly lines.append('-'*32) residue = ' Ave' average_r = '{:+3.3f}'.format(r_layer_aves[1]).rjust(9) average_a = '{:+3.3f}'.format(a_layer_aves[1]).rjust(9) average_c = '{:+3.3f}'.format(c_layer_aves[1]).rjust(9) line = [residue, average_r, average_a, average_c] lines.append(''.join(line)) # Std dev residue = 'Std D' std_d_r = '{:+3.3f}'.format(numpy.std(r_layer_aves[0])).rjust(9) std_d_a = '{:+3.3f}'.format(numpy.std(a_layer_aves[0][:-1])).rjust(9) std_d_c = '{:+3.3f}'.format(numpy.std(c_layer_aves[0][:-1])).rjust(9) line = [residue, std_d_r, std_d_a, std_d_c] lines.append(''.join(line)) return '\n'.join(lines)
<SYSTEM_TASK:> Creates optimizer with default build and BUFF interaction eval. <END_TASK> <USER_TASK:> Description: 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 : [str] A list of sequences, one for each polymer. parameters : [base_ev_opt.Parameter] A list of `Parameter` objects in the same order as the function signature expects. """
instance = cls(specification, sequences, parameters, build_fn=default_build, eval_fn=buff_interaction_eval, **kwargs) return instance
<SYSTEM_TASK:> Creates optimizer with default build and RMSD eval. <END_TASK> <USER_TASK:> Description: 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 : ampal.assembly.specification Any assembly level specification. sequences : [str] A list of sequences, one for each polymer. parameters : [base_ev_opt.Parameter] A list of `Parameter` objects in the same order as the function signature expects. reference_ampal : ampal.Assembly The target structure of the optimisation. """
eval_fn = make_rmsd_eval(reference_ampal) instance = cls(specification, sequences, parameters, build_fn=default_build, eval_fn=eval_fn, mp_disabled=True, **kwargs) return instance
<SYSTEM_TASK:> Converts a deap individual into a full list of parameters. <END_TASK> <USER_TASK:> Description: 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 converts them into the values used to actually build the model Returns ------- fullpars: list Full parameter list for model building. """
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(fullpars)): if fullpars[j] == self.variable_parameters[k]: fullpars[j] = scaled_ind[k] return fullpars
<SYSTEM_TASK:> Runs the optimizer. <END_TASK> <USER_TASK:> Description: 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 'mp_disabled' keyword is passed to the optimizer, this will be ignored and one core will be used. plot: bool, optional If true, matplotlib will be used to plot information about the minimisation. log: bool, optional If true, a log file describing the optimisation will be created. By default it will be written to the current directory and named according to the time the minimisation finished. This can be manually specified by passing the 'output_path' and 'run_id' keyword arguments. log_path : str Path to write output file. run_id : str An identifier used as the name of your log file. store_params: bool, optional If true, the parameters for each model created during the optimisation will be stored. This can be used to create funnel data later on. """
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.stats.register("std", numpy.std) self.stats.register("min", numpy.min) self.stats.register("max", numpy.max) self.logbook = tools.Logbook() self.logbook.header = ["gen", "evals"] + self.stats.fields start_time = datetime.datetime.now() self._initialize_pop(pop_size) for g in range(generations): self._update_pop(pop_size) self.halloffame.update(self.population) self.logbook.record(gen=g, evals=self._evals, **self.stats.compile(self.population)) print(self.logbook.stream) end_time = datetime.datetime.now() time_taken = end_time - start_time print("Evaluated {} models in total in {}".format( self._model_count, time_taken)) print("Best fitness is {0}".format(self.halloffame[0].fitness)) print("Best parameters are {0}".format(self.parse_individual( self.halloffame[0]))) for i, entry in enumerate(self.halloffame[0]): if entry > 0.95: print( "Warning! Parameter {0} is at or near maximum allowed " "value\n".format(i + 1)) elif entry < -0.95: print( "Warning! Parameter {0} is at or near minimum allowed " "value\n".format(i + 1)) if log: self.log_results(output_path=output_path, run_id=run_id) if plot: print('----Minimisation plot:') plt.figure(figsize=(5, 5)) plt.plot(range(len(self.logbook.select('min'))), self.logbook.select('min')) plt.xlabel('Iteration', fontsize=20) plt.ylabel('Score', fontsize=20) return