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 run_scwrl(pdb, sequence, path=True):
"""Runs SCWRL on input PDB strong or path to PDB and a sequence string. Parameters pdb : str PDB string or a path to a PDB file. sequence : str Amino acid sequence for SCWRL to pack in single-letter code. path : bool, optional True if pdb is a path. Returns ------- scwrl_std_out : str Std out from SCWRL. scwrl_pdb : str String of packed SCWRL PDB. Raises ------ IOError Raised if SCWRL failed to run. """
|
if path:
with open(pdb, 'r') as inf:
pdb = inf.read()
pdb = pdb.encode()
sequence = sequence.encode()
try:
with tempfile.NamedTemporaryFile(delete=False) as scwrl_tmp,\
tempfile.NamedTemporaryFile(delete=False) as scwrl_seq,\
tempfile.NamedTemporaryFile(delete=False) as scwrl_out:
scwrl_tmp.write(pdb)
scwrl_tmp.seek(0) # Resets the buffer back to the first line
scwrl_seq.write(sequence)
scwrl_seq.seek(0)
if not global_settings['scwrl']['rigid_rotamer_model']:
scwrl_std_out = subprocess.check_output(
[global_settings['scwrl']['path'],
'-i', scwrl_tmp.name,
'-o', scwrl_out.name,
'-s', scwrl_seq.name])
else:
scwrl_std_out = subprocess.check_output(
[global_settings['scwrl']['path'],
'-v', # Rigid rotamer model
'-i', scwrl_tmp.name,
'-o', scwrl_out.name,
'-s', scwrl_seq.name])
scwrl_out.seek(0)
scwrl_pdb = scwrl_out.read()
finally:
os.remove(scwrl_tmp.name)
os.remove(scwrl_out.name)
os.remove(scwrl_seq.name)
if not scwrl_pdb:
raise IOError('SCWRL failed to run. SCWRL:\n{}'.format(scwrl_std_out))
return scwrl_std_out.decode(), scwrl_pdb.decode()
|
<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_scwrl_out(scwrl_std_out, scwrl_pdb):
"""Parses SCWRL output and returns PDB and SCWRL score. Parameters scwrl_std_out : str Std out from SCWRL. scwrl_pdb : str String of packed SCWRL PDB. Returns ------- fixed_scwrl_str : str String of packed SCWRL PDB, with correct PDB format. score : float SCWRL Score """
|
score = re.findall(
r'Total minimal energy of the graph = ([-0-9.]+)', scwrl_std_out)[0]
# Add temperature factors to SCWRL out
split_scwrl = scwrl_pdb.splitlines()
fixed_scwrl = []
for line in split_scwrl:
if len(line) < 80:
line += ' ' * (80 - len(line))
if re.search(r'H?E?T?ATO?M\s+\d+.+', line):
front = line[:61]
temp_factor = ' 0.00'
back = line[66:]
fixed_scwrl.append(''.join([front, temp_factor, back]))
else:
fixed_scwrl.append(line)
fixed_scwrl_str = '\n'.join(fixed_scwrl) + '\n'
return fixed_scwrl_str, float(score)
|
<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_sidechains(pdb, sequence, path=False):
"""Packs sidechains onto a given PDB file or string. Parameters pdb : str PDB string or a path to a PDB file. sequence : str Amino acid sequence for SCWRL to pack in single-letter code. path : bool, optional True if pdb is a path. Returns ------- scwrl_pdb : str String of packed SCWRL PDB. scwrl_score : float Scwrl packing score. """
|
scwrl_std_out, scwrl_pdb = run_scwrl(pdb, sequence, path=path)
return parse_scwrl_out(scwrl_std_out, scwrl_pdb)
|
<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_pdb_file(self):
"""Runs the PDB parser."""
|
self.pdb_parse_tree = {'info': {},
'data': {
self.state: {}}
}
try:
for line in self.pdb_lines:
self.current_line = line
record_name = line[:6].strip()
if record_name in self.proc_functions:
self.proc_functions[record_name]()
else:
if record_name not in self.pdb_parse_tree['info']:
self.pdb_parse_tree['info'][record_name] = []
self.pdb_parse_tree['info'][record_name].append(line)
except EOFError:
# Raised by END record
pass
if self.new_labels:
ampal_data_session.commit()
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 proc_atom(self):
"""Processes an "ATOM" or "HETATM" record."""
|
atom_data = self.proc_line_coordinate(self.current_line)
(at_type, at_ser, at_name, alt_loc, res_name, chain_id, res_seq,
i_code, x, y, z, occupancy, temp_factor, element, charge) = atom_data
# currently active state
a_state = self.pdb_parse_tree['data'][self.state]
res_id = (res_seq, i_code)
if chain_id not in a_state:
a_state[chain_id] = (set(), OrderedDict())
if res_id not in a_state[chain_id][1]:
a_state[chain_id][1][res_id] = (set(), OrderedDict())
if at_type == 'ATOM':
if res_name in standard_amino_acids.values():
poly = 'P'
else:
poly = 'N'
else:
poly = 'H'
a_state[chain_id][0].add((chain_id, at_type, poly))
a_state[chain_id][1][res_id][0].add(
(at_type, res_seq, res_name, i_code))
if at_ser not in a_state[chain_id][1][res_id][1]:
a_state[chain_id][1][res_id][1][at_ser] = [atom_data]
else:
a_state[chain_id][1][res_id][1][at_ser].append(atom_data)
return
|
<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_ampal(self):
"""Generates an AMPAL object from the parse tree. Notes ----- Will create an `Assembly` if there is a single state in the parese tree or an `AmpalContainer` if there is more than one. """
|
data = self.pdb_parse_tree['data']
if len(data) > 1:
ac = AmpalContainer(id=self.id)
for state, chains in sorted(data.items()):
if chains:
ac.append(self.proc_state(chains, self.id +
'_state_{}'.format(state + 1)))
return ac
elif len(data) == 1:
return self.proc_state(data[0], self.id)
else:
raise ValueError('Empty parse tree, check input PDB 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 proc_state(self, state_data, state_id):
"""Processes a state into an `Assembly`. Parameters state_data : dict Contains information about the state, including all the per line structural data. state_id : str ID given to `Assembly` that represents the state. """
|
assembly = Assembly(assembly_id=state_id)
for k, chain in sorted(state_data.items()):
assembly._molecules.append(self.proc_chain(chain, assembly))
return 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 proc_chain(self, chain_info, parent):
"""Converts a chain into a `Polymer` type object. Parameters chain_info : (set, OrderedDict) Contains a set of chain labels and atom records. parent : ampal.Assembly `Assembly` used to assign `ampal_parent` on created `Polymer`. Raises ------ ValueError Raised if multiple or unknown atom types found within the same chain. AttributeError Raised if unknown `Monomer` type encountered. """
|
hetatom_filters = {
'nc_aas': self.check_for_non_canonical
}
polymer = False
chain_labels, chain_data = chain_info
chain_label = list(chain_labels)[0]
monomer_types = {x[2] for x in chain_labels if x[2]}
if ('P' in monomer_types) and ('N' in monomer_types):
raise ValueError(
'Malformed PDB, multiple "ATOM" types in a single chain.')
# Changes Polymer type based on chain composition
if 'P' in monomer_types:
polymer_class = Polypeptide
polymer = True
elif 'N' in monomer_types:
polymer_class = Polynucleotide
polymer = True
elif 'H' in monomer_types:
polymer_class = LigandGroup
else:
raise AttributeError('Malformed parse tree, check inout PDB.')
chain = polymer_class(polymer_id=chain_label[0], ampal_parent=parent)
# Changes where the ligands should go based on the chain composition
if polymer:
chain.ligands = LigandGroup(
polymer_id=chain_label[0], ampal_parent=parent)
ligands = chain.ligands
else:
ligands = chain
for residue in chain_data.values():
res_info = list(residue[0])[0]
if res_info[0] == 'ATOM':
chain._monomers.append(self.proc_monomer(residue, chain))
elif res_info[0] == 'HETATM':
mon_cls = None
on_chain = False
for filt_func in hetatom_filters.values():
filt_res = filt_func(residue)
if filt_res:
mon_cls, on_chain = filt_res
break
mon_cls = Ligand
if on_chain:
chain._monomers.append(self.proc_monomer(
residue, chain, mon_cls=mon_cls))
else:
ligands._monomers.append(self.proc_monomer(
residue, chain, mon_cls=mon_cls))
else:
raise ValueError('Malformed PDB, unknown record type for data')
return chain
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proc_monomer(self, monomer_info, parent, mon_cls=False):
"""Processes a records into a `Monomer`. Parameters monomer_info : (set, OrderedDict) Labels and data for a monomer. parent : ampal.Polymer `Polymer` used to assign `ampal_parent` on created `Monomer`. mon_cls : `Monomer class or subclass`, optional A `Monomer` class can be defined explicitly. """
|
monomer_labels, monomer_data = monomer_info
if len(monomer_labels) > 1:
raise ValueError(
'Malformed PDB, single monomer id with '
'multiple labels. {}'.format(monomer_labels))
else:
monomer_label = list(monomer_labels)[0]
if mon_cls:
monomer_class = mon_cls
het = True
elif monomer_label[0] == 'ATOM':
if monomer_label[2] in standard_amino_acids.values():
monomer_class = Residue
else:
monomer_class = Nucleotide
het = False
else:
raise ValueError('Unknown Monomer type.')
monomer = monomer_class(
atoms=None, mol_code=monomer_label[2], monomer_id=monomer_label[1],
insertion_code=monomer_label[3], is_hetero=het, ampal_parent=parent
)
monomer.states = self.gen_states(monomer_data.values(), monomer)
monomer._active_state = sorted(monomer.states.keys())[0]
return monomer
|
<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_antisense_sequence(sequence):
"""Creates the antisense sequence of a DNA strand."""
|
dna_antisense = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C'
}
antisense = [dna_antisense[x] for x in sequence[::-1]]
return ''.join(antisense)
|
<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_sequence(cls, sequence, phos_3_prime=False):
"""Creates a DNA duplex from a nucleotide sequence. Parameters sequence: str Nucleotide sequence. phos_3_prime: bool, optional If false the 5' and the 3' phosphor will be omitted. """
|
strand1 = NucleicAcidStrand(sequence, phos_3_prime=phos_3_prime)
duplex = cls(strand1)
return duplex
|
<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, phos_3_prime=False):
"""Creates a DNA duplex from a start and end point. Parameters start: [float, float, float] Start of the build axis. end: [float, float, float] End of build axis. sequence: str Nucleotide sequence. phos_3_prime: bool, optional If false the 5' and the 3' phosphor will be omitted."""
|
strand1 = NucleicAcidStrand.from_start_and_end(
start, end, sequence, phos_3_prime=phos_3_prime)
duplex = cls(strand1)
return duplex
|
<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_complementary_strand(strand1):
"""Takes a SingleStrandHelix and creates the antisense strand."""
|
rise_adjust = (
strand1.rise_per_nucleotide * strand1.axis.unit_tangent) * 2
strand2 = NucleicAcidStrand.from_start_and_end(
strand1.helix_end - rise_adjust, strand1.helix_start - rise_adjust,
generate_antisense_sequence(strand1.base_sequence),
phos_3_prime=strand1.phos_3_prime)
ad_ang = dihedral(strand1[0]["C1'"]._vector, strand1.axis.start,
strand2.axis.start + rise_adjust,
strand2[-1]["C1'"]._vector)
strand2.rotate(
225.0 + ad_ang, strand2.axis.unit_tangent,
point=strand2.helix_start) # 225 is the base adjust
return strand2
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_accessibility(in_rsa, path=True):
"""Parses rsa file for the total surface accessibility data. Parameters in_rsa : str Path to naccess rsa file. path : bool Indicates if in_rsa is a path or a string. Returns ------- dssp_residues : 5-tuple(float) Total accessibility values for: [0] all atoms [1] all side-chain atoms [2] all main-chain atoms [3] all non-polar atoms [4] all polar atoms """
|
if path:
with open(in_rsa, 'r') as inf:
rsa = inf.read()
else:
rsa = in_rsa[:]
all_atoms, side_chains, main_chain, non_polar, polar = [
float(x) for x in rsa.splitlines()[-1].split()[1:]]
return all_atoms, side_chains, main_chain, non_polar, polar
|
<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_aa_code(aa_letter):
""" Get three-letter aa code if possible. If not, return None. If three-letter code is None, will have to find this later from the filesystem. Parameters aa_letter : str One-letter amino acid code. Returns ------- aa_code : str, or None Three-letter aa code. """
|
aa_code = None
if aa_letter != 'X':
for key, val in standard_amino_acids.items():
if key == aa_letter:
aa_code = val
return aa_code
|
<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_aa_letter(aa_code):
""" Get one-letter version of aa_code if possible. If not, return 'X'. Parameters aa_code : str Three-letter amino acid code. Returns ------- aa_letter : str One-letter aa code. Default value is 'X'. """
|
aa_letter = 'X'
for key, val in standard_amino_acids.items():
if val == aa_code:
aa_letter = key
return aa_letter
|
<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_aa_info(code):
"""Get dictionary of information relating to a new amino acid code not currently in the database. Notes ----- Use this function to get a dictionary that is then to be sent to the function add_amino_acid_to_json(). use to fill in rows of amino_acid table for new amino acid code. Parameters code : str Three-letter amino acid code. Raises ------ IOError If unable to locate the page associated with the amino acid name on the PDBE site. Returns ------- aa_dict : dict Keys are AminoAcidDB field names. Values are the str values for the new amino acid, scraped from the PDBE if possible. None if not found. """
|
letter = 'X'
# Try to get content from PDBE.
url_string = 'http://www.ebi.ac.uk/pdbe-srv/pdbechem/chemicalCompound/show/{0}'.format(code)
r = requests.get(url_string)
# Raise error if content not obtained.
if not r.ok:
raise IOError("Could not get to url {0}".format(url_string))
# Parse r.text in an ugly way to get the required information.
description = r.text.split('<h3>Molecule name')[1].split('</tr>')[0]
description = description.strip().split('\n')[3].strip()[:255]
modified = r.text.split("<h3>Standard parent ")[1].split('</tr>')[0]
modified = modified.replace(" ", "").replace('\n', '').split('<')[-3].split('>')[-1]
if modified == "NotAssigned":
modified = None
# Add the required information to a dictionary which can then be passed to add_amino_acid_to_json.
aa_dict = {'code': code, 'description': description, 'modified': modified, 'letter': letter}
return aa_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 add_amino_acid_to_json(code, description, letter='X', modified=None, force_add=False):
""" Add an amino acid to the amino_acids.json file used to populate the amino_acid table. Parameters code : str New code to be added to amino acid table. description : str Description of the amino acid, e.g. 'amidated terminal carboxy group'. letter : str, optional One letter code for the amino acid. Defaults to 'X' modified : str or None, optional Code of modified amino acid, e.g. 'ALA', or None. Defaults to None force_add : bool, optional If True, will over-write existing dictionary value for code if already in amino_acids.json. If False, then an IOError is raised if code is already in amino_acids.json. Raises ------ IOError If code is already in amino_acids.json and force_add is False. Returns ------- None """
|
# If code is already in the dictionary, raise an error
if (not force_add) and code in amino_acids_dict.keys():
raise IOError("{0} is already in the amino_acids dictionary, with values: {1}".format(
code, amino_acids_dict[code]))
# Prepare data to be added.
add_code = code
add_code_dict = {'description': description, 'letter': letter, 'modified': modified}
# Check that data does not already exist, and if not, add it to the dictionary.
amino_acids_dict[add_code] = add_code_dict
# Write over json file with updated dictionary.
with open(_amino_acids_json_path, 'w') as foo:
foo.write(json.dumps(amino_acids_dict))
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 from_polymers(cls, polymers):
"""Creates a `CoiledCoil` from a list of `HelicalHelices`. Parameters polymers : [HelicalHelix] List of `HelicalHelices`. """
|
n = len(polymers)
instance = cls(n=n, auto_build=False)
instance.major_radii = [x.major_radius for x in polymers]
instance.major_pitches = [x.major_pitch for x in polymers]
instance.major_handedness = [x.major_handedness for x in polymers]
instance.aas = [x.num_monomers for x in polymers]
instance.minor_helix_types = [x.minor_helix_type for x in polymers]
instance.orientations = [x.orientation for x in polymers]
instance.phi_c_alphas = [x.phi_c_alpha for x in polymers]
instance.minor_repeats = [x.minor_repeat for x in polymers]
instance.build()
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 from_parameters(cls, n, aa=28, major_radius=None, major_pitch=None, phi_c_alpha=26.42, minor_helix_type='alpha', auto_build=True):
"""Creates a `CoiledCoil` from defined super-helical parameters. Parameters n : int Oligomeric state aa : int, optional Number of amino acids per minor helix. major_radius : float, optional Radius of super helix. major_pitch : float, optional Pitch of super helix. phi_c_alpha : float, optional Rotation of minor helices relative to the super-helical axis. minor_helix_type : float, optional Helix type of minor helices. Can be: 'alpha', 'pi', '3-10', 'PPI', 'PP2', 'collagen'. auto_build : bool, optional If `True`, the model will be built as part of instantiation. """
|
instance = cls(n=n, auto_build=False)
instance.aas = [aa] * n
instance.phi_c_alphas = [phi_c_alpha] * n
instance.minor_helix_types = [minor_helix_type] * n
if major_pitch is not None:
instance.major_pitches = [major_pitch] * n
if major_radius is not None:
instance.major_radii = [major_radius] * n
if auto_build:
instance.build()
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 tropocollagen( cls, aa=28, major_radius=5.0, major_pitch=85.0, auto_build=True):
"""Creates a model of a collagen triple helix. Parameters aa : int, optional Number of amino acids per minor helix. major_radius : float, optional Radius of super helix. major_pitch : float, optional Pitch of super helix. auto_build : bool, optional If `True`, the model will be built as part of instantiation. """
|
instance = cls.from_parameters(
n=3, aa=aa, major_radius=major_radius, major_pitch=major_pitch,
phi_c_alpha=0.0, minor_helix_type='collagen', auto_build=False)
instance.major_handedness = ['r'] * 3
# default z-shifts taken from rise_per_residue of collagen helix
rpr_collagen = _helix_parameters['collagen'][1]
instance.z_shifts = [-rpr_collagen * 2, -rpr_collagen, 0.0]
instance.minor_repeats = [None] * 3
if auto_build:
instance.build()
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 build(self):
"""Builds a model of a coiled coil protein using input parameters."""
|
monomers = [HelicalHelix(major_pitch=self.major_pitches[i],
major_radius=self.major_radii[i],
major_handedness=self.major_handedness[i],
aa=self.aas[i],
minor_helix_type=self.minor_helix_types[i],
orientation=self.orientations[i],
phi_c_alpha=self.phi_c_alphas[i],
minor_repeat=self.minor_repeats[i],
)
for i in range(self.oligomeric_state)]
axis_unit_vector = numpy.array([0, 0, 1])
for i, m in enumerate(monomers):
m.rotate(angle=self.rotational_offsets[i], axis=axis_unit_vector)
m.translate(axis_unit_vector * self.z_shifts[i])
self._molecules = monomers[:]
self.relabel_all()
for m in self._molecules:
m.ampal_parent = self
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_max_rad_npnp(self):
"""Finds the maximum radius and npnp in the force field. Returns ------- (max_rad, max_npnp):
(float, float) Maximum radius and npnp distance in the loaded force field. """
|
max_rad = 0
max_npnp = 0
for res, atoms in self.items():
if res != 'KEY':
for atom, ff_params in self[res].items():
if max_rad < ff_params[1]:
max_rad = ff_params[1]
if max_npnp < ff_params[4]:
max_npnp = ff_params[4]
return max_rad, max_npnp
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameter_struct_dict(self):
"""Dictionary containing PyAtomData structs for the force field."""
|
if self._parameter_struct_dict is None:
self._parameter_struct_dict = self._make_ff_params_dict()
elif self.auto_update_f_params:
new_hash = hash(
tuple([tuple(item)
for sublist in self.values()
for item in sublist.values()]))
if self._old_hash != new_hash:
self._parameter_struct_dict = self._make_ff_params_dict()
self._old_hash = new_hash
return self._parameter_struct_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 run_reduce(input_file, path=True):
""" Runs reduce on a pdb or mmol file at the specified path. Notes ----- Runs Reduce programme to add missing protons to a PDB file. Parameters input_file : str Path to file to add protons to or structure in mmol/pdb format. path : bool, optional True if input_file is a path. Returns ------- reduce_mmol : str Structure file with protons added. reduce_message : str Messages generated while running Reduce. Raises ------ FileNotFoundError Raised if the executable cannot be found. """
|
if path:
input_path = Path(input_file)
if not input_path.exists():
print('No file found at', path)
return None, None
else:
pathf = tempfile.NamedTemporaryFile()
encoded_input = input_file.encode()
pathf.write(encoded_input)
pathf.seek(0)
file_path = pathf.name
input_path = Path(file_path)
reduce_folder = Path(global_settings['reduce']['folder'])
reduce_exe = reduce_folder / global_settings['reduce']['path']
reduce_dict = reduce_folder / 'reduce_wwPDB_het_dict.txt'
try:
reduce_output = subprocess.run(
[str(reduce_exe), '-build', '-DB',
str(reduce_dict), str(input_path)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except FileNotFoundError as e:
raise FileNotFoundError(
'The Reduce executable cannot be found. Ensure the '
'location and filename are specified in settings.')
try:
reduced_mmol = reduce_output.stdout.decode()
except UnicodeDecodeError:
print("Reduce could not detect any missing protons in the protein. "
"Using the original structure.")
if path:
reduced_mmol = input_path.read_text()
else:
reduced_mmol = input_file
reduce_message = reduce_output.stderr.decode()
if 'could not open' in reduce_message:
print('Caution: the Reduce connectivity dictionary could not be '
'found. Some protons may be missing. See notes.')
return reduced_mmol, reduce_message
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce_output_path(path=None, pdb_name=None):
"""Defines location of Reduce output files relative to input files."""
|
if not path:
if not pdb_name:
raise NameError(
"Cannot save an output for a temporary file without a PDB"
"code specified")
pdb_name = pdb_name.lower()
output_path = Path(global_settings['structural_database']['path'],
pdb_name[1:3].lower(), pdb_name[:4].lower(),
'reduce', pdb_name + '_reduced.mmol')
else:
input_path = Path(path)
if len(input_path.parents) > 1:
output_path = input_path.parents[1] / 'reduce' / \
(input_path.stem + '_reduced' + input_path.suffix)
else:
output_path = input_path.parent / \
(input_path.stem + '_reduced' + input_path.suffix)
return output_path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output_reduce(input_file, path=True, pdb_name=None, force=False):
"""Runs Reduce on a pdb or mmol file and creates a new file with the output. Parameters input_file : str or pathlib.Path Path to file to run Reduce on. path : bool True if input_file is a path. pdb_name : str PDB ID of protein. Required if providing string not path. force : bool True if existing reduce outputs should be overwritten. Returns ------- output_path : pathlib.Path Location of output file. """
|
if path:
output_path = reduce_output_path(path=input_file)
else:
output_path = reduce_output_path(pdb_name=pdb_name)
if output_path.exists() and not force:
return output_path
reduce_mmol, reduce_message = run_reduce(input_file, path=path)
if not reduce_mmol:
return None
output_path.parent.mkdir(exist_ok=True)
output_path.write_text(reduce_mmol)
return output_path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output_reduce_list(path_list, force=False):
"""Generates structure file with protons from a list of structure files."""
|
output_paths = []
for path in path_list:
output_path = output_reduce(path, force=force)
if output_path:
output_paths.append(output_path)
return output_paths
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assembly_plus_protons(input_file, path=True, pdb_name=None, save_output=False, force_save=False):
"""Returns an Assembly with protons added by Reduce. Notes ----- Looks for a pre-existing Reduce output in the standard location before running Reduce. If the protein contains oligosaccharides or glycans, use reduce_correct_carbohydrates. Parameters input_file : str or pathlib.Path Location of file to be converted to Assembly or PDB file as string. path : bool Whether we are looking at a file or a pdb string. Defaults to file. pdb_name : str PDB ID of protein. Required if providing string not path. save_output : bool If True will save the generated assembly. force_save : bool If True will overwrite existing reduced assembly. Returns ------- reduced_assembly : AMPAL Assembly Assembly of protein with protons added by Reduce. """
|
from ampal.pdb_parser import convert_pdb_to_ampal
if path:
input_path = Path(input_file)
if not pdb_name:
pdb_name = input_path.stem[:4]
reduced_path = reduce_output_path(path=input_path)
if reduced_path.exists() and not save_output and not force_save:
reduced_assembly = convert_pdb_to_ampal(
str(reduced_path), pdb_id=pdb_name)
return reduced_assembly
if save_output:
reduced_path = output_reduce(
input_file, path=path, pdb_name=pdb_name, force=force_save)
reduced_assembly = convert_pdb_to_ampal(str(reduced_path), path=True)
else:
reduce_mmol, reduce_message = run_reduce(input_file, path=path)
if not reduce_mmol:
return None
reduced_assembly = convert_pdb_to_ampal(
reduce_mmol, path=False, pdb_id=pdb_name)
return reduced_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 from_start_and_end(cls, start, end, aa=None, helix_type='alpha'):
"""Creates a `Helix` between `start` and `end`. Parameters start : 3D Vector (tuple or list or numpy.array) The coordinate of the start of the helix primitive. end : 3D Vector (tuple or list or numpy.array) The coordinate of the end of the helix primitive. aa : int, optional Number of amino acids in the `Helix`. If `None, an appropriate number of residues are added. helix_type : str, optional Type of helix, can be: 'alpha', 'pi', '3-10', 'PPI', 'PPII', 'collagen'. """
|
start = numpy.array(start)
end = numpy.array(end)
if aa is None:
rise_per_residue = _helix_parameters[helix_type][1]
aa = int((numpy.linalg.norm(end - start) / rise_per_residue) + 1)
instance = cls(aa=aa, helix_type=helix_type)
instance.move_to(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 build(self):
"""Build straight helix along z-axis, starting with CA1 on x-axis"""
|
ang_per_res = (2 * numpy.pi) / self.residues_per_turn
atom_offsets = _atom_offsets[self.helix_type]
if self.handedness == 'l':
handedness = -1
else:
handedness = 1
atom_labels = ['N', 'CA', 'C', 'O']
if all([x in atom_offsets.keys() for x in atom_labels]):
res_label = 'GLY'
else:
res_label = 'UNK'
monomers = []
for i in range(self.num_monomers):
residue = Residue(mol_code=res_label, ampal_parent=self)
atoms_dict = OrderedDict()
for atom_label in atom_labels:
r, zeta, z_shift = atom_offsets[atom_label]
rot_ang = ((i * ang_per_res) + zeta) * handedness
z = (self.rise_per_residue * i) + z_shift
coords = cylindrical_to_cartesian(
radius=r, azimuth=rot_ang, z=z, radians=True)
atom = Atom(
coordinates=coords, element=atom_label[0],
ampal_parent=residue, res_label=atom_label)
atoms_dict[atom_label] = atom
residue.atoms = atoms_dict
monomers.append(residue)
self._monomers = monomers
self.relabel_monomers()
self.relabel_atoms()
return
|
<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, aa=None, major_pitch=225.8, major_radius=5.07, major_handedness='l', minor_helix_type='alpha', orientation=1, phi_c_alpha=0.0, minor_repeat=None):
"""Creates a `HelicalHelix` between a `start` and `end` point."""
|
start = numpy.array(start)
end = numpy.array(end)
if aa is None:
minor_rise_per_residue = _helix_parameters[minor_helix_type][1]
aa = int((numpy.linalg.norm(end - start) /
minor_rise_per_residue) + 1)
instance = cls(
aa=aa, major_pitch=major_pitch, major_radius=major_radius,
major_handedness=major_handedness,
minor_helix_type=minor_helix_type, orientation=orientation,
phi_c_alpha=phi_c_alpha, minor_repeat=minor_repeat)
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 curve(self):
"""Curve of the super helix."""
|
return HelicalCurve.pitch_and_radius(
self.major_pitch, self.major_radius,
handedness=self.major_handedness)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def curve_primitive(self):
"""`Primitive` of the super-helical curve."""
|
curve = self.curve
curve.axis_start = self.helix_start
curve.axis_end = self.helix_end
coords = curve.get_coords(
n_points=(self.num_monomers + 1), spacing=self.minor_rise_per_residue)
if self.orientation == -1:
coords.reverse()
return Primitive.from_coordinates(coords)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def major_rise_per_monomer(self):
"""Rise along super-helical axis per monomer."""
|
return numpy.cos(numpy.deg2rad(self.curve.alpha)) * self.minor_rise_per_residue
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minor_residues_per_turn(self, minor_repeat=None):
"""Calculates the number of residues per turn of the minor helix. Parameters minor_repeat : float, optional Hydrophobic repeat of the minor helix. Returns ------- minor_rpt : float Residues per turn of the minor helix. """
|
if minor_repeat is None:
minor_rpt = _helix_parameters[self.minor_helix_type][0]
else:
# precession angle in radians
precession = self.curve.t_from_arc_length(
minor_repeat * self.minor_rise_per_residue)
if self.orientation == -1:
precession = -precession
if self.major_handedness != self.minor_handedness:
precession = -precession
minor_rpt = ((minor_repeat * numpy.pi * 2) /
((2 * numpy.pi) + precession))
return minor_rpt
|
<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 the `HelicalHelix`."""
|
helical_helix = Polypeptide()
primitive_coords = self.curve_primitive.coordinates
helices = [Helix.from_start_and_end(start=primitive_coords[i],
end=primitive_coords[i + 1],
helix_type=self.minor_helix_type,
aa=1)
for i in range(len(primitive_coords) - 1)]
residues_per_turn = self.minor_residues_per_turn(
minor_repeat=self.minor_repeat)
if residues_per_turn == 0:
residues_per_turn = _helix_parameters[self.minor_helix_type][0]
if self.minor_handedness == 'l':
residues_per_turn *= -1
# initial phi_c_alpha value calculated using the first Helix in helices.
if self.orientation != -1:
initial_angle = dihedral(numpy.array([0, 0, 0]),
primitive_coords[0],
primitive_coords[1],
helices[0][0]['CA'])
else:
initial_angle = dihedral(
numpy.array([0, 0, primitive_coords[0][2]]),
primitive_coords[0],
numpy.array([primitive_coords[0][0],
primitive_coords[0][1], primitive_coords[1][2]]),
helices[0][0]['CA'])
# angle required to achieve desired phi_c_alpha value of self.phi_c_alpha.
addition_angle = self.phi_c_alpha - initial_angle
for i, h in enumerate(helices):
angle = (i * (360.0 / residues_per_turn)) + addition_angle
h.rotate(angle=angle, axis=h.axis.unit_tangent,
point=h.helix_start)
helical_helix.extend(h)
helical_helix.relabel_all()
self._monomers = helical_helix._monomers[:]
for monomer in self._monomers:
monomer.ampal_parent = self
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 rotate_monomers(self, angle, radians=False):
""" Rotates each Residue in the Polypeptide. Notes ----- Each monomer is rotated about the axis formed between its corresponding primitive `PseudoAtom` and that of the subsequent `Monomer`. Parameters angle : float Angle by which to rotate each monomer. radians : bool Indicates whether angle is in radians or degrees. """
|
if radians:
angle = numpy.rad2deg(angle)
for i in range(len(self.primitive) - 1):
axis = self.primitive[i + 1]['CA'] - self.primitive[i]['CA']
point = self.primitive[i]['CA']._vector
self[i].rotate(angle=angle, axis=axis, point=point)
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 side_chain_centres(assembly, masses=False):
""" PseudoGroup containing side_chain centres of each Residue in each Polypeptide in Assembly. Notes ----- Each PseudoAtom is a side-chain centre. There is one PseudoMonomer per chain in ampal (each containing len(chain) PseudoAtoms). The PseudoGroup has len(ampal) PseudoMonomers. Parameters assembly : Assembly masses : bool If True, side-chain centres are centres of mass. If False, side-chain centres are centres of coordinates. Returns ------- PseudoGroup containing all side_chain centres, and with ampal_parent=assembly. """
|
if masses:
elts = set([x.element for x in assembly.get_atoms()])
masses_dict = {e: element_data[e]['atomic mass'] for e in elts}
pseudo_monomers = []
for chain in assembly:
if isinstance(chain, Polypeptide):
centres = OrderedDict()
for r in chain.get_monomers(ligands=False):
side_chain = r.side_chain
if masses:
masses_list = [masses_dict[x.element] for x in side_chain]
else:
masses_list = None
if side_chain:
centre = centre_of_mass(points=[x._vector for x in side_chain], masses=masses_list)
# for Glycine residues.
else:
centre = r['CA']._vector
centres[r.unique_id] = PseudoAtom(coordinates=centre, name=r.unique_id, ampal_parent=r)
pseudo_monomers.append(PseudoMonomer(pseudo_atoms=centres, monomer_id=' ', ampal_parent=chain))
return PseudoGroup(monomers=pseudo_monomers, ampal_parent=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 cluster_helices(helices, cluster_distance=12.0):
""" Clusters helices according to the minimum distance between the line segments representing their backbone. Notes ----- Each helix is represented as a line segement joining the CA of its first Residue to the CA if its final Residue. The minimal distance between pairwise line segments is calculated and stored in a condensed_distance_matrix. This is clustered using the 'single' linkage metric (all members of cluster i are at < cluster_distance away from at least one other member of cluster i). Helices belonging to the same cluster are grouped together as values of the returned cluster_dict. Parameters helices: Assembly cluster_distance: float Returns ------- cluster_dict: dict Keys: int cluster number Values: [Polymer] """
|
condensed_distance_matrix = []
for h1, h2 in itertools.combinations(helices, 2):
md = minimal_distance_between_lines(h1[0]['CA']._vector, h1[-1]['CA']._vector,
h2[0]['CA']._vector, h2[-1]['CA']._vector, segments=True)
condensed_distance_matrix.append(md)
z = linkage(condensed_distance_matrix, method='single')
clusters = fcluster(z, t=cluster_distance, criterion='distance')
cluster_dict = {}
for h, k in zip(helices, clusters):
if k not in cluster_dict:
cluster_dict[k] = [h]
else:
cluster_dict[k].append(h)
return cluster_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 find_kihs(assembly, hole_size=4, cutoff=7.0):
""" KnobIntoHoles between residues of different chains in assembly. Notes ----- A KnobIntoHole is a found when the side-chain centre of a Residue a chain is close than (cutoff) Angstroms from at least (hole_size) side-chain centres of Residues of a different chain. Parameters assembly : Assembly hole_size : int Number of Residues required to form each hole. cutoff : float Maximum distance between the knob and each of the hole residues. Returns ------- kihs : [KnobIntoHole] """
|
pseudo_group = side_chain_centres(assembly=assembly, masses=False)
pairs = itertools.permutations(pseudo_group, 2)
kihs = []
for pp_1, pp_2 in pairs:
for r in pp_1:
close_atoms = pp_2.is_within(cutoff, r)
# kihs occur between residue and (hole_size) closest side-chains on adjacent polypeptide.
if len(close_atoms) < hole_size:
continue
elif len(close_atoms) > hole_size:
close_atoms = sorted(close_atoms, key=lambda x: distance(x, r))[:hole_size]
kih = OrderedDict()
kih['k'] = r
for i, hole_atom in enumerate(close_atoms):
kih['h{0}'.format(i)] = hole_atom
knob_into_hole = KnobIntoHole(pseudo_atoms=kih)
kihs.append(knob_into_hole)
return kihs
|
<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_contiguous_packing_segments(polypeptide, residues, max_dist=10.0):
""" Assembly containing segments of polypeptide, divided according to separation of contiguous residues. Parameters polypeptide : Polypeptide residues : iterable containing Residues max_dist : float Separation beyond which splitting of Polymer occurs. Returns ------- segments : Assembly Each segment contains a subset of residues, each not separated by more than max_dist from the previous Residue. """
|
segments = Assembly(assembly_id=polypeptide.ampal_parent.id)
residues_in_polypeptide = list(sorted(residues.intersection(set(polypeptide.get_monomers())),
key=lambda x: int(x.id)))
if not residues_in_polypeptide:
return segments
# residue_pots contains separate pots of residues divided according to their separation distance.
residue_pots = []
pot = [residues_in_polypeptide[0]]
for r1, r2 in zip(residues_in_polypeptide, residues_in_polypeptide[1:]):
d = distance(r1['CA'], r2['CA'])
if d <= max_dist:
pot.append(r2)
if sum([len(x) for x in residue_pots] + [len(pot)]) == len(residues_in_polypeptide):
residue_pots.append(pot)
else:
residue_pots.append(pot)
pot = [r2]
for pot in residue_pots:
segment = polypeptide.get_slice_from_res_id(pot[0].id, pot[-1].id)
segment.ampal_parent = polypeptide.ampal_parent
segments.append(segment)
return segments
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_reference_primitive(polypeptide, start, end):
""" Generates a reference Primitive for a Polypeptide given start and end coordinates. Notes ----- Uses the rise_per_residue of the Polypeptide primitive to define the separation of points on the line joining start and end. Parameters polypeptide : Polypeptide start : numpy.array 3D coordinates of reference axis start end : numpy.array 3D coordinates of reference axis end Returns ------- reference_primitive : Primitive """
|
prim = polypeptide.primitive
q = find_foot(a=start, b=end, p=prim.coordinates[0])
ax = Axis(start=q, end=end)
# flip axis if antiparallel to polypeptide_vector
if not is_acute(polypeptide_vector(polypeptide), ax.unit_tangent):
ax = Axis(start=end, end=q)
arc_length = 0
points = [ax.start]
for rise in prim.rise_per_residue()[:-1]:
arc_length += rise
t = ax.t_from_arc_length(arc_length=arc_length)
point = ax.point(t)
points.append(point)
reference_primitive = Primitive.from_coordinates(points)
return reference_primitive
|
<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_helices(cls, assembly, cutoff=7.0, min_helix_length=8):
""" Generate KnobGroup from the helices in the assembly - classic socket functionality. Notes ----- Socket identifies knobs-into-holes (KIHs) packing motifs in protein structures. The following resources can provide more information: The socket webserver: http://coiledcoils.chm.bris.ac.uk/socket/server.html The help page: http://coiledcoils.chm.bris.ac.uk/socket/help.html The original publication reference: Walshaw, J. & Woolfson, D.N. (2001) J. Mol. Biol., 307 (5), 1427-1450. Parameters assembly : Assembly cutoff : float Socket cutoff in Angstroms min_helix_length : int Minimum number of Residues in a helix considered for KIH packing. Returns ------- instance : KnobGroup None if no helices or no kihs. """
|
cutoff = float(cutoff)
helices = Assembly([x for x in assembly.helices if len(x) >= min_helix_length])
if len(helices) <= 1:
return None
# reassign ampal_parents
helices.relabel_polymers([x.ampal_parent.id for x in helices])
for i, h in enumerate(helices):
h.number = i
h.ampal_parent = h[0].ampal_parent
for r in h.get_monomers():
r.tags['helix'] = h
all_kihs = []
cluster_dict = cluster_helices(helices, cluster_distance=(cutoff + 10))
for k, v in cluster_dict.items():
if len(v) > 1:
kihs = find_kihs(v, cutoff=cutoff, hole_size=4)
if len(kihs) == 0:
continue
for x in kihs:
all_kihs.append(x)
instance = cls(ampal_parent=helices, cutoff=cutoff)
for x in all_kihs:
x.ampal_parent = instance
instance._monomers = all_kihs
instance.relabel_monomers()
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 knob_subgroup(self, cutoff=7.0):
""" KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff. """
|
if cutoff > self.cutoff:
raise ValueError("cutoff supplied ({0}) cannot be greater than self.cutoff ({1})".format(cutoff,
self.cutoff))
return KnobGroup(monomers=[x for x in self.get_monomers()
if x.max_kh_distance <= cutoff], ampal_parent=self.ampal_parent)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def graph(self):
""" Returns MultiDiGraph from kihs. Nodes are helices and edges are kihs. """
|
g = networkx.MultiDiGraph()
edge_list = [(x.knob_helix, x.hole_helix, x.id, {'kih': x}) for x in self.get_monomers()]
g.add_edges_from(edge_list)
return g
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_graph(g, cutoff=7.0, min_kihs=2):
""" Get subgraph formed from edges that have max_kh_distance < cutoff. Parameters g : MultiDiGraph representing KIHs g is the output from graph_from_protein cutoff : float Socket cutoff in Angstroms. Default is 7.0. min_kihs : int Minimum number of KIHs shared between all pairs of connected nodes in the graph. Returns ------- networkx.MultiDigraph subgraph formed from edges that have max_kh_distance < cutoff. """
|
edge_list = [e for e in g.edges(keys=True, data=True) if e[3]['kih'].max_kh_distance <= cutoff]
if min_kihs > 0:
c = Counter([(e[0], e[1]) for e in edge_list])
# list of nodes that share > min_kihs edges with at least one other node.
node_list = set(list(itertools.chain.from_iterable([k for k, v in c.items() if v > min_kihs])))
edge_list = [e for e in edge_list if (e[0] in node_list) and (e[1] in node_list)]
return networkx.MultiDiGraph(edge_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_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2):
""" Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles. """
|
g = self.filter_graph(self.graph, cutoff=cutoff, min_kihs=min_kihs)
ccs = sorted(networkx.connected_component_subgraphs(g, copy=True),
key=lambda x: len(x.nodes()), reverse=True)
cc = ccs[cc_number]
helices = [x for x in g.nodes() if x.number in cc.nodes()]
assigned_regions = self.get_assigned_regions(helices=helices, include_alt_states=False, complementary_only=True)
coiledcoil_monomers = [h.get_slice_from_res_id(*assigned_regions[h.number]) for h in helices]
return Assembly(coiledcoil_monomers)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daisy_chain_graph(self):
""" Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self. """
|
g = networkx.DiGraph()
for x in self.get_monomers():
for h in x.hole:
g.add_edge(x.knob, h)
return g
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def knob_end(self):
""" Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom. Returns CA coordinates for GLY. """
|
side_chain_atoms = self.knob_residue.side_chain
if not side_chain_atoms:
return self.knob_residue['CA']
distances = [distance(self.knob_residue['CB'], x) for x in side_chain_atoms]
max_d = max(distances)
knob_end_atoms = [atom for atom, d in zip(side_chain_atoms, distances) if d == max_d]
if len(knob_end_atoms) == 1:
return knob_end_atoms[0]._vector
else:
return numpy.mean([x._vector for x in knob_end_atoms], axis=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 max_knob_end_distance(self):
""" Maximum distance between knob_end and each of the hole side-chain centres. """
|
return max([distance(self.knob_end, h) for h in self.hole])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base_install():
"""Generates configuration setting for required functionality of ISAMBARD."""
|
# scwrl
scwrl = {}
print('{BOLD}{HEADER}Generating configuration files for ISAMBARD.{END_C}\n'
'All required input can use tab completion for paths.\n'
'{BOLD}Setting up SCWRL 4.0 (Recommended){END_C}'.format(**text_colours))
scwrl_path = get_user_path('Please provide a path to your SCWRL executable', required=False)
scwrl['path'] = str(scwrl_path)
pack_mode = get_user_option(
'Please choose your packing mode (flexible is significantly slower but is more accurate).',
['flexible', 'rigid'])
if pack_mode == 'rigid':
scwrl['rigid_rotamer_model'] = True
else:
scwrl['rigid_rotamer_model'] = False
settings['scwrl'] = scwrl
# dssp
print('{BOLD}Setting up DSSP (Recommended){END_C}'.format(**text_colours))
dssp = {}
dssp_path = get_user_path('Please provide a path to your DSSP executable.', required=False)
dssp['path'] = str(dssp_path)
settings['dssp'] = dssp
# buff
print('{BOLD}Setting up BUFF (Required){END_C}'.format(**text_colours))
buff = {}
ffs = []
ff_dir = isambard_path / 'buff' / 'force_fields'
for ff_file in os.listdir(str(ff_dir)):
ff = pathlib.Path(ff_file)
ffs.append(ff.stem)
force_field_choice = get_user_option(
'Please choose the default BUFF force field, this can be modified during runtime.',
ffs)
buff['default_force_field'] = force_field_choice
settings['buff'] = buff
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 optional_install():
"""Generates configuration settings for optional functionality of ISAMBARD."""
|
# reduce
print('{BOLD}Setting up Reduce (optional){END_C}'.format(**text_colours))
reduce = {}
reduce_path = get_user_path('Please provide a path to your reduce executable.', required=False)
reduce['path'] = str(reduce_path)
reduce['folder'] = str(reduce_path.parent) if reduce_path else ''
settings['reduce'] = reduce
# naccess
print('{BOLD}Setting up naccess (optional){END_C}'.format(**text_colours))
naccess = {}
naccess_path = get_user_path('Please provide a path to your naccess executable.', required=False)
naccess['path'] = str(naccess_path)
settings['naccess'] = naccess
# profit
print('{BOLD}Setting up ProFit (optional){END_C}'.format(**text_colours))
profit = {}
profit_path = get_user_path('Please provide a path to your ProFit executable.', required=False)
profit['path'] = str(profit_path)
settings['profit'] = profit
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):
"""Generates a PDB string for the `PseudoMonomer`."""
|
pdb_str = write_pdb(
[self], ' ' if not self.tags['chain_id'] else self.tags['chain_id'])
return pdb_str
|
<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_coordinates(cls, coordinates):
"""Creates a `Primitive` from a list of coordinates."""
|
prim = cls()
for coord in coordinates:
pm = PseudoMonomer(ampal_parent=prim)
pa = PseudoAtom(coord, ampal_parent=pm)
pm.atoms = OrderedDict([('CA', pa)])
prim.append(pm)
prim.relabel_all()
return prim
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rise_per_residue(self):
"""The rise per residue at each point on the Primitive. Notes ----- Each element of the returned list is the rise per residue, at a point on the Primitive. Element i is the distance between primitive[i] and primitive[i + 1]. The final value is None. """
|
rprs = [distance(self[i]['CA'], self[i + 1]['CA'])
for i in range(len(self) - 1)]
rprs.append(None)
return rprs
|
<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 `Polynucleotide` as a string. Returns ------- sequence : str String of the monomer sequence of the `Polynucleotide`. """
|
seq = [x.mol_code 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 run_dssp(pdb, path=True, outfile=None):
"""Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. outfile : str, optional Filepath for storing the dssp output. Returns ------- dssp_out : str Std out from DSSP. """
|
if not path:
if type(pdb) == str:
pdb = pdb.encode()
try:
temp_pdb = tempfile.NamedTemporaryFile(delete=False)
temp_pdb.write(pdb)
temp_pdb.seek(0)
dssp_out = subprocess.check_output(
[global_settings['dssp']['path'], temp_pdb.name])
temp_pdb.close()
finally:
os.remove(temp_pdb.name)
else:
dssp_out = subprocess.check_output(
[global_settings['dssp']['path'], pdb])
# Python 3 string formatting.
dssp_out = dssp_out.decode()
if outfile:
with open(outfile, 'w') as outf:
outf.write(dssp_out)
return dssp_out
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_solvent_accessibility_dssp(in_dssp, path=True):
"""Uses DSSP to extract solvent accessibilty information on every residue. Notes ----- For more information on the solvent accessibility metrics used in dssp, see: http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC In the dssp files value is labeled 'ACC'. Parameters in_dssp : str Path to DSSP file. path : bool Indicates if in_dssp is a path or a string. Returns ------- dssp_residues : list Each internal list contains: [0] int Residue number [1] str Chain identifier [2] str Residue type [3] int dssp solvent accessibilty """
|
if path:
with open(in_dssp, 'r') as inf:
dssp_out = inf.read()
else:
dssp_out = in_dssp[:]
dssp_residues = []
go = False
for line in dssp_out.splitlines():
if go:
try:
res_num = int(line[5:10].strip())
chain = line[10:12].strip()
residue = line[13]
acc = int(line[35:38].strip())
# It is IMPORTANT that acc remains the final value of the
# returned list, due to its usage in
# isambard.ampal.base_ampal.tag_dssp_solvent_accessibility
dssp_residues.append([res_num, chain, residue, acc])
except ValueError:
pass
else:
if line[2] == '#':
go = True
pass
return dssp_residues
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_helices_dssp(in_pdb):
"""Uses DSSP to find alpha-helices and extracts helices from a pdb file. Returns a length 3 list with a helix id, the chain id and a dict containing the coordinates of each residues CA. Parameters in_pdb : string Path to a PDB file. """
|
from ampal.pdb_parser import split_pdb_lines
dssp_out = subprocess.check_output(
[global_settings['dssp']['path'], in_pdb])
helix = 0
helices = []
h_on = False
for line in dssp_out.splitlines():
dssp_line = line.split()
try:
if dssp_line[4] == 'H':
if helix not in [x[0] for x in helices]:
helices.append(
[helix, dssp_line[2], {int(dssp_line[1]): None}])
else:
helices[helix][2][int(dssp_line[1])] = None
h_on = True
else:
if h_on:
helix += 1
h_on = False
except IndexError:
pass
with open(in_pdb, 'r') as pdb:
pdb_atoms = split_pdb_lines(pdb.read())
for atom in pdb_atoms:
for helix in helices:
if (atom[2] == "CA") and (atom[5] == helix[1]) and (atom[6] in helix[2].keys()):
helix[2][atom[6]] = tuple(atom[8:11])
return helices
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_pp_helices(in_pdb):
"""Uses DSSP to find polyproline helices in a pdb file. Returns a length 3 list with a helix id, the chain id and a dict containing the coordinates of each residues CA. Parameters in_pdb : string Path to a PDB file. """
|
t_phi = -75.0
t_phi_d = 29.0
t_psi = 145.0
t_psi_d = 29.0
pph_dssp = subprocess.check_output(
[global_settings['dssp']['path'], in_pdb])
dssp_residues = []
go = False
for line in pph_dssp.splitlines():
if go:
res_num = int(line[:5].strip())
chain = line[11:13].strip()
ss_type = line[16]
phi = float(line[103:109].strip())
psi = float(line[109:116].strip())
dssp_residues.append((res_num, ss_type, chain, phi, psi))
else:
if line[2] == '#':
go = True
pass
pp_chains = []
chain = []
ch_on = False
for item in dssp_residues:
if (item[1] == ' ') and (
t_phi - t_phi_d < item[3] < t_phi + t_phi_d) and (
t_psi - t_psi_d < item[4] < t_psi + t_psi_d):
chain.append(item)
ch_on = True
else:
if ch_on:
pp_chains.append(chain)
chain = []
ch_on = False
pp_chains = [x for x in pp_chains if len(x) > 1]
pp_helices = []
with open(in_pdb, 'r') as pdb:
pdb_atoms = split_pdb_lines(pdb.read())
for pp_helix in pp_chains:
chain_id = pp_helix[0][2]
res_range = [x[0] for x in pp_helix]
helix = []
for atom in pdb_atoms:
if (atom[2] == "CA") and (
atom[5] == chain_id) and (
atom[6] in res_range):
helix.append(tuple(atom[8:11]))
pp_helices.append(helix)
return pp_helices
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" This will offer a step by step guide to create a new run in TestRail, update tests in the run with results, and close the run """
|
# Parse command line arguments
args = get_args()
# Instantiate the TestRail client
# Use the CLI argument to identify which project to work with
tr = TestRail(project_dict[args.project])
# Get a reference to the current project
project = tr.project(project_dict[args.project])
# To create a new run in TestRail, first create a new, blank run
# Update the new run with a name and project reference
new_run = tr.run()
new_run.name = "Creating a new Run through the API"
new_run.project = project
new_run.include_all = True # All Cases in the Suite will be added as Tests
# Add the run in TestRail. This creates the run, and returns a run object
run = tr.add(new_run)
print("Created new run: {0}".format(run.name))
# Before starting the tests, lets pull in the Status objects for later
PASSED = tr.status('passed')
FAILED = tr.status('failed')
BLOCKED = tr.status('blocked')
# Get a list of tests associated with the new run
tests = list(tr.tests(run))
print("Found {0} tests".format(len(tests)))
# Execute the tests, marking as passed, failed, or blocked
for test_num, test in enumerate(tests):
print("Executing test #{0}".format(test_num))
# Run your tests here, reaching some sort of pass/fail criteria
# This example will pick results at random and update the tests as such
test_status = random.choice([PASSED, FAILED, BLOCKED])
print("Updating test #{0} with a status of {1}".format(test_num,
test_status.name))
# Create a blank result, and associate it with a test and a status
result = tr.result()
result.test = test
result.status = test_status
result.comment = "The test case was udpated via a script"
# Add the result to TestRail
tr.add(result)
# All tests have been executed. Close this test run
print("Finished, closing the run")
tr.close(run)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memory():
"""Determine the machine's memory specifications. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """
|
mem_info = {}
if platform.linux_distribution()[0]:
with open('/proc/meminfo') as file:
c = 0
for line in file:
lst = line.split()
if str(lst[0]) == 'MemTotal:':
mem_info['total'] = int(lst[1])
elif str(lst[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
c += int(lst[1])
mem_info['free'] = c
mem_info['used'] = (mem_info['total']) - c
elif platform.mac_ver()[0]:
ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]
# Iterate processes
process_lines = ps.split('\n')
sep = re.compile('[\s]+')
rss_total = 0 # kB
for row in range(1, len(process_lines)):
row_text = process_lines[row].strip()
row_elements = sep.split(row_text)
try:
rss = float(row_elements[0]) * 1024
except:
rss = 0 # ignore...
rss_total += rss
# Process vm_stat
vm_lines = vm.split('\n')
sep = re.compile(':[\s]+')
vm_stats = {}
for row in range(1, len(vm_lines) - 2):
row_text = vm_lines[row].strip()
row_elements = sep.split(row_text)
vm_stats[(row_elements[0])] = int(row_elements[1].strip('\.')) * 4096
mem_info['total'] = rss_total
mem_info['used'] = vm_stats["Pages active"]
mem_info['free'] = vm_stats["Pages free"]
else:
raise('Unsupported Operating System.\n')
exit(1)
return mem_info
|
<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_chunk_size(N, n):
"""Given a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters N : int The size of one of the dimension of a two-dimensional array. n : int The number of times an 'N' by 'chunks_size' array can fit in memory. Returns ------- chunks_size : int The size of a dimension orthogonal to the dimension of size 'N'. """
|
mem_free = memory()['free']
if mem_free > 60000000:
chunks_size = int(((mem_free - 10000000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 40000000:
chunks_size = int(((mem_free - 7000000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 14000000:
chunks_size = int(((mem_free - 2000000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 8000000:
chunks_size = int(((mem_free - 1400000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 2000000:
chunks_size = int(((mem_free - 900000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 1000000:
chunks_size = int(((mem_free - 400000) * 1000) / (4 * n * N))
return chunks_size
else:
raise MemoryError("\nERROR: DBSCAN_multiplex @ get_chunk_size:\n"
"this machine does not have enough free memory "
"to perform the remaining computations.\n")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_floating_ips(self):
""" Lists all of the Floating IPs available on the account. """
|
if self.api_version == 2:
json = self.request('/floating_ips')
return json['floating_ips']
else:
raise DoError(v2_api_required_str)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_floating_ip(self, **kwargs):
""" Creates a Floating IP and assigns it to a Droplet or reserves it to a region. """
|
droplet_id = kwargs.get('droplet_id')
region = kwargs.get('region')
if self.api_version == 2:
if droplet_id is not None and region is not None:
raise DoError('Only one of droplet_id and region is required to create a Floating IP. ' \
'Set one of the variables and try again.')
elif droplet_id is None and region is None:
raise DoError('droplet_id or region is required to create a Floating IP. ' \
'Set one of the variables and try again.')
else:
if droplet_id is not None:
params = {'droplet_id': droplet_id}
else:
params = {'region': region}
json = self.request('/floating_ips', params=params, method='POST')
return json['floating_ip']
else:
raise DoError(v2_api_required_str)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destroy_floating_ip(self, ip_addr):
""" Deletes a Floating IP and removes it from the account. """
|
if self.api_version == 2:
self.request('/floating_ips/' + ip_addr, method='DELETE')
else:
raise DoError(v2_api_required_str)
|
<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_floating_ip(self, ip_addr, droplet_id):
""" Assigns a Floating IP to a Droplet. """
|
if self.api_version == 2:
params = {'type': 'assign','droplet_id': droplet_id}
json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST')
return json['action']
else:
raise DoError(v2_api_required_str)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unassign_floating_ip(self, ip_addr):
""" Unassign a Floating IP from a Droplet. The Floating IP will be reserved in the region but not assigned to a Droplet. """
|
if self.api_version == 2:
params = {'type': 'unassign'}
json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST')
return json['action']
else:
raise DoError(v2_api_required_str)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_floating_ip_actions(self, ip_addr):
""" Retrieve a list of all actions that have been executed on a Floating IP. """
|
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions')
return json['actions']
else:
raise DoError(v2_api_required_str)
|
<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_floating_ip_action(self, ip_addr, action_id):
""" Retrieve the status of a Floating IP action. """
|
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions/' + action_id)
return json['action']
else:
raise DoError(v2_api_required_str)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_sign(message, secret):
"""Sign a message."""
|
digest = hmac.new(secret, message, hashlib.sha256).digest()
return base64.b64encode(digest)
|
<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_signature_from_signature_string(self, signature):
"""Return the signature from the signature header or None."""
|
match = self.SIGNATURE_RE.search(signature)
if not match:
return None
return match.group(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 get_headers_from_signature(self, signature):
"""Returns a list of headers fields to sign. According to http://tools.ietf.org/html/draft-cavage-http-signatures-03 section 2.1.3, the headers are optional. If not specified, the single value of "Date" must be used. """
|
match = self.SIGNATURE_HEADERS_RE.search(signature)
if not match:
return ['date']
headers_string = match.group(1)
return headers_string.split()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def header_canonical(self, header_name):
"""Translate HTTP headers to Django header names."""
|
# Translate as stated in the docs:
# https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META
header_name = header_name.lower()
if header_name == 'content-type':
return 'CONTENT-TYPE'
elif header_name == 'content-length':
return 'CONTENT-LENGTH'
return 'HTTP_%s' % header_name.replace('-', '_').upper()
|
<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_dict_to_sign(self, request, signature_headers):
"""Build a dict with headers and values used in the signature. "signature_headers" is a list of lowercase header names. """
|
d = {}
for header in signature_headers:
if header == '(request-target)':
continue
d[header] = request.META.get(self.header_canonical(header))
return d
|
<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_signature(self, user_api_key, user_secret, request):
"""Return the signature for the request."""
|
path = request.get_full_path()
sent_signature = request.META.get(
self.header_canonical('Authorization'))
signature_headers = self.get_headers_from_signature(sent_signature)
unsigned = self.build_dict_to_sign(request, signature_headers)
# Sign string and compare.
signer = HeaderSigner(
key_id=user_api_key, secret=user_secret,
headers=signature_headers, algorithm=self.ALGORITHM)
signed = signer.sign(unsigned, method=request.method, path=path)
return signed['authorization']
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def camel_to_snake_case(string):
"""Converts 'string' presented in camel case to snake case. e.g.: CamelCase => snake_case """
|
s = _1.sub(r'\1_\2', string)
return _2.sub(r'\1_\2', s).lower()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_assembler(query_string, no_redirect=0, no_html=0, skip_disambig=0):
"""Assembler of parameters for building request query. Args: query_string: Query to be passed to DuckDuckGo API. no_redirect: Skip HTTP redirects (for !bang commands). Default - False. no_html: Remove HTML from text, e.g. bold and italics. Default - False. skip_disambig: Skip disambiguation (D) Type. Default - False. Returns: A “percent-encoded” string which is used as a part of the query. """
|
params = [('q', query_string.encode("utf-8")), ('format', 'json')]
if no_redirect:
params.append(('no_redirect', 1))
if no_html:
params.append(('no_html', 1))
if skip_disambig:
params.append(('skip_disambig', 1))
return '/?' + urlencode(params)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(query_string, secure=False, container='namedtuple', verbose=False, user_agent=api.USER_AGENT, no_redirect=False, no_html=False, skip_disambig=False):
""" Generates and sends a query to DuckDuckGo API. Args: query_string: Query to be passed to DuckDuckGo API. secure: Use secure SSL/TLS connection. Default - False. Syntactic sugar is secure_query function which is passed the same parameters. container: Indicates how dict-like objects are serialized. There are two possible options: namedtuple and dict. If 'namedtuple' is passed the objects will be serialized to namedtuple instance of certain class. If 'dict' is passed the objects won't be deserialized. Default value: 'namedtuple'. verbose: Don't raise any exception if error occurs. Default value: False. user_agent: User-Agent header of HTTP requests to DuckDuckGo API. Default value: 'duckduckpy 0.2' no_redirect: Skip HTTP redirects (for !bang commands). Default value: False. no_html: Remove HTML from text, e.g. bold and italics. Default value: False. skip_disambig: Skip disambiguation (D) Type. Default value: False. Raises: DuckDuckDeserializeError: JSON serialization failed. DuckDuckConnectionError: Something went wrong with client operation. DuckDuckArgumentError: Passed argument is wrong. Returns: Container depends on container parameter. Each field in the response is converted to the so-called snake case. Usage: <class 'duckduckpy.api.Response'> <class 'duckduckpy.api.Result'> <type 'dict'> <type 'dict'> """
|
if container not in Hook.containers:
raise exc.DuckDuckArgumentError(
"Argument 'container' must be one of the values: "
"{0}".format(', '.join(Hook.containers)))
headers = {"User-Agent": user_agent}
url = url_assembler(
query_string,
no_redirect=no_redirect,
no_html=no_html,
skip_disambig=skip_disambig)
if secure:
conn = http_client.HTTPSConnection(api.SERVER_HOST)
else:
conn = http_client.HTTPConnection(api.SERVER_HOST)
try:
conn.request("GET", url, "", headers)
resp = conn.getresponse()
data = decoder(resp.read())
except socket.gaierror as e:
raise exc.DuckDuckConnectionError(e.strerror)
finally:
conn.close()
hook = Hook(container, verbose=verbose)
try:
obj = json.loads(data, object_hook=hook)
except ValueError:
raise exc.DuckDuckDeserializeError(
"Unable to deserialize response to an object")
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(type_dict, *type_parameters):
""" Construct a List containing type 'klazz'. """
|
assert len(type_parameters) == 1
klazz = TypeFactory.new(type_dict, *type_parameters[0])
assert isclass(klazz)
assert issubclass(klazz, Object)
return TypeMetaclass('%sList' % klazz.__name__, (ListContainer,), {'TYPE': klazz})
|
<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_file(filename):
"Runs the given scent.py file."
mod_name = '.'.join(os.path.basename(filename).split('.')[:-1])
mod_path = os.path.dirname(filename)
if mod_name in sys.modules:
del sys.modules[mod_name]
if mod_path not in set(sys.modules.keys()):
sys.path.insert(0, mod_path)
return ScentModule(__import__(mod_name, g, g), filename)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(type_dict, type_factory, *type_parameters):
""" Create a fully reified type from a type schema. """
|
type_tuple = (type_factory,) + type_parameters
if type_tuple not in type_dict:
factory = TypeFactory.get_factory(type_factory)
reified_type = factory.create(type_dict, *type_parameters)
type_dict[type_tuple] = reified_type
return type_dict[type_tuple]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap(sig):
"""Convert a Python class into a type signature."""
|
if isclass(sig) and issubclass(sig, Object):
return TypeSignature(sig)
elif isinstance(sig, TypeSignature):
return sig
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger_modified(self, filepath):
"""Triggers modified event if the given filepath mod time is newer."""
|
mod_time = self._get_modified_time(filepath)
if mod_time > self._watched_files.get(filepath, 0):
self._trigger('modified', filepath)
self._watched_files[filepath] = mod_time
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger_created(self, filepath):
"""Triggers created event if file exists."""
|
if os.path.exists(filepath):
self._trigger('created', filepath)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger_deleted(self, filepath):
"""Triggers deleted event if the flie doesn't exist."""
|
if not os.path.exists(filepath):
self._trigger('deleted', filepath)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, *message):
""" Logs a messate to a defined io stream if available. """
|
if self._logger is None:
return
s = " ".join([str(m) for m in message])
self._logger.write(s+'\n')
self._logger.flush()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_repo(self, filepath):
""" This excludes repository directories because they cause some exceptions occationally. """
|
filepath = set(filepath.replace('\\', '/').split('/'))
for p in ('.git', '.hg', '.svn', '.cvs', '.bzr'):
if p in filepath:
return True
return 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 _modify_event(self, event_name, method, func):
""" Wrapper to call a list's method from one of the events """
|
if event_name not in self.ALL_EVENTS:
raise TypeError(('event_name ("%s") can only be one of the '
'following: %s') % (event_name,
repr(self.ALL_EVENTS)))
if not isinstance(func, collections.Callable):
raise TypeError(('func must be callable to be added as an '
'observer.'))
getattr(self._events[event_name], method)(func)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _watch_file(self, filepath, trigger_event=True):
"""Adds the file's modified time into its internal watchlist."""
|
is_new = filepath not in self._watched_files
if trigger_event:
if is_new:
self.trigger_created(filepath)
else:
self.trigger_modified(filepath)
try:
self._watched_files[filepath] = self._get_modified_time(filepath)
except OSError:
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 _unwatch_file(self, filepath, trigger_event=True):
""" Removes the file from the internal watchlist if exists. """
|
if filepath not in self._watched_files:
return
if trigger_event:
self.trigger_deleted(filepath)
del self._watched_files[filepath]
|
<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_modified(self, filepath):
""" Returns True if the file has been modified since last seen. Will return False if the file has not been seen before. """
|
if self._is_new(filepath):
return False
mtime = self._get_modified_time(filepath)
return self._watched_files[filepath] < mtime
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loop(self, sleep_time=1, callback=None):
""" Goes into a blocking IO loop. If polling is used, the sleep_time is the interval, in seconds, between polls. """
|
self.log("No supported libraries found: using polling-method.")
self._running = True
self.trigger_init()
self._scan(trigger=False) # put after the trigger
if self._warn:
print("""
You should install a third-party library so I don't eat CPU.
Supported libraries are:
- pyinotify (Linux)
- pywin32 (Windows)
- MacFSEvents (OSX)
Use pip or easy_install and install one of those libraries above.
""")
while self._running:
self._scan()
if isinstance(callback, collections.Callable):
callback()
time.sleep(sleep_time)
|
<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(sniffer_instance=None, wait_time=0.5, clear=True, args=(), debug=False):
""" Runs the auto tester loop. Internally, the runner instanciates the sniffer_cls and scanner class. ``sniffer_instance`` The class to run. Usually this is set to but a subclass of scanner. Defaults to Sniffer. Sniffer class documentation for more information. ``wait_time`` The time, in seconds, to wait between polls. This is dependent on the underlying scanner implementation. OS-specific libraries may choose to ignore this parameter. Defaults to 0.5 seconds. ``clear`` Boolean. Set to True to clear the terminal before running the sniffer, (alias, the unit tests). Defaults to True. ``args`` The arguments to pass to the sniffer/test runner. Defaults to (). ``debug`` Boolean. Sets the scanner and sniffer in debug mode, printing more internal information. Defaults to False (and should usually be False). """
|
if sniffer_instance is None:
sniffer_instance = ScentSniffer()
if debug:
scanner = Scanner(
sniffer_instance.watch_paths,
scent=sniffer_instance.scent, logger=sys.stdout)
else:
scanner = Scanner(
sniffer_instance.watch_paths, scent=sniffer_instance.scent)
#sniffer = sniffer_cls(tuple(args), clear, debug)
sniffer_instance.set_up(tuple(args), clear, debug)
sniffer_instance.observe_scanner(scanner)
scanner.loop(wait_time)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(sniffer_instance=None, test_args=(), progname=sys.argv[0], args=sys.argv[1:]):
""" Runs the program. This is used when you want to run this program standalone. ``sniffer_instance`` A class (usually subclassed of Sniffer) that hooks into the scanner and handles running the test framework. Defaults to Sniffer instance. ``test_args`` This function normally extracts args from ``--test-arg ARG`` command. A preset argument list can be passed. Defaults to an empty tuple. ``program`` Program name. Defaults to sys.argv[0]. ``args`` Command line arguments. Defaults to sys.argv[1:] """
|
parser = OptionParser(version="%prog " + __version__)
parser.add_option('-w', '--wait', dest="wait_time", metavar="TIME",
default=0.5, type="float",
help="Wait time, in seconds, before possibly rerunning"
"tests. (default: %default)")
parser.add_option('--no-clear', dest="clear_on_run", default=True,
action="store_false",
help="Disable the clearing of screen")
parser.add_option('--debug', dest="debug", default=False,
action="store_true",
help="Enabled debugging output. (default: %default)")
parser.add_option('-x', '--test-arg', dest="test_args", default=[],
action="append",
help="Arguments to pass to nose (use multiple times to "
"pass multiple arguments.)")
(options, args) = parser.parse_args(args)
test_args = test_args + tuple(options.test_args)
if options.debug:
print("Options:", options)
print("Test Args:", test_args)
try:
print("Starting watch...")
run(sniffer_instance, options.wait_time, options.clear_on_run,
test_args, options.debug)
except KeyboardInterrupt:
print("Good bye.")
except Exception:
import traceback
traceback.print_exc()
return sys.exit(1)
return sys.exit(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 set_up(self, test_args=(), clear=True, debug=False):
""" Sets properties right before calling run. ``test_args`` The arguments to pass to the test runner. ``clear`` Boolean. Set to True if we should clear console before running the tests. ``debug`` Boolean. Set to True if we want to print debugging information. """
|
self.test_args = test_args
self.debug, self.clear = debug, clear
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def observe_scanner(self, scanner):
""" Hooks into multiple events of a scanner. """
|
scanner.observe(scanner.ALL_EVENTS,
self.absorb_args(self.modules.restore))
if self.clear:
scanner.observe(scanner.ALL_EVENTS,
self.absorb_args(self.clear_on_run))
scanner.observe(scanner.ALL_EVENTS, self.absorb_args(self._run))
if self.debug:
scanner.observe('created', echo("callback - created %(file)s"))
scanner.observe('modified', echo("callback - changed %(file)s"))
scanner.observe('deleted', echo("callback - deleted %(file)s"))
self._scanners.append(scanner)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_on_run(self, prefix="Running Tests:"):
"""Clears console before running the tests."""
|
if platform.system() == 'Windows':
os.system('cls')
else:
os.system('clear')
if prefix:
print(prefix)
|
<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(self):
""" Runs the unit test framework. Can be overridden to run anything. Returns True on passing and False on failure. """
|
try:
import nose
arguments = [sys.argv[0]] + list(self.test_args)
return nose.run(argv=arguments)
except ImportError:
print()
print("*** Nose library missing. Please install it. ***")
print()
raise
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.