text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Converts a list of Parameters into DEAP format. <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]) if parameter.value[1] < 0: raise AttributeError( '"{}" parameter has an invalid range. Range values ' 'must be greater than zero'.format(parameter.label)) self.value_ranges.append(parameter.value[1]) var_label = 'var{}'.format(current_var) self.arrangement.append(var_label) self.variable_parameters.append(var_label) current_var += 1 elif parameter.type == ParameterType.STATIC: self.arrangement.append(parameter.value) else: raise AttributeError( '"{}"Unknown parameter type ({}). Parameters can be STATIC or' ' DYNAMIC.'.format(parameter.type)) return
<SYSTEM_TASK:> Assigns fitnesses to parameters. <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 --------- targets Parameter values for each member of the population. """
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.build_fn, px_parameters) fitnesses = map(self.eval_fn, models) else: with futures.ProcessPoolExecutor( max_workers=self._cores) as executor: models = executor.map(self.build_fn, px_parameters) fitnesses = executor.map(self.eval_fn, models) tars_fits = list(zip(targets, fitnesses)) if self._store_params: self.parameter_log.append( [(self.parse_individual(x[0]), x[1]) for x in tars_fits]) for ind, fit in tars_fits: ind.fitness.values = (fit,) return
<SYSTEM_TASK:> Creates a static parameter. <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 The mean value of the parameter. val_range : float The minimum and maximum variance from the mean allowed for parameter. """
return cls(label, ParameterType.DYNAMIC, (val_mean, val_range))
<SYSTEM_TASK:> Runs SCWRL on input PDB strong or path to PDB and a sequence string. <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:> Packs sidechains onto a given PDB file or string. <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:> Generates an AMPAL object from the parse tree. <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:> Processes a state into an `Assembly`. <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:> Converts a chain into a `Polymer` type object. <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:> Processes a records into a `Monomer`. <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:> Creates the antisense sequence of a DNA strand. <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:> Creates a DNA duplex from a nucleotide sequence. <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:> Creates a DNA duplex from a start and end point. <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:> Takes a SingleStrandHelix and creates the antisense strand. <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:> Parses rsa file for the total surface accessibility data. <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:> Get three-letter aa code if possible. If not, return None. <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:> Get one-letter version of aa_code if possible. If not, return 'X'. <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:> Get dictionary of information relating to a new amino acid code not currently in the database. <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:> Add an amino acid to the amino_acids.json file used to populate the amino_acid table. <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:> Creates a `CoiledCoil` from a list of `HelicalHelices`. <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:> Creates a `CoiledCoil` from defined super-helical parameters. <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:> Creates a model of a collagen triple helix. <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:> Builds a model of a coiled coil protein using input parameters. <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:> Finds the maximum radius and npnp in the force field. <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:> Dictionary containing PyAtomData structs for the force field. <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:> Runs reduce on a pdb or mmol file at the specified path. <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:> Runs Reduce on a pdb or mmol file and creates a new file with the output. <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:> Generates structure file with protons from a list of structure files. <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:> Returns an Assembly with protons added by Reduce. <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:> Creates a `Helix` between `start` and `end`. <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:> Build straight helix along z-axis, starting with CA1 on x-axis <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:> Creates a `HelicalHelix` between a `start` and `end` point. <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:> Curve of the super helix. <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:> `Primitive` of the super-helical curve. <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:> Rise along super-helical axis per monomer. <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:> Calculates the number of residues per turn of the minor helix. <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:> Rotates each Residue in the Polypeptide. <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:> PseudoGroup containing side_chain centres of each Residue in each Polypeptide in Assembly. <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:> Clusters helices according to the minimum distance between the line segments representing their backbone. <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:> KnobIntoHoles between residues of different chains in assembly. <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:> Assembly containing segments of polypeptide, divided according to separation of contiguous residues. <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:> Generates a reference Primitive for a Polypeptide given start and end coordinates. <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:> Generate KnobGroup from the helices in the assembly - classic socket functionality. <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:> KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff. <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:> Returns MultiDiGraph from kihs. Nodes are helices and edges are kihs. <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:> Get subgraph formed from edges that have max_kh_distance < cutoff. <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:> Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles. <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:> Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self. <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:> Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom. <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:> Maximum distance between knob_end and each of the hole side-chain centres. <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:> Generates configuration setting for required functionality of ISAMBARD. <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:> Creates a `Primitive` from a list of coordinates. <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:> The rise per residue at each point on the Primitive. <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:> Returns the sequence of the `Polynucleotide` as a string. <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:> Uses DSSP to find helices and extracts helices from a pdb file or string. <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:> Uses DSSP to extract solvent accessibilty information on every residue. <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:> Uses DSSP to find alpha-helices and extracts helices from a pdb file. <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:> Uses DSSP to find polyproline helices in a pdb file. <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:> This will offer a step by step guide to create a new run in TestRail, <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:> Determine the machine's memory specifications. <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:> Given a dimension of size 'N', determine the number of rows or columns <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:> Lists all of the Floating IPs available on the account. <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:> Creates a Floating IP and assigns it to a Droplet or reserves it to a region. <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:> Deletes a Floating IP and removes it from the account. <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:> Assigns a Floating IP to a Droplet. <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:> Unassign a Floating IP from a Droplet. <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:> Retrieve a list of all actions that have been executed on a Floating IP. <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:> Return the signature from the signature header or None. <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:> Returns a list of headers fields to sign. <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:> Translate HTTP headers to Django header names. <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:> Build a dict with headers and values used in the signature. <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:> Return the signature for the request. <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:> Assembler of parameters for building request query. <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:> Generates and sends a query to DuckDuckGo API. <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: >>> import duckduckpy >>># Namedtuple is used as a container: >>> response = duckduckpy.query('Python') >>> response Response(redirect=u'', definition=u'', image_width=0, ...} >>> type(response) <class 'duckduckpy.api.Response'> >>> response.related_topics[0] Result(first_url=u'https://duckduckgo.com/Python', text=...) >>> type(response.related_topics[0]) <class 'duckduckpy.api.Result'> >>># Dict is used as a container: >>> response = duckduckpy.query('Python', container='dict') >>> type(response) <type 'dict'> >>> response {u'abstract': u'', u'results': [], u'image_is_logo': 0, ...} >>> type(response['related_topics'][0]) <type 'dict'> >>> response['related_topics'][0] {u'first_url': u'https://duckduckgo.com/Python', u'text': ...} """
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:> Construct a List containing type 'klazz'. <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:> Create a fully reified type from a type schema. <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:> Convert a Python class into a type signature. <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:> Triggers modified event if the given filepath mod time is newer. <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:> Triggers created event if file exists. <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:> Triggers deleted event if the flie doesn't exist. <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:> Logs a messate to a defined io stream if available. <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:> This excludes repository directories because they cause some exceptions <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:> Wrapper to call a list's method from one of the events <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:> Adds the file's modified time into its internal watchlist. <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:> Removes the file from the internal watchlist if exists. <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:> Returns True if the file has been modified since last seen. <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:> Goes into a blocking IO loop. If polling is used, the sleep_time is <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:> Runs the auto tester loop. Internally, the runner instanciates the sniffer_cls and <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:> Runs the program. This is used when you want to run this program standalone. <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:> Sets properties right before calling run. <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:> Hooks into multiple events of a scanner. <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:> Clears console before running the tests. <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:> Runs the unit test framework. Can be overridden to run anything. <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
<SYSTEM_TASK:> Runs the CWD's scent file. <END_TASK> <USER_TASK:> Description: def run(self): """ Runs the CWD's scent file. """
if not self.scent or len(self.scent.runners) == 0: print("Did not find 'scent.py', running nose:") return super(ScentSniffer, self).run() else: print("Using scent:") arguments = [sys.argv[0]] + list(self.test_args) return self.scent.run(arguments) return True
<SYSTEM_TASK:> Bind environment variables into this object's scope. <END_TASK> <USER_TASK:> Description: def bind(self, *args, **kw): """ Bind environment variables into this object's scope. """
new_self = self.copy() new_scopes = Object.translate_to_scopes(*args, **kw) new_self._scopes = tuple(reversed(new_scopes)) + new_self._scopes return new_self
<SYSTEM_TASK:> Unloads all modules that weren't loaded when save_modules was called. <END_TASK> <USER_TASK:> Description: def restore(self): """ Unloads all modules that weren't loaded when save_modules was called. """
sys = set(self._sys_modules.keys()) for mod_name in sys.difference(self._saved_modules): del self._sys_modules[mod_name]
<SYSTEM_TASK:> Interpolate strings. <END_TASK> <USER_TASK:> Description: def join(cls, splits, *namables): """ Interpolate strings. :params splits: The output of Parser.split(string) :params namables: A sequence of Namable objects in which the interpolation should take place. Returns 2-tuple containing: joined string, list of unbound object ids (potentially empty) """
isplits = [] unbound = [] for ref in splits: if isinstance(ref, Ref): resolved = False for namable in namables: try: value = namable.find(ref) resolved = True break except Namable.Error: continue if resolved: isplits.append(value) else: isplits.append(ref) unbound.append(ref) else: isplits.append(ref) return (''.join(map(str if Compatibility.PY3 else unicode, isplits)), unbound)
<SYSTEM_TASK:> Output formatted as list item. <END_TASK> <USER_TASK:> Description: def outitem(title, elems, indent=4): """Output formatted as list item."""
out(title) max_key_len = max(len(key) for key, _ in elems) + 1 for key, val in elems: key_spaced = ('%s:' % key).ljust(max_key_len) out('%s%s %s' % (indent * ' ', key_spaced, val)) out()
<SYSTEM_TASK:> Decorate a Feature method to register it as an output formatter. <END_TASK> <USER_TASK:> Description: def formatter(name, default=False): """Decorate a Feature method to register it as an output formatter. All formatters are picked up by the argument parser so that they can be listed and selected on the CLI via the -f, --format argument. """
def decorator(func): func._output_format = dict(name=name, default=default) return func return decorator
<SYSTEM_TASK:> Load data from sqlite db and return as list of specified objects. <END_TASK> <USER_TASK:> Description: def load_sqlite(self, db, query=None, table=None, cls=None, column_map=None): """Load data from sqlite db and return as list of specified objects."""
if column_map is None: column_map = {} db_path = self.profile_path(db, must_exist=True) def obj_factory(cursor, row): dict_ = {} for idx, col in enumerate(cursor.description): new_name = column_map.get(col[0], col[0]) dict_[new_name] = row[idx] return cls(**dict_) con = sqlite3.connect(str(db_path)) con.row_factory = obj_factory cursor = con.cursor() if not query: columns = [f.name for f in attr.fields(cls)] for k, v in column_map.items(): columns[columns.index(v)] = k query = 'SELECT %s FROM %s' % (','.join(columns), table) cursor.execute(query) while True: item = cursor.fetchone() if item is None: break yield item con.close()
<SYSTEM_TASK:> Load a Mozilla LZ4 file from the user profile. <END_TASK> <USER_TASK:> Description: def load_mozlz4(self, path): """Load a Mozilla LZ4 file from the user profile. Mozilla LZ4 is regular LZ4 with a custom string prefix. """
with open(self.profile_path(path, must_exist=True), 'rb') as f: if f.read(8) != b'mozLz40\0': raise NotMozLz4Error('Not Mozilla LZ4 format.') data = lz4.block.decompress(f.read()) return data