text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 :... |
self._generate_initial_model()
self._mmc_loop(rounds, temp=temp)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 : flo... |
# 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 = r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 alg... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 usin... |
# 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, count... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 co... |
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 = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 val... |
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 a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pdbe_status_code(code):
"""Check if a PDB code has structure files on the PDBE site. Parameters code : str PDB code to check for on PDBE. Returns ------- sta... |
url = 'http://www.ebi.ac.uk/pdbe/entry-files/download/{0}_1.mmol'.format(code)
r = requests.head(url=url)
return r.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 no... |
# 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_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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_di... |
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) f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. A... |
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(ds... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 fr... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 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(co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def categories(self):
"""Returns the categories of `Ligands` in `LigandGroup`.""" |
category_dict = {}
for ligand in self:
if ligand.category in category_dict:
category_dict[ligand.category].append(ligand)
else:
category_dict[ligand.category] = [ligand]
return category_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ami... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 Sequ... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 o... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 """ |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 aci... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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`... |
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:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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` obj... |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 R... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 resi... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 fina... |
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 = [... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 -... |
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_poin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ------- r... |
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.coordina... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 `Poly... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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(n... |
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]) / wind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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 (c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ... |
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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 `As... |
if isinstance(assembly, Assembly):
self._molecules.extend(assembly)
else:
raise TypeError(
'Only Assembly objects may be merged with an Assembly.')
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 `tru... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 inclu... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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, optio... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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, opt... |
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(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
counter = start
for atom in self.get_atoms(ligands=True):
atom.id = counter
counter += 1
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ... |
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(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. Seq... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ob... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 Recommendati... |
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_lin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. Parameter... |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ... |
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 ma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 cal... |
for polymer in self._molecules:
if polymer.molecule_type == 'protein':
polymer.tag_secondary_structure(force=force)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 s... |
for polymer in self._molecules:
polymer.tag_dssp_solvent_accessibility(force=force)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
for polymer in self._molecules:
if polymer.molecule_type == 'protein':
polymer.tag_torsion_angles(force=force)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. ... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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)... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 conseq... |
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:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 referen... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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)
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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] Fla... |
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 at... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. Sequen... |
bb_poly = Polypeptide([x.backbone for x in self._monomers], self.id)
return bb_poly |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 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(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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`, ... |
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_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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`,... |
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)],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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.... |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 solven... |
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(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ... |
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=Fals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 ... |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 `T... |
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'] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 an... |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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_le... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 angle... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 at... |
try:
backbone = OrderedDict([('N', self.atoms['N']),
('CA', self.atoms['CA']),
('C', self.atoms['C']),
('O', self.atoms['O'])])
except KeyError:
missing_atoms = filter(lam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 wi... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
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=s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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.ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. P... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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) ... |
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.isc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 t... |
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(crangl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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] L... |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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... |
# 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))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buff_interaction_eval(cls, specification, sequences, parameters, **kwargs):
"""Creates optimizer with default build and BUFF interaction eval. Notes ----- An... |
instance = cls(specification,
sequences,
parameters,
build_fn=default_build,
eval_fn=buff_interaction_eval,
**kwargs)
return instance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 keywo... |
eval_fn = make_rmsd_eval(reference_ampal)
instance = cls(specification,
sequences,
parameters,
build_fn=default_build,
eval_fn=eval_fn,
mp_disabled=True,
**kwargs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 De... |
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)):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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. Paramet... |
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.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_parameters(self):
"""Converts a list of Parameters into DEAP format.""" |
self.value_means = []
self.value_ranges = []
self.arrangement = []
self.variable_parameters = []
current_var = 0
for parameter in self.parameters:
if parameter.type == ParameterType.DYNAMIC:
self.value_means.append(parameter.value[0])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign_fitnesses(self, targets):
"""Assigns fitnesses to parameters. Notes ----- Uses `self.eval_fn` to evaluate each member of target. Parameters --------- ... |
self._evals = len(targets)
px_parameters = zip([self.specification] * len(targets),
[self.sequences] * len(targets),
[self.parse_individual(x) for x in targets])
if (self._cores == 1) or (self.mp_disabled):
models = map(self.bu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dynamic(cls, label, val_mean, val_range):
"""Creates a static parameter. Parameters label : str A human-readable label for the parameter. val_mean : float Th... |
return cls(label, ParameterType.DYNAMIC, (val_mean, val_range)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.