text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Generate data from an npz file. <END_TASK> <USER_TASK:> Description: def npz_generator(npz_path): """Generate data from an npz file."""
npz_data = np.load(npz_path) X = npz_data['X'] # Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,) y = npz_data['Y'] n = X.shape[0] while True: i = np.random.randint(0, n) yield {'X': X[i], 'Y': y[i]}
<SYSTEM_TASK:> Current hypergeometric implementation in scipy is broken, so here's the correct version <END_TASK> <USER_TASK:> Description: def phyper(k, good, bad, N): """ Current hypergeometric implementation in scipy is broken, so here's the correct version """
pvalues = [phyper_single(x, good, bad, N) for x in range(k + 1, N + 1)] return np.sum(pvalues)
<SYSTEM_TASK:> Calculate enrichment based on hypergeometric distribution <END_TASK> <USER_TASK:> Description: def calc_motif_enrichment(sample, background, mtc=None, len_sample=None, len_back=None): """Calculate enrichment based on hypergeometric distribution"""
INF = "Inf" if mtc not in [None, "Bonferroni", "Benjamini-Hochberg", "None"]: raise RuntimeError("Unknown correction: %s" % mtc) sig = {} p_value = {} n_sample = {} n_back = {} if not(len_sample): len_sample = sample.seqn() if not(len_back): len_back = background.seqn() for motif in sample.motifs.keys(): p = "NA" s = "NA" q = len(sample.motifs[motif]) m = 0 if(background.motifs.get(motif)): m = len(background.motifs[motif]) n = len_back - m k = len_sample p = phyper(q - 1, m, n, k) if p != 0: s = -(log(p)/log(10)) else: s = INF else: s = INF p = 0.0 sig[motif] = s p_value[motif] = p n_sample[motif] = q n_back[motif] = m if mtc == "Bonferroni": for motif in p_value.keys(): if p_value[motif] != "NA": p_value[motif] = p_value[motif] * len(p_value.keys()) if p_value[motif] > 1: p_value[motif] = 1 elif mtc == "Benjamini-Hochberg": motifs = sorted(p_value.keys(), key=lambda x: -p_value[x]) l = len(p_value) c = l for m in motifs: if p_value[m] != "NA": p_value[m] = p_value[m] * l / c c -= 1 return (sig, p_value, n_sample, n_back)
<SYSTEM_TASK:> Provide either a file with one cutoff per motif or a single cutoff <END_TASK> <USER_TASK:> Description: def parse_cutoff(motifs, cutoff, default=0.9): """ Provide either a file with one cutoff per motif or a single cutoff returns a hash with motif id as key and cutoff as value """
cutoffs = {} if os.path.isfile(str(cutoff)): for i,line in enumerate(open(cutoff)): if line != "Motif\tScore\tCutoff\n": try: motif,_,c = line.strip().split("\t") c = float(c) cutoffs[motif] = c except Exception as e: sys.stderr.write("Error parsing cutoff file, line {0}: {1}\n".format(e, i + 1)) sys.exit(1) else: for motif in motifs: cutoffs[motif.id] = float(cutoff) for motif in motifs: if not motif.id in cutoffs: sys.stderr.write("No cutoff found for {0}, using default {1}\n".format(motif.id, default)) cutoffs[motif.id] = default return cutoffs
<SYSTEM_TASK:> Detect file type. <END_TASK> <USER_TASK:> Description: def determine_file_type(fname): """ Detect file type. The following file types are supported: BED, narrowPeak, FASTA, list of chr:start-end regions If the extension is bed, fa, fasta or narrowPeak, we will believe this without checking! Parameters ---------- fname : str File name. Returns ------- filetype : str Filename in lower-case. """
if not (isinstance(fname, str) or isinstance(fname, unicode)): raise ValueError("{} is not a file name!", fname) if not os.path.isfile(fname): raise ValueError("{} is not a file!", fname) ext = os.path.splitext(fname)[1].lower() if ext in ["bed"]: return "bed" elif ext in ["fa", "fasta"]: return "fasta" elif ext in ["narrowpeak"]: return "narrowpeak" try: Fasta(fname) return "fasta" except: pass # Read first line that is not a comment or an UCSC-specific line p = re.compile(r'^(#|track|browser)') with open(fname) as f: for line in f.readlines(): line = line.strip() if not p.search(line): break region_p = re.compile(r'^(.+):(\d+)-(\d+)$') if region_p.search(line): return "region" else: vals = line.split("\t") if len(vals) >= 3: try: _, _ = int(vals[1]), int(vals[2]) except ValueError: return "unknown" if len(vals) == 10: try: _, _ = int(vals[4]), int(vals[9]) return "narrowpeak" except ValueError: # As far as I know there is no 10-column BED format return "unknown" pass return "bed" # Catch-all return "unknown"
<SYSTEM_TASK:> Return md5 checksum of file. <END_TASK> <USER_TASK:> Description: def file_checksum(fname): """Return md5 checksum of file. Note: only works for files < 4GB. Parameters ---------- filename : str File used to calculate checksum. Returns ------- checkum : str """
size = os.path.getsize(fname) with open(fname, "r+") as f: checksum = hashlib.md5(mmap.mmap(f.fileno(), size)).hexdigest() return checksum
<SYSTEM_TASK:> Download gene annotation from UCSC based on genomebuild. <END_TASK> <USER_TASK:> Description: def download_annotation(genomebuild, gene_file): """ Download gene annotation from UCSC based on genomebuild. Will check UCSC, Ensembl and RefSeq annotation. Parameters ---------- genomebuild : str UCSC genome name. gene_file : str Output file name. """
pred_bin = "genePredToBed" pred = find_executable(pred_bin) if not pred: sys.stderr.write("{} not found in path!\n".format(pred_bin)) sys.exit(1) tmp = NamedTemporaryFile(delete=False, suffix=".gz") anno = [] f = urlopen(UCSC_GENE_URL.format(genomebuild)) p = re.compile(r'\w+.Gene.txt.gz') for line in f.readlines(): m = p.search(line.decode()) if m: anno.append(m.group(0)) sys.stderr.write("Retrieving gene annotation for {}\n".format(genomebuild)) url = "" for a in ANNOS: if a in anno: url = UCSC_GENE_URL.format(genomebuild) + a break if url: sys.stderr.write("Using {}\n".format(url)) urlretrieve( url, tmp.name ) with gzip.open(tmp.name) as f: cols = f.readline().decode(errors='ignore').split("\t") start_col = 1 for i,col in enumerate(cols): if col == "+" or col == "-": start_col = i - 1 break end_col = start_col + 10 cmd = "zcat {} | cut -f{}-{} | {} /dev/stdin {}" print(cmd.format(tmp.name, start_col, end_col, pred, gene_file)) sp.call(cmd.format( tmp.name, start_col, end_col, pred, gene_file), shell=True) else: sys.stderr.write("No annotation found!")
<SYSTEM_TASK:> Index a single, one-sequence fasta-file <END_TASK> <USER_TASK:> Description: def _make_index(self, fasta, index): """ Index a single, one-sequence fasta-file"""
out = open(index, "wb") f = open(fasta) # Skip first line of fasta-file line = f.readline() offset = f.tell() line = f.readline() while line: out.write(pack(self.pack_char, offset)) offset = f.tell() line = f.readline() f.close() out.close()
<SYSTEM_TASK:> read the param_file, index_dir should already be set <END_TASK> <USER_TASK:> Description: def _read_index_file(self): """read the param_file, index_dir should already be set """
param_file = os.path.join(self.index_dir, self.param_file) with open(param_file) as f: for line in f.readlines(): (name, fasta_file, index_file, line_size, total_size) = line.strip().split("\t") self.size[name] = int(total_size) self.fasta_file[name] = fasta_file self.index_file[name] = index_file self.line_size[name] = int(line_size)
<SYSTEM_TASK:> retrieve a number of lines from a fasta file-object, starting at offset <END_TASK> <USER_TASK:> Description: def _read_seq_from_fasta(self, fasta, offset, nr_lines): """ retrieve a number of lines from a fasta file-object, starting at offset"""
fasta.seek(offset) lines = [fasta.readline().strip() for _ in range(nr_lines)] return "".join(lines)
<SYSTEM_TASK:> Return the sizes of all sequences in the index, or the size of chrom if specified <END_TASK> <USER_TASK:> Description: def get_size(self, chrom=None): """ Return the sizes of all sequences in the index, or the size of chrom if specified as an optional argument """
if len(self.size) == 0: raise LookupError("no chromosomes in index, is the index correct?") if chrom: if chrom in self.size: return self.size[chrom] else: raise KeyError("chromosome {} not in index".format(chrom)) total = 0 for size in self.size.values(): total += size return total
<SYSTEM_TASK:> Returns an instance of a specific tool. <END_TASK> <USER_TASK:> Description: def get_tool(name): """ Returns an instance of a specific tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram instance """
tool = name.lower() if tool not in __tools__: raise ValueError("Tool {0} not found!\n".format(name)) t = __tools__[tool]() if not t.is_installed(): sys.stderr.write("Tool {0} not installed!\n".format(tool)) if not t.is_configured(): sys.stderr.write("Tool {0} not configured!\n".format(tool)) return t
<SYSTEM_TASK:> Returns the binary of a tool. <END_TASK> <USER_TASK:> Description: def locate_tool(name, verbose=True): """ Returns the binary of a tool. Parameters ---------- name : str Name of the tool (case-insensitive). Returns ------- tool_bin : str Binary of tool. """
m = get_tool(name) tool_bin = which(m.cmd) if tool_bin: if verbose: print("Found {} in {}".format(m.name, tool_bin)) return tool_bin else: print("Couldn't find {}".format(m.name))
<SYSTEM_TASK:> Get the command used to run the tool. <END_TASK> <USER_TASK:> Description: def bin(self): """ Get the command used to run the tool. Returns ------- command : str The tool system command. """
if self.local_bin: return self.local_bin else: return self.config.bin(self.name)
<SYSTEM_TASK:> Run the tool and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def run(self, fastafile, params=None, tmp=None): """ Run the tool and predict motifs from a FASTA file. Parameters ---------- fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. tmp : str, optional Directory to use for creation of temporary files. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
if not self.is_configured(): raise ValueError("%s is not configured" % self.name) if not self.is_installed(): raise ValueError("%s is not installed or not correctly configured" % self.name) self.tmpdir = mkdtemp(prefix="{0}.".format(self.name), dir=tmp) fastafile = os.path.abspath(fastafile) try: return self._run_program(self.bin(), fastafile, params) except KeyboardInterrupt: return ([], "Killed", "Killed")
<SYSTEM_TASK:> Run XXmotif and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run XXmotif and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) outfile = os.path.join( self.tmpdir, os.path.basename(fastafile.replace(".fa", ".pwm"))) stdout = "" stderr = "" cmd = "%s %s %s --localization --batch %s %s" % ( bin, self.tmpdir, fastafile, params["background"], params["strand"], ) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out,err = p.communicate() stdout += out.decode() stderr += err.decode() motifs = [] if os.path.exists(outfile): motifs = read_motifs(outfile, fmt="xxmotif") for m in motifs: m.id = "{0}_{1}".format(self.name, m.id) else: stdout += "\nMotif file {0} not found!\n".format(outfile) stderr += "\nMotif file {0} not found!\n".format(outfile) return motifs, stdout, stderr
<SYSTEM_TASK:> Run Homer and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run Homer and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) outfile = NamedTemporaryFile( mode="w", dir=self.tmpdir, prefix= "homer_w{}.".format(params["width"]) ).name cmd = "%s denovo -i %s -b %s -len %s -S %s %s -o %s -p 8" % ( bin, fastafile, params["background"], params["width"], params["number"], params["strand"], outfile) stderr = "" stdout = "Running command:\n{}\n".format(cmd) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.tmpdir) out,err = p.communicate() stdout += out.decode() stderr += err.decode() motifs = [] if os.path.exists(outfile): motifs = read_motifs(outfile, fmt="pwm") for i, m in enumerate(motifs): m.id = "{}_{}_{}".format(self.name, params["width"], i + 1) return motifs, stdout, stderr
<SYSTEM_TASK:> Run HMS and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run HMS and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) default_params = {"width":10} if params is not None: default_params.update(params) fgfile, summitfile, outfile = self._prepare_files(fastafile) current_path = os.getcwd() os.chdir(self.tmpdir) cmd = "{} -i {} -w {} -dna 4 -iteration 50 -chain 20 -seqprop -0.1 -strand 2 -peaklocation {} -t_dof 3 -dep 2".format( bin, fgfile, params['width'], summitfile) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout,stderr = p.communicate() os.chdir(current_path) motifs = [] if os.path.exists(outfile): with open(outfile) as f: motifs = self.parse(f) for i,m in enumerate(motifs): m.id = "HMS_w{}_{}".format(params['width'], i + 1) return motifs, stdout, stderr
<SYSTEM_TASK:> Run AMD and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run AMD and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) fgfile = os.path.join(self.tmpdir, "AMD.in.fa") outfile = fgfile + ".Matrix" shutil.copy(fastafile, fgfile) current_path = os.getcwd() os.chdir(self.tmpdir) stdout = "" stderr = "" cmd = "%s -F %s -B %s" % ( bin, fgfile, params["background"], ) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out,err = p.communicate() stdout += out.decode() stderr += err.decode() os.chdir(current_path) motifs = [] if os.path.exists(outfile): f = open(outfile) motifs = self.parse(f) f.close() return motifs, stdout, stderr
<SYSTEM_TASK:> Run Trawler and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run Trawler and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) tmp = NamedTemporaryFile(mode="w", dir=self.tmpdir, delete=False) shutil.copy(fastafile, tmp.name) fastafile = tmp.name current_path = os.getcwd() os.chdir(self.dir()) motifs = [] stdout = "" stderr = "" for wildcard in [0,1,2]: cmd = "%s -sample %s -background %s -directory %s -strand %s -wildcard %s" % ( bin, fastafile, params["background"], self.tmpdir, params["strand"], wildcard, ) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out,err = p.communicate() stdout += out.decode() stderr += err.decode() os.chdir(current_path) pwmfiles = glob.glob("{}/tmp*/result/*pwm".format(self.tmpdir)) if len(pwmfiles) > 0: out_file = pwmfiles[0] stdout += "\nOutfile: {}".format(out_file) my_motifs = [] if os.path.exists(out_file): my_motifs = read_motifs(out_file, fmt="pwm") for m in motifs: m.id = "{}_{}".format(self.name, m.id) stdout += "\nTrawler: {} motifs".format(len(motifs)) # remove temporary files if os.path.exists(tmp.name): os.unlink(tmp.name) for motif in my_motifs: motif.id = "{}_{}_{}".format(self.name, wildcard, motif.id) motifs += my_motifs else: stderr += "\nNo outfile found" return motifs, stdout, stderr
<SYSTEM_TASK:> Run Weeder and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin,fastafile, params=None): """ Run Weeder and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) organism = params["organism"] weeder_organisms = { "hg18":"HS", "hg19":"HS", "hg38":"HS", "mm9":"MM", "mm10":"MM", "dm3":"DM", "dm5":"DM", "dm6":"DM", "yeast":"SC", "sacCer2":"SC", "sacCer3":"SC", "TAIR10":"AT", "TAIR11":"AT", } weeder_organism = weeder_organisms.get(organism, "HS") tmp = NamedTemporaryFile(dir=self.tmpdir) name = tmp.name tmp.close() shutil.copy(fastafile, name) fastafile = name cmd = "{} -f {} -O".format( self.cmd, fastafile, weeder_organism, ) if params["single"]: cmd += " -ss" #print cmd stdout, stderr = "", "" p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.tmpdir) out,err = p.communicate() stdout += out.decode() stderr += err.decode() motifs = [] if os.path.exists(fastafile + ".matrix.w2"): f = open(fastafile + ".matrix.w2") motifs = self.parse(f) f.close() for m in motifs: m.id = "{}_{}".format(self.name, m.id.split("\t")[0]) for ext in [".w2", ".matrix.w2" ]: if os.path.exists(fastafile + ext): os.unlink(fastafile + ext) return motifs, stdout, stderr
<SYSTEM_TASK:> Run MotifSampler and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run MotifSampler and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) # TODO: test organism #cmd = "%s -f %s -b %s -m %s -w %s -n %s -o %s -s %s > /dev/null 2>&1" % ( cmd = "%s -f %s -b %s -m %s -w %s -n %s -o %s -s %s" % ( bin, fastafile, params["background_model"], params["pwmfile"], params["width"], params["number"], params["outfile"], params["strand"], ) #print cmd p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() #stdout,stderr = "","" #p = Popen(cmd, shell=True) #p.wait() motifs = [] if os.path.exists(params["outfile"]): with open(params["outfile"]) as f: motifs = self.parse_out(f) for motif in motifs: motif.id = "%s_%s" % (self.name, motif.id) return motifs, stdout, stderr
<SYSTEM_TASK:> Run MDmodule and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run MDmodule and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
default_params = {"width":10, "number":10} if params is not None: default_params.update(params) new_file = os.path.join(self.tmpdir, "mdmodule_in.fa") shutil.copy(fastafile, new_file) fastafile = new_file pwmfile = fastafile + ".out" width = default_params['width'] number = default_params['number'] current_path = os.getcwd() os.chdir(self.tmpdir) cmd = "%s -i %s -a 1 -o %s -w %s -t 100 -r %s" % (bin, fastafile, pwmfile, width, number) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout,stderr = p.communicate() stdout = "cmd: {}\n".format(cmd) + stdout.decode() motifs = [] if os.path.exists(pwmfile): with open(pwmfile) as f: motifs = self.parse(f) os.chdir(current_path) for motif in motifs: motif.id = "%s_%s" % (self.name, motif.id) return motifs, stdout, stderr
<SYSTEM_TASK:> Run ChIPMunk and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run ChIPMunk and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
params = self._parse_params(params) basename = "munk_in.fa" new_file = os.path.join(self.tmpdir, basename) out = open(new_file, "w") f = Fasta(fastafile) for seq in f.seqs: header = len(seq) // 2 out.write(">%s\n" % header) out.write("%s\n" % seq) out.close() fastafile = new_file outfile = fastafile + ".out" current_path = os.getcwd() os.chdir(self.dir()) motifs = [] # Max recommended by ChIPMunk userguide ncpus = 4 stdout = "" stderr = "" for zoops_factor in ["oops", 0.0, 0.5, 1.0]: cmd = "{} {} {} y {} m:{} 100 10 1 {} 1>{}".format( bin, params.get("width", 8), params.get("width", 20), zoops_factor, fastafile, ncpus, outfile ) #print("command: ", cmd) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) std = p.communicate() stdout = stdout + std[0].decode() stderr = stderr + std[1].decode() if "RuntimeException" in stderr: return [], stdout, stderr if os.path.exists(outfile): with open(outfile) as f: motifs += self.parse(f) os.chdir(current_path) return motifs, stdout, stderr
<SYSTEM_TASK:> Run Posmo and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run Posmo and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
default_params = {} if params is not None: default_params.update(params) width = params.get("width", 8) basename = "posmo_in.fa" new_file = os.path.join(self.tmpdir, basename) shutil.copy(fastafile, new_file) fastafile = new_file #pwmfile = fastafile + ".pwm" motifs = [] current_path = os.getcwd() os.chdir(self.tmpdir) for n_ones in range(4, min(width, 11), 2): x = "1" * n_ones outfile = "%s.%s.out" % (fastafile, x) cmd = "%s 5000 %s %s 1.6 2.5 %s 200" % (bin, x, fastafile, width) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() stdout = stdout.decode() stderr = stderr.decode() context_file = fastafile.replace(basename, "context.%s.%s.txt" % (basename, x)) cmd = "%s %s %s simi.txt 0.88 10 2 10" % (bin.replace("posmo","clusterwd"), context_file, outfile) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out, err = p.communicate() stdout += out.decode() stderr += err.decode() if os.path.exists(outfile): with open(outfile) as f: motifs += self.parse(f, width, n_ones) os.chdir(current_path) return motifs, stdout, stderr
<SYSTEM_TASK:> Get enriched JASPAR motifs in a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Get enriched JASPAR motifs in a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
fname = os.path.join(self.config.get_motif_dir(), "JASPAR2010_vertebrate.pwm") motifs = read_motifs(fname, fmt="pwm") for motif in motifs: motif.id = "JASPAR_%s" % motif.id return motifs, "", ""
<SYSTEM_TASK:> Run MEME and predict motifs from a FASTA file. <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run MEME and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools required parameters are passed using this dictionary. Returns ------- motifs : list of Motif instances The predicted motifs. stdout : str Standard out of the tool. stderr : str Standard error of the tool. """
default_params = {"width":10, "single":False, "number":10} if params is not None: default_params.update(params) tmp = NamedTemporaryFile(dir=self.tmpdir) tmpname = tmp.name strand = "-revcomp" width = default_params["width"] number = default_params["number"] cmd = [bin, fastafile, "-text","-dna","-nostatus","-mod", "zoops","-nmotifs", "%s" % number, "-w","%s" % width, "-maxsize", "10000000"] if not default_params["single"]: cmd.append(strand) #sys.stderr.write(" ".join(cmd) + "\n") p = Popen(cmd, bufsize=1, stderr=PIPE, stdout=PIPE) stdout,stderr = p.communicate() motifs = [] motifs = self.parse(io.StringIO(stdout.decode())) # Delete temporary files tmp.close() return motifs, stdout, stderr
<SYSTEM_TASK:> Scan regions in input table with motifs. <END_TASK> <USER_TASK:> Description: def scan_to_table(input_table, genome, scoring, pwmfile=None, ncpus=None): """Scan regions in input table with motifs. Parameters ---------- input_table : str Filename of input table. Can be either a text-separated tab file or a feather file. genome : str Genome name. Can be either the name of a FASTA-formatted file or a genomepy genome name. scoring : str "count" or "score" pwmfile : str, optional Specify a PFM file for scanning. ncpus : int, optional If defined this specifies the number of cores to use. Returns ------- table : pandas.DataFrame DataFrame with motif ids as column names and regions as index. Values are either counts or scores depending on the 'scoring' parameter.s """
config = MotifConfig() if pwmfile is None: pwmfile = config.get_default_params().get("motif_db", None) if pwmfile is not None: pwmfile = os.path.join(config.get_motif_dir(), pwmfile) if pwmfile is None: raise ValueError("no pwmfile given and no default database specified") logger.info("reading table") if input_table.endswith("feather"): df = pd.read_feather(input_table) idx = df.iloc[:,0].values else: df = pd.read_table(input_table, index_col=0, comment="#") idx = df.index regions = list(idx) s = Scanner(ncpus=ncpus) s.set_motifs(pwmfile) s.set_genome(genome) s.set_background(genome=genome) nregions = len(regions) scores = [] if scoring == "count": logger.info("setting threshold") s.set_threshold(fpr=FPR) logger.info("creating count table") for row in s.count(regions): scores.append(row) logger.info("done") else: s.set_threshold(threshold=0.0) logger.info("creating score table") for row in s.best_score(regions, normalize=True): scores.append(row) logger.info("done") motif_names = [m.id for m in read_motifs(pwmfile)] logger.info("creating dataframe") return pd.DataFrame(scores, index=idx, columns=motif_names)
<SYSTEM_TASK:> Converts arguments extracted from a parser to a dict, <END_TASK> <USER_TASK:> Description: def get_args(parser): """ Converts arguments extracted from a parser to a dict, and will dismiss arguments which default to NOT_SET. :param parser: an ``argparse.ArgumentParser`` instance. :type parser: argparse.ArgumentParser :return: Dictionary with the configs found in the parsed CLI arguments. :rtype: dict """
args = vars(parser.parse_args()).items() return {key: val for key, val in args if not isinstance(val, NotSet)}
<SYSTEM_TASK:> Buffered read from socket. Reads all data available from socket. <END_TASK> <USER_TASK:> Description: def socket_read(fp): """Buffered read from socket. Reads all data available from socket. @fp: File pointer for socket. @return: String of characters read from buffer. """
response = '' oldlen = 0 newlen = 0 while True: response += fp.read(buffSize) newlen = len(response) if newlen - oldlen == 0: break else: oldlen = newlen return response
<SYSTEM_TASK:> Convenience function that executes command and returns result. <END_TASK> <USER_TASK:> Description: def exec_command(args, env=None): """Convenience function that executes command and returns result. @param args: Tuple of command and arguments. @param env: Dictionary of environment variables. (Environment is not modified if None.) @return: Command output. """
try: cmd = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=buffSize, env=env) except OSError, e: raise Exception("Execution of command failed.\n", " Command: %s\n Error: %s" % (' '.join(args), str(e))) out, err = cmd.communicate(None) if cmd.returncode != 0: raise Exception("Execution of command failed with error code: %s\n%s\n" % (cmd.returncode, err)) return out
<SYSTEM_TASK:> Register filter on a column of table. <END_TASK> <USER_TASK:> Description: def registerFilter(self, column, patterns, is_regex=False, ignore_case=False): """Register filter on a column of table. @param column: The column name. @param patterns: A single pattern or a list of patterns used for matching column values. @param is_regex: The patterns will be treated as regex if True, the column values will be tested for equality with the patterns otherwise. @param ignore_case: Case insensitive matching will be used if True. """
if isinstance(patterns, basestring): patt_list = (patterns,) elif isinstance(patterns, (tuple, list)): patt_list = list(patterns) else: raise ValueError("The patterns parameter must either be as string " "or a tuple / list of strings.") if is_regex: if ignore_case: flags = re.IGNORECASE else: flags = 0 patt_exprs = [re.compile(pattern, flags) for pattern in patt_list] else: if ignore_case: patt_exprs = [pattern.lower() for pattern in patt_list] else: patt_exprs = patt_list self._filters[column] = (patt_exprs, is_regex, ignore_case)
<SYSTEM_TASK:> Unregister filter on a column of the table. <END_TASK> <USER_TASK:> Description: def unregisterFilter(self, column): """Unregister filter on a column of the table. @param column: The column header. """
if self._filters.has_key(column): del self._filters[column]
<SYSTEM_TASK:> Register multiple filters at once. <END_TASK> <USER_TASK:> Description: def registerFilters(self, **kwargs): """Register multiple filters at once. @param **kwargs: Multiple filters are registered using keyword variables. Each keyword must correspond to a field name with an optional suffix: field: Field equal to value or in list of values. field_ic: Field equal to value or in list of values, using case insensitive comparison. field_regex: Field matches regex value or matches with any regex in list of values. field_ic_regex: Field matches regex value or matches with any regex in list of values using case insensitive match. """
for (key, patterns) in kwargs.items(): if key.endswith('_regex'): col = key[:-len('_regex')] is_regex = True else: col = key is_regex = False if col.endswith('_ic'): col = col[:-len('_ic')] ignore_case = True else: ignore_case = False self.registerFilter(col, patterns, is_regex, ignore_case)
<SYSTEM_TASK:> Apply filter on ps command result. <END_TASK> <USER_TASK:> Description: def applyFilters(self, headers, table): """Apply filter on ps command result. @param headers: List of column headers. @param table: Nested list of rows and columns. @return: Nested list of rows and columns filtered using registered filters. """
result = [] column_idxs = {} for column in self._filters.keys(): try: column_idxs[column] = headers.index(column) except ValueError: raise ValueError('Invalid column name %s in filter.' % column) for row in table: for (column, (patterns, is_regex, ignore_case)) in self._filters.items(): col_idx = column_idxs[column] col_val = row[col_idx] if is_regex: for pattern in patterns: if pattern.search(col_val): break else: break else: if ignore_case: col_val = col_val.lower() if col_val in patterns: pass else: break else: result.append(row) return result
<SYSTEM_TASK:> Calculate the autocorrelation function for a 1D time series. <END_TASK> <USER_TASK:> Description: def function(data, maxt=None): """ Calculate the autocorrelation function for a 1D time series. Parameters ---------- data : numpy.ndarray (N,) The time series. Returns ------- rho : numpy.ndarray (N,) An autocorrelation function. """
data = np.atleast_1d(data) assert len(np.shape(data)) == 1, \ "The autocorrelation function can only by computed " \ + "on a 1D time series." if maxt is None: maxt = len(data) result = np.zeros(maxt, dtype=float) _acor.function(np.array(data, dtype=float), result) return result / result[0]
<SYSTEM_TASK:> Computes clustering along a set of feature dimensions <END_TASK> <USER_TASK:> Description: def fingerprint_helper(egg, permute=False, n_perms=1000, match='exact', distance='euclidean', features=None): """ Computes clustering along a set of feature dimensions Parameters ---------- egg : quail.Egg Data to analyze dist_funcs : dict Dictionary of distance functions for feature clustering analyses Returns ---------- probabilities : Numpy array Each number represents clustering along a different feature dimension """
if features is None: features = egg.dist_funcs.keys() inds = egg.pres.index.tolist() slices = [egg.crack(subjects=[i], lists=[j]) for i, j in inds] weights = _get_weights(slices, features, distdict, permute, n_perms, match, distance) return np.nanmean(weights, axis=0)
<SYSTEM_TASK:> Searches os.environ. If a key is found try evaluating its type else; <END_TASK> <USER_TASK:> Description: def get(key, default=None): """ Searches os.environ. If a key is found try evaluating its type else; return the string. returns: k->value (type as defined by ast.literal_eval) """
try: # Attempt to evaluate into python literal return ast.literal_eval(os.environ.get(key.upper(), default)) except (ValueError, SyntaxError): return os.environ.get(key.upper(), default)
<SYSTEM_TASK:> Saves a list of keyword arguments as environment variables to a file. <END_TASK> <USER_TASK:> Description: def save(filepath=None, **kwargs): """ Saves a list of keyword arguments as environment variables to a file. If no filepath given will default to the default `.env` file. """
if filepath is None: filepath = os.path.join('.env') with open(filepath, 'wb') as file_handle: file_handle.writelines( '{0}={1}\n'.format(key.upper(), val) for key, val in kwargs.items() )
<SYSTEM_TASK:> Reads a .env file into os.environ. <END_TASK> <USER_TASK:> Description: def load(filepath=None): """ Reads a .env file into os.environ. For a set filepath, open the file and read contents into os.environ. If filepath is not set then look in current dir for a .env file. """
if filepath and os.path.exists(filepath): pass else: if not os.path.exists('.env'): return False filepath = os.path.join('.env') for key, value in _get_line_(filepath): # set the key, value in the python environment vars dictionary # does not make modifications system wide. os.environ.setdefault(key, str(value)) return True
<SYSTEM_TASK:> Returns a df of features for presented items <END_TASK> <USER_TASK:> Description: def get_pres_features(self, features=None): """ Returns a df of features for presented items """
if features is None: features = self.dist_funcs.keys() elif not isinstance(features, list): features = [features] return self.pres.applymap(lambda x: {k:v for k,v in x.items() if k in features} if x is not None else None)
<SYSTEM_TASK:> Returns a df of features for recalled items <END_TASK> <USER_TASK:> Description: def get_rec_features(self, features=None): """ Returns a df of features for recalled items """
if features is None: features = self.dist_funcs.keys() elif not isinstance(features, list): features = [features] return self.rec.applymap(lambda x: {k:v for k,v in x.items() if k != 'item'} if x is not None else None)
<SYSTEM_TASK:> Print info about the data egg <END_TASK> <USER_TASK:> Description: def info(self): """ Print info about the data egg """
print('Number of subjects: ' + str(self.n_subjects)) print('Number of lists per subject: ' + str(self.n_lists)) print('Number of words per list: ' + str(self.list_length)) print('Date created: ' + str(self.date_created)) print('Meta data: ' + str(self.meta))
<SYSTEM_TASK:> Save method for the Egg object <END_TASK> <USER_TASK:> Description: def save(self, fname, compression='blosc'): """ Save method for the Egg object The data will be saved as a 'egg' file, which is a dictionary containing the elements of a Egg saved in the hd5 format using `deepdish`. Parameters ---------- fname : str A name for the file. If the file extension (.egg) is not specified, it will be appended. compression : str The kind of compression to use. See the deepdish documentation for options: http://deepdish.readthedocs.io/en/latest/api_io.html#deepdish.io.save """
# put egg vars into a dict egg = { 'pres' : df2list(self.pres), 'rec' : df2list(self.rec), 'dist_funcs' : self.dist_funcs, 'subjgroup' : self.subjgroup, 'subjname' : self.subjname, 'listgroup' : self.listgroup, 'listname' : self.listname, 'date_created' : self.date_created, 'meta' : self.meta } # if extension wasn't included, add it if fname[-4:]!='.egg': fname+='.egg' # save with warnings.catch_warnings(): warnings.simplefilter("ignore") dd.io.save(fname, egg, compression=compression)
<SYSTEM_TASK:> Save method for the FriedEgg object <END_TASK> <USER_TASK:> Description: def save(self, fname, compression='blosc'): """ Save method for the FriedEgg object The data will be saved as a 'fegg' file, which is a dictionary containing the elements of a FriedEgg saved in the hd5 format using `deepdish`. Parameters ---------- fname : str A name for the file. If the file extension (.fegg) is not specified, it will be appended. compression : str The kind of compression to use. See the deepdish documentation for options: http://deepdish.readthedocs.io/en/latest/api_io.html#deepdish.io.save """
egg = { 'data' : self.data, 'analysis' : self.analysis, 'list_length' : self.list_length, 'n_lists' : self.n_lists, 'n_subjects' : self.n_subjects, 'position' : self.position, 'date_created' : self.date_created, 'meta' : self.meta } if fname[-4:]!='.fegg': fname+='.fegg' with warnings.catch_warnings(): warnings.simplefilter("ignore") dd.io.save(fname, egg, compression=compression)
<SYSTEM_TASK:> Solution of system of linear equation using the Numeric object. <END_TASK> <USER_TASK:> Description: def solve(self, sys, mtx, rhs, autoTranspose=False): """ Solution of system of linear equation using the Numeric object. Parameters ---------- sys : constant one of UMFPACK system description constants, like UMFPACK_A, UMFPACK_At, see umfSys list and UMFPACK docs mtx : scipy.sparse.csc_matrix or scipy.sparse.csr_matrix Input. rhs : ndarray Right Hand Side autoTranspose : bool Automatically changes `sys` to the transposed type, if `mtx` is in CSR, since UMFPACK assumes CSC internally Returns ------- sol : ndarray Solution to the equation system. """
if sys not in umfSys: raise ValueError('sys must be in' % umfSys) if autoTranspose and self.isCSR: ## # UMFPACK uses CSC internally... if self.family in umfRealTypes: ii = 0 else: ii = 1 if sys in umfSys_transposeMap[ii]: sys = umfSys_transposeMap[ii][sys] else: raise RuntimeError('autoTranspose ambiguous, switch it off') if self._numeric is not None: if self.mtx is not mtx: raise ValueError('must be called with same matrix as numeric()') else: raise RuntimeError('numeric() not called') indx = self._getIndx(mtx) if self.isReal: rhs = rhs.astype(np.float64) sol = np.zeros((mtx.shape[1],), dtype=np.float64) status = self.funs.solve(sys, mtx.indptr, indx, mtx.data, sol, rhs, self._numeric, self.control, self.info) else: rhs = rhs.astype(np.complex128) sol = np.zeros((mtx.shape[1],), dtype=np.complex128) mreal, mimag = mtx.data.real.copy(), mtx.data.imag.copy() sreal, simag = sol.real.copy(), sol.imag.copy() rreal, rimag = rhs.real.copy(), rhs.imag.copy() status = self.funs.solve(sys, mtx.indptr, indx, mreal, mimag, sreal, simag, rreal, rimag, self._numeric, self.control, self.info) sol.real, sol.imag = sreal, simag # self.funs.report_info( self.control, self.info ) # pause() if status != UMFPACK_OK: if status == UMFPACK_WARNING_singular_matrix: ## Change inf, nan to zeros. warnings.warn('Zeroing nan and inf entries...', UmfpackWarning) sol[~np.isfinite(sol)] = 0.0 else: raise RuntimeError('%s failed with %s' % (self.funs.solve, umfStatus[status])) econd = 1.0 / self.info[UMFPACK_RCOND] if econd > self.maxCond: msg = '(almost) singular matrix! '\ + '(estimated cond. number: %.2e)' % econd warnings.warn(msg, UmfpackWarning) return sol
<SYSTEM_TASK:> One-shot solution of system of linear equation. Reuses Numeric object <END_TASK> <USER_TASK:> Description: def linsolve(self, sys, mtx, rhs, autoTranspose=False): """ One-shot solution of system of linear equation. Reuses Numeric object if possible. Parameters ---------- sys : constant one of UMFPACK system description constants, like UMFPACK_A, UMFPACK_At, see umfSys list and UMFPACK docs mtx : scipy.sparse.csc_matrix or scipy.sparse.csr_matrix Input. rhs : ndarray Right Hand Side autoTranspose : bool Automatically changes `sys` to the transposed type, if `mtx` is in CSR, since UMFPACK assumes CSC internally Returns ------- sol : ndarray Solution to the equation system. """
if sys not in umfSys: raise ValueError('sys must be in' % umfSys) if self._numeric is None: self.numeric(mtx) else: if self.mtx is not mtx: self.numeric(mtx) sol = self.solve(sys, mtx, rhs, autoTranspose) self.free_numeric() return sol
<SYSTEM_TASK:> Computes weights for one reordering using stick-breaking method <END_TASK> <USER_TASK:> Description: def stick_perm(presenter, egg, dist_dict, strategy): """Computes weights for one reordering using stick-breaking method"""
# seed RNG np.random.seed() # unpack egg egg_pres, egg_rec, egg_features, egg_dist_funcs = parse_egg(egg) # reorder regg = order_stick(presenter, egg, dist_dict, strategy) # unpack regg regg_pres, regg_rec, regg_features, regg_dist_funcs = parse_egg(regg) # # get the order regg_pres = list(regg_pres) egg_pres = list(egg_pres) idx = [egg_pres.index(r) for r in regg_pres] # compute weights weights = compute_feature_weights_dict(list(regg_pres), list(regg_pres), list(regg_features), dist_dict) # save out the order orders = idx return weights, orders
<SYSTEM_TASK:> Creates a nested dict of distances <END_TASK> <USER_TASK:> Description: def compute_distances_dict(egg): """ Creates a nested dict of distances """
pres, rec, features, dist_funcs = parse_egg(egg) pres_list = list(pres) features_list = list(features) # initialize dist dict distances = {} # for each word in the list for idx1, item1 in enumerate(pres_list): distances[item1]={} # for each word in the list for idx2, item2 in enumerate(pres_list): distances[item1][item2]={} # for each feature in dist_funcs for feature in dist_funcs: distances[item1][item2][feature] = builtin_dist_funcs[dist_funcs[feature]](features_list[idx1][feature],features_list[idx2][feature]) return distances
<SYSTEM_TASK:> Return major and minor device number for block device path devpath. <END_TASK> <USER_TASK:> Description: def _getDevMajorMinor(self, devpath): """Return major and minor device number for block device path devpath. @param devpath: Full path for block device. @return: Tuple (major, minor). """
fstat = os.stat(devpath) if stat.S_ISBLK(fstat.st_mode): return(os.major(fstat.st_rdev), os.minor(fstat.st_rdev)) else: raise ValueError("The file %s is not a valid block device." % devpath)
<SYSTEM_TASK:> Return unique device for any block device path. <END_TASK> <USER_TASK:> Description: def _getUniqueDev(self, devpath): """Return unique device for any block device path. @param devpath: Full path for block device. @return: Unique device string without the /dev prefix. """
realpath = os.path.realpath(devpath) mobj = re.match('\/dev\/(.*)$', realpath) if mobj: dev = mobj.group(1) if dev in self._diskStats: return dev else: try: (major, minor) = self._getDevMajorMinor(realpath) except: return None return self._mapMajorMinor2dev.get((major, minor)) return None
<SYSTEM_TASK:> Initialize filesystem to device mappings. <END_TASK> <USER_TASK:> Description: def _initFilesystemInfo(self): """Initialize filesystem to device mappings."""
self._mapFSpathDev = {} fsinfo = FilesystemInfo() for fs in fsinfo.getFSlist(): devpath = fsinfo.getFSdev(fs) dev = self._getUniqueDev(devpath) if dev is not None: self._mapFSpathDev[fs] = dev
<SYSTEM_TASK:> Initialize swap partition to device mappings. <END_TASK> <USER_TASK:> Description: def _initSwapInfo(self): """Initialize swap partition to device mappings."""
self._swapList = [] sysinfo = SystemInfo() for (swap,attrs) in sysinfo.getSwapStats().iteritems(): if attrs['type'] == 'partition': dev = self._getUniqueDev(swap) if dev is not None: self._swapList.append(dev)
<SYSTEM_TASK:> Sort block devices into lists depending on device class and <END_TASK> <USER_TASK:> Description: def _initDevClasses(self): """Sort block devices into lists depending on device class and initialize device type map and partition map."""
self._devClassTree = {} self._partitionTree = {} self._mapDevType = {} basedevs = [] otherdevs = [] if self._mapMajorDevclass is None: self._initBlockMajorMap() for dev in self._diskStats: stats = self._diskStats[dev] devclass = self._mapMajorDevclass.get(stats['major']) if devclass is not None: devdir = os.path.join(sysfsBlockdevDir, dev) if os.path.isdir(devdir): if not self._devClassTree.has_key(devclass): self._devClassTree[devclass] = [] self._devClassTree[devclass].append(dev) self._mapDevType[dev] = devclass basedevs.append(dev) else: otherdevs.append(dev) basedevs.sort(key=len, reverse=True) otherdevs.sort(key=len, reverse=True) idx = 0 for partdev in otherdevs: while len(basedevs[idx]) > partdev: idx += 1 for dev in basedevs[idx:]: if re.match("%s(\d+|p\d+)$" % dev, partdev): if not self._partitionTree.has_key(dev): self._partitionTree[dev] = [] self._partitionTree[dev].append(partdev) self._mapDevType[partdev] = 'part'
<SYSTEM_TASK:> Returns Rackspace Cloud Files usage stats for containers. <END_TASK> <USER_TASK:> Description: def getContainerStats(self, limit=None, marker=None): """Returns Rackspace Cloud Files usage stats for containers. @param limit: Number of containers to return. @param marker: Return only results whose name is greater than marker. @return: Dictionary of container stats indexed by container name. """
stats = {} for row in self._conn.list_containers_info(limit, marker): stats[row['name']] = {'count': row['count'], 'size': row['bytes']} return stats
<SYSTEM_TASK:> Connect to Squid Proxy Manager interface. <END_TASK> <USER_TASK:> Description: def _connect(self): """Connect to Squid Proxy Manager interface."""
if sys.version_info[:2] < (2,6): self._conn = httplib.HTTPConnection(self._host, self._port) else: self._conn = httplib.HTTPConnection(self._host, self._port, False, defaultTimeout)
<SYSTEM_TASK:> Parse simple stats list of key, value pairs. <END_TASK> <USER_TASK:> Description: def _parseCounters(self, data): """Parse simple stats list of key, value pairs. @param data: Multiline data with one key-value pair in each line. @return: Dictionary of stats. """
info_dict = util.NestedDict() for line in data.splitlines(): mobj = re.match('^\s*([\w\.]+)\s*=\s*(\S.*)$', line) if mobj: (key, value) = mobj.groups() klist = key.split('.') info_dict.set_nested(klist, parse_value(value)) return info_dict
<SYSTEM_TASK:> Parse data and separate sections. Returns dictionary that maps <END_TASK> <USER_TASK:> Description: def _parseSections(self, data): """Parse data and separate sections. Returns dictionary that maps section name to section data. @param data: Multiline data. @return: Dictionary that maps section names to section data. """
section_dict = {} lines = data.splitlines() idx = 0 numlines = len(lines) section = None while idx < numlines: line = lines[idx] idx += 1 mobj = re.match('^(\w[\w\s\(\)]+[\w\)])\s*:$', line) if mobj: section = mobj.group(1) section_dict[section] = [] else: mobj = re.match('(\t|\s)\s*(\w.*)$', line) if mobj: section_dict[section].append(mobj.group(2)) else: mobj = re.match('^(\w[\w\s\(\)]+[\w\)])\s*:\s*(\S.*)$', line) if mobj: section = None if not section_dict.has_key(section): section_dict[section] = [] section_dict[section].append(line) else: if not section_dict.has_key('PARSEERROR'): section_dict['PARSEERROR'] = [] section_dict['PARSEERROR'].append(line) return section_dict
<SYSTEM_TASK:> Get manager interface section list from Squid Proxy Server <END_TASK> <USER_TASK:> Description: def getMenu(self): """Get manager interface section list from Squid Proxy Server @return: List of tuples (section, description, type) """
data = self._retrieve('') info_list = [] for line in data.splitlines(): mobj = re.match('^\s*(\S.*\S)\s*\t\s*(\S.*\S)\s*\t\s*(\S.*\S)$', line) if mobj: info_list.append(mobj.groups()) return info_list
<SYSTEM_TASK:> Return dictionary of Traffic Stats for each Wanpipe Interface. <END_TASK> <USER_TASK:> Description: def getIfaceStats(self): """Return dictionary of Traffic Stats for each Wanpipe Interface. @return: Nested dictionary of statistics for each interface. """
ifInfo = netiface.NetIfaceInfo() ifStats = ifInfo.getIfStats() info_dict = {} for ifname in ifStats: if re.match('^w\d+g\d+$', ifname): info_dict[ifname] = ifStats[ifname] return info_dict
<SYSTEM_TASK:> Execute command and return result body as list of lines. <END_TASK> <USER_TASK:> Description: def _execCmd(self, cmd, args): """Execute command and return result body as list of lines. @param cmd: Command string. @param args: Comand arguments string. @return: Result dictionary. """
output = self._eslconn.api(cmd, args) if output: body = output.getBody() if body: return body.splitlines() return None
<SYSTEM_TASK:> Ping Redis Server and return Round-Trip-Time in seconds. <END_TASK> <USER_TASK:> Description: def ping(self): """Ping Redis Server and return Round-Trip-Time in seconds. @return: Round-trip-time in seconds as float. """
start = time.time() self._conn.ping() return (time.time() - start)
<SYSTEM_TASK:> Makes multi-indexed dataframe of subject data <END_TASK> <USER_TASK:> Description: def list2pd(all_data, subjindex=None, listindex=None): """ Makes multi-indexed dataframe of subject data Parameters ---------- all_data : list of lists of strings strings are either all presented or all recalled items, in the order of presentation or recall *should also work for presented / recalled ints and floats, if desired Returns ---------- subs_list_of_dfs : multi-indexed dataframe dataframe of subject data (presented or recalled words/items), indexed by subject and list number cell populated by the term presented or recalled in the position indicated by the column number """
# set default index if it is not defined # max_nlists = max(map(lambda x: len(x), all_data)) listindex = [[idx for idx in range(len(sub))] for sub in all_data] if not listindex else listindex subjindex = [idx for idx,subj in enumerate(all_data)] if not subjindex else subjindex def make_multi_index(listindex, sub_num): return pd.MultiIndex.from_tuples([(sub_num,lst) for lst in listindex], names = ['Subject', 'List']) listindex = list(listindex) subjindex = list(subjindex) subs_list_of_dfs = [pd.DataFrame(sub_data, index=make_multi_index(listindex[sub_num], subjindex[sub_num])) for sub_num,sub_data in enumerate(all_data)] return pd.concat(subs_list_of_dfs)
<SYSTEM_TASK:> Creates egg data object from zero-indexed recall matrix <END_TASK> <USER_TASK:> Description: def recmat2egg(recmat, list_length=None): """ Creates egg data object from zero-indexed recall matrix Parameters ---------- recmat : list of lists (subs) of lists (encoding lists) of ints or 2D numpy array recall matrix representing serial positions of freely recalled words \ e.g. [[[16, 15, 0, 2, 3, None, None...], [16, 4, 5, 6, 1, None, None...]]] list_length : int The length of each list (e.g. 16) Returns ---------- egg : Egg data object egg data object computed from the recall matrix """
from .egg import Egg as Egg pres = [[[str(word) for word in list(range(0,list_length))] for reclist in recsub] for recsub in recmat] rec = [[[str(word) for word in reclist if word is not None] for reclist in recsub] for recsub in recmat] return Egg(pres=pres,rec=rec)
<SYSTEM_TASK:> Fills in default distance metrics for fingerprint analyses <END_TASK> <USER_TASK:> Description: def default_dist_funcs(dist_funcs, feature_example): """ Fills in default distance metrics for fingerprint analyses """
if dist_funcs is None: dist_funcs = dict() for key in feature_example: if key in dist_funcs: pass if key == 'item': pass elif isinstance(feature_example[key], (six.string_types, six.binary_type)): dist_funcs[key] = 'match' elif isinstance(feature_example[key], (int, np.integer, float)) or all([isinstance(i, (int, np.integer, float)) for i in feature_example[key]]): dist_funcs[key] = 'euclidean' return dist_funcs
<SYSTEM_TASK:> Convert a MultiIndex df to list <END_TASK> <USER_TASK:> Description: def df2list(df): """ Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values The input df reformatted as a list """
subjects = df.index.levels[0].values.tolist() lists = df.index.levels[1].values.tolist() idx = pd.IndexSlice df = df.loc[idx[subjects,lists],df.columns] lst = [df.loc[sub,:].values.tolist() for sub in subjects] return lst
<SYSTEM_TASK:> Parses an egg and returns fields <END_TASK> <USER_TASK:> Description: def parse_egg(egg): """Parses an egg and returns fields"""
pres_list = egg.get_pres_items().values[0] rec_list = egg.get_rec_items().values[0] feature_list = egg.get_pres_features().values[0] dist_funcs = egg.dist_funcs return pres_list, rec_list, feature_list, dist_funcs
<SYSTEM_TASK:> Helper function to merge pres and features to support legacy features argument <END_TASK> <USER_TASK:> Description: def merge_pres_feats(pres, features): """ Helper function to merge pres and features to support legacy features argument """
sub = [] for psub, fsub in zip(pres, features): exp = [] for pexp, fexp in zip(psub, fsub): lst = [] for p, f in zip(pexp, fexp): p.update(f) lst.append(p) exp.append(lst) sub.append(exp) return sub
<SYSTEM_TASK:> Function that calculates the Fisher z-transformation <END_TASK> <USER_TASK:> Description: def r2z(r): """ Function that calculates the Fisher z-transformation Parameters ---------- r : int or ndarray Correlation value Returns ---------- result : int or ndarray Fishers z transformed correlation value """
with np.errstate(invalid='ignore', divide='ignore'): return 0.5 * (np.log(1 + r) - np.log(1 - r))
<SYSTEM_TASK:> Function that calculates the inverse Fisher z-transformation <END_TASK> <USER_TASK:> Description: def z2r(z): """ Function that calculates the inverse Fisher z-transformation Parameters ---------- z : int or ndarray Fishers z transformed correlation value Returns ---------- result : int or ndarray Correlation value """
with np.errstate(invalid='ignore', divide='ignore'): return (np.exp(2 * z) - 1) / (np.exp(2 * z) + 1)
<SYSTEM_TASK:> Return system uptime in seconds. <END_TASK> <USER_TASK:> Description: def getUptime(self): """Return system uptime in seconds. @return: Float that represents uptime in seconds. """
try: fp = open(uptimeFile, 'r') line = fp.readline() fp.close() except: raise IOError('Failed reading stats from file: %s' % uptimeFile) return float(line.split()[0])
<SYSTEM_TASK:> Return system Load Average. <END_TASK> <USER_TASK:> Description: def getLoadAvg(self): """Return system Load Average. @return: List of 1 min, 5 min and 15 min Load Average figures. """
try: fp = open(loadavgFile, 'r') line = fp.readline() fp.close() except: raise IOError('Failed reading stats from file: %s' % loadavgFile) arr = line.split() if len(arr) >= 3: return [float(col) for col in arr[:3]] else: return None
<SYSTEM_TASK:> Return stats for running and blocked processes, forks, <END_TASK> <USER_TASK:> Description: def getProcessStats(self): """Return stats for running and blocked processes, forks, context switches and interrupts. @return: Dictionary of stats. """
info_dict = {} try: fp = open(cpustatFile, 'r') data = fp.read() fp.close() except: raise IOError('Failed reading stats from file: %s' % cpustatFile) for line in data.splitlines(): arr = line.split() if len(arr) > 1 and arr[0] in ('ctxt', 'intr', 'softirq', 'processes', 'procs_running', 'procs_blocked'): info_dict[arr[0]] = arr[1] return info_dict
<SYSTEM_TASK:> Send stat command to Memcached Server and return response lines. <END_TASK> <USER_TASK:> Description: def _sendStatCmd(self, cmd): """Send stat command to Memcached Server and return response lines. @param cmd: Command string. @return: Array of strings. """
try: self._conn.write("%s\r\n" % cmd) regex = re.compile('^(END|ERROR)\r\n', re.MULTILINE) (idx, mobj, text) = self._conn.expect([regex,], self._timeout) #@UnusedVariable except: raise Exception("Communication with %s failed" % self._instanceName) if mobj is not None: if mobj.group(1) == 'END': return text.splitlines()[:-1] elif mobj.group(1) == 'ERROR': raise Exception("Protocol error in communication with %s." % self._instanceName) else: raise Exception("Connection with %s timed out." % self._instanceName)
<SYSTEM_TASK:> Parse stats output from memcached and return dictionary of stats- <END_TASK> <USER_TASK:> Description: def _parseStats(self, lines, parse_slabs = False): """Parse stats output from memcached and return dictionary of stats- @param lines: Array of lines of input text. @param parse_slabs: Parse slab stats if True. @return: Stats dictionary. """
info_dict = {} info_dict['slabs'] = {} for line in lines: mobj = re.match('^STAT\s(\w+)\s(\S+)$', line) if mobj: info_dict[mobj.group(1)] = util.parse_value(mobj.group(2), True) continue elif parse_slabs: mobj = re.match('STAT\s(\w+:)?(\d+):(\w+)\s(\S+)$', line) if mobj: (slab, key, val) = mobj.groups()[-3:] if not info_dict['slabs'].has_key(slab): info_dict['slabs'][slab] = {} info_dict['slabs'][slab][key] = util.parse_value(val, True) return info_dict
<SYSTEM_TASK:> Execute ps command with custom output format with columns from <END_TASK> <USER_TASK:> Description: def parseProcCmd(self, fields=('pid', 'user', 'cmd',), threads=False): """Execute ps command with custom output format with columns from fields and return result as a nested list. The Standard Format Specifiers from ps man page must be used for the fields parameter. @param fields: List of fields included in the output. Default: pid, user, cmd @param threads: If True, include threads in output. @return: List of headers and list of rows and columns. """
args = [] headers = [f.lower() for f in fields] args.append('--no-headers') args.append('-e') if threads: args.append('-T') field_ranges = [] fmt_strs = [] start = 0 for header in headers: field_width = psFieldWidth.get(header, psDefaultFieldWidth) fmt_strs.append('%s:%d' % (header, field_width)) end = start + field_width + 1 field_ranges.append((start,end)) start = end args.append('-o') args.append(','.join(fmt_strs)) lines = self.execProcCmd(*args) if len(lines) > 0: stats = [] for line in lines: cols = [] for (start, end) in field_ranges: cols.append(line[start:end].strip()) stats.append(cols) return {'headers': headers, 'stats': stats} else: return None
<SYSTEM_TASK:> Execute ps command with custom output format with columns columns <END_TASK> <USER_TASK:> Description: def getProcList(self, fields=('pid', 'user', 'cmd',), threads=False, **kwargs): """Execute ps command with custom output format with columns columns from fields, select lines using the filters defined by kwargs and return result as a nested list. The Standard Format Specifiers from ps man page must be used for the fields parameter. @param fields: Fields included in the output. Default: pid, user, cmd @param threads: If True, include threads in output. @param **kwargs: Keyword variables are used for filtering the results depending on the values of the columns. Each keyword must correspond to a field name with an optional suffix: field: Field equal to value or in list of values. field_ic: Field equal to value or in list of values, using case insensitive comparison. field_regex: Field matches regex value or matches with any regex in list of values. field_ic_regex: Field matches regex value or matches with any regex in list of values using case insensitive match. @return: List of headers and list of rows and columns. """
field_list = list(fields) for key in kwargs: col = re.sub('(_ic)?(_regex)?$', '', key) if not col in field_list: field_list.append(col) pinfo = self.parseProcCmd(field_list, threads) if pinfo: if len(kwargs) > 0: pfilter = util.TableFilter() pfilter.registerFilters(**kwargs) stats = pfilter.applyFilters(pinfo['headers'], pinfo['stats']) return {'headers': pinfo['headers'], 'stats': stats} else: return pinfo else: return None
<SYSTEM_TASK:> Execute ps command with custom output format with columns format with <END_TASK> <USER_TASK:> Description: def getProcDict(self, fields=('user', 'cmd',), threads=False, **kwargs): """Execute ps command with custom output format with columns format with columns from fields, and return result as a nested dictionary with the key PID or SPID. The Standard Format Specifiers from ps man page must be used for the fields parameter. @param fields: Fields included in the output. Default: user, cmd (PID or SPID column is included by default.) @param threads: If True, include threads in output. @param **kwargs: Keyword variables are used for filtering the results depending on the values of the columns. Each keyword must correspond to a field name with an optional suffix: field: Field equal to value or in list of values. field_ic: Field equal to value or in list of values, using case insensitive comparison. field_regex: Field matches regex value or matches with any regex in list of values. field_ic_regex: Field matches regex value or matches with any regex in list of values using case insensitive match. @return: Nested dictionary indexed by: PID for process info. SPID for thread info. """
stats = {} field_list = list(fields) num_cols = len(field_list) if threads: key = 'spid' else: key = 'pid' try: key_idx = field_list.index(key) except ValueError: field_list.append(key) key_idx = len(field_list) - 1 result = self.getProcList(field_list, threads, **kwargs) if result is not None: headers = result['headers'][:num_cols] lines = result['stats'] if len(lines) > 1: for cols in lines: stats[cols[key_idx]] = dict(zip(headers, cols[:num_cols])) return stats else: return None
<SYSTEM_TASK:> Return process counts per status and priority. <END_TASK> <USER_TASK:> Description: def getProcStatStatus(self, threads=False, **kwargs): """Return process counts per status and priority. @param **kwargs: Keyword variables are used for filtering the results depending on the values of the columns. Each keyword must correspond to a field name with an optional suffix: field: Field equal to value or in list of values. field_ic: Field equal to value or in list of values, using case insensitive comparison. field_regex: Field matches regex value or matches with any regex in list of values. field_ic_regex: Field matches regex value or matches with any regex in list of values using case insensitive match. @return: Dictionary of process counters. """
procs = self.getProcList(['stat',], threads=threads, **kwargs) status = dict(zip(procStatusNames.values(), [0,] * len(procStatusNames))) prio = {'high': 0, 'low': 0, 'norm': 0, 'locked_in_mem': 0} total = 0 locked_in_mem = 0 if procs is not None: for cols in procs['stats']: col_stat = cols[0] status[procStatusNames[col_stat[0]]] += 1 if '<' in col_stat[1:]: prio['high'] += 1 elif 'N' in col_stat[1:]: prio['low'] += 1 else: prio['norm'] += 1 if 'L' in col_stat[1:]: locked_in_mem += 1 total += 1 return {'status': status, 'prio': prio, 'locked_in_mem': locked_in_mem, 'total': total}
<SYSTEM_TASK:> Truncate long graph and field labels. <END_TASK> <USER_TASK:> Description: def fixLabel(label, maxlen, delim=None, repl='', truncend=True): """Truncate long graph and field labels. @param label: Label text. @param maxlen: Maximum field label length in characters. No maximum field label length is enforced by default. @param delim: Delimiter for field labels field labels longer than maxlen will preferably be truncated at delimiter. @param repl: Replacement string for truncated part. @param truncend: Truncate the end of label name if True. (Default) The beginning part of label will be truncated if False. """
if len(label) <= maxlen: return label else: maxlen -= len(repl) if delim is not None: if truncend: end = label.rfind(delim, 0, maxlen) if end > 0: return label[:end+1] + repl else: start = label.find(delim, len(label) - maxlen) if start > 0: return repl + label[start:] if truncend: return label[:maxlen] + repl else: return repl + label[-maxlen:]
<SYSTEM_TASK:> Private method for returning graph object with name graph_name. <END_TASK> <USER_TASK:> Description: def _getGraph(self, graph_name, fail_noexist=False): """Private method for returning graph object with name graph_name. @param graph_name: Graph Name @param fail_noexist: If true throw exception if there is no graph with name graph_name. @return: Graph Object or None """
graph = self._graphDict.get(graph_name) if fail_noexist and graph is None: raise AttributeError("Invalid graph name: %s" % graph_name) else: return graph
<SYSTEM_TASK:> Private method for returning subgraph object with name graph_name <END_TASK> <USER_TASK:> Description: def _getSubGraph(self, parent_name, graph_name, fail_noexist=False): """Private method for returning subgraph object with name graph_name and parent graph with name parent_name. @param parent_name: Root Graph Name @param graph_name: Subgraph Name @param fail_noexist: If true throw exception if there is no subgraph with name graph_name. @return: Graph Object or None """
if not self.isMultigraph: raise AttributeError("Simple Munin Plugins cannot have subgraphs.") if self._graphDict.has_key(parent_name) is not None: subgraphs = self._subgraphDict.get(parent_name) if subgraphs is not None: subgraph = subgraphs.get(graph_name) if fail_noexist and subgraph is None: raise AttributeError("Invalid subgraph name %s" "for graph %s." % (graph_name, parent_name)) else: return subgraph else: raise AttributeError("Parent graph %s has no subgraphs." % (parent_name,)) else: raise AttributeError("Invalid parent graph name %s " "for subgraph %s." % (parent_name, graph_name))
<SYSTEM_TASK:> Private method for generating Multigraph ID from graph name and <END_TASK> <USER_TASK:> Description: def _getMultigraphID(self, graph_name, subgraph_name=None): """Private method for generating Multigraph ID from graph name and subgraph name. @param graph_name: Graph Name. @param subgraph_name: Subgraph Name. @return: Multigraph ID. """
if self.isMultiInstance and self._instanceName is not None: if subgraph_name is None: return "%s_%s" % (graph_name, self._instanceName) else: return "%s_%s.%s_%s" % (graph_name, self._instanceName, subgraph_name, self._instanceName) else: if subgraph_name is None: return graph_name else: return "%s.%s" % (graph_name, subgraph_name)
<SYSTEM_TASK:> Formats configuration directory from Munin Graph and returns <END_TASK> <USER_TASK:> Description: def _formatConfig(self, conf_dict): """Formats configuration directory from Munin Graph and returns multi-line value entries for the plugin config cycle. @param conf_dict: Configuration directory. @return: Multi-line text. """
confs = [] graph_dict = conf_dict['graph'] field_list = conf_dict['fields'] # Order and format Graph Attributes title = graph_dict.get('title') if title is not None: if self.isMultiInstance and self._instanceLabel is not None: if self._instanceLabelType == 'suffix': confs.append("graph_%s %s - %s" % ('title', title, self._instanceLabel,)) elif self._instanceLabelType == 'prefix': confs.append("graph_%s %s - %s" % ('title', self._instanceLabel, title,)) else: confs.append("graph_%s %s" % ('title', title)) for key in ('category', 'vlabel', 'info', 'args', 'period', 'scale', 'total', 'order', 'printf', 'width', 'height'): val = graph_dict.get(key) if val is not None: if isinstance(val, bool): if val: val = "yes" else: val = "no" confs.append("graph_%s %s" % (key, val)) # Order and Format Field Attributes for (field_name, field_attrs) in field_list: for key in ('label', 'type', 'draw', 'info', 'extinfo', 'colour', 'negative', 'graph', 'min', 'max', 'cdef', 'line', 'warning', 'critical'): val = field_attrs.get(key) if val is not None: if isinstance(val, bool): if val: val = "yes" else: val = "no" confs.append("%s.%s %s" % (field_name, key, val)) return "\n".join(confs)
<SYSTEM_TASK:> Formats value list from Munin Graph and returns multi-line value <END_TASK> <USER_TASK:> Description: def _formatVals(self, val_list): """Formats value list from Munin Graph and returns multi-line value entries for the plugin fetch cycle. @param val_list: List of name-value pairs. @return: Multi-line text. """
vals = [] for (name, val) in val_list: if val is not None: if isinstance(val, float): vals.append("%s.value %f" % (name, val)) else: vals.append("%s.value %s" % (name, val)) else: vals.append("%s.value U" % (name,)) return "\n".join(vals)
<SYSTEM_TASK:> Return value for environment variable or None. <END_TASK> <USER_TASK:> Description: def envGet(self, name, default=None, conv=None): """Return value for environment variable or None. @param name: Name of environment variable. @param default: Default value if variable is undefined. @param conv: Function for converting value to desired type. @return: Value of environment variable. """
if self._env.has_key(name): if conv is not None: return conv(self._env.get(name)) else: return self._env.get(name) else: return default
<SYSTEM_TASK:> Utility methos to save plugin state stored in stateObj to persistent <END_TASK> <USER_TASK:> Description: def saveState(self, stateObj): """Utility methos to save plugin state stored in stateObj to persistent storage to permit access to previous state in subsequent plugin runs. Any object that can be pickled and unpickled can be used to store the plugin state. @param stateObj: Object that stores plugin state. """
try: fp = open(self._stateFile, 'w') pickle.dump(stateObj, fp) except: raise IOError("Failure in storing plugin state in file: %s" % self._stateFile) return True
<SYSTEM_TASK:> Utility method to restore plugin state from persistent storage to <END_TASK> <USER_TASK:> Description: def restoreState(self): """Utility method to restore plugin state from persistent storage to permit access to previous plugin state. @return: Object that stores plugin state. """
if os.path.exists(self._stateFile): try: fp = open(self._stateFile, 'r') stateObj = pickle.load(fp) except: raise IOError("Failure in reading plugin state from file: %s" % self._stateFile) return stateObj return None
<SYSTEM_TASK:> Utility method to associate Subgraph Instance to Root Graph Instance. <END_TASK> <USER_TASK:> Description: def appendSubgraph(self, parent_name, graph_name, graph): """Utility method to associate Subgraph Instance to Root Graph Instance. This utility method is for use in constructor of child classes for associating a MuninGraph Subgraph instance with a Root Graph instance. @param parent_name: Root Graph Name @param graph_name: Subgraph Name @param graph: MuninGraph Instance """
if not self.isMultigraph: raise AttributeError("Simple Munin Plugins cannot have subgraphs.") if self._graphDict.has_key(parent_name): if not self._subgraphDict.has_key(parent_name): self._subgraphDict[parent_name] = {} self._subgraphNames[parent_name] = [] self._subgraphDict[parent_name][graph_name] = graph self._subgraphNames[parent_name].append(graph_name) else: raise AttributeError("Invalid parent graph name %s used for subgraph %s." % (parent_name, graph_name))
<SYSTEM_TASK:> Set Value for Field in Subgraph. <END_TASK> <USER_TASK:> Description: def setSubgraphVal(self, parent_name, graph_name, field_name, val): """Set Value for Field in Subgraph. The private method is for use in retrieveVals() method of child classes. @param parent_name: Root Graph Name @param graph_name: Subgraph Name @param field_name: Field Name. @param val: Value for field. """
subgraph = self._getSubGraph(parent_name, graph_name, True) if subgraph.hasField(field_name): subgraph.setVal(field_name, val) else: raise AttributeError("Invalid field name %s for subgraph %s " "of parent graph %s." % (field_name, graph_name, parent_name))
<SYSTEM_TASK:> Returns list of names of subgraphs for Root Graph with name parent_name. <END_TASK> <USER_TASK:> Description: def getSubgraphList(self, parent_name): """Returns list of names of subgraphs for Root Graph with name parent_name. @param parent_name: Name of Root Graph. @return: List of subgraph names. """
if not self.isMultigraph: raise AttributeError("Simple Munin Plugins cannot have subgraphs.") if self._graphDict.has_key(parent_name): return self._subgraphNames[parent_name] or [] else: raise AttributeError("Invalid parent graph name %s." % (parent_name,))
<SYSTEM_TASK:> Return true if graph with name graph_name has field with <END_TASK> <USER_TASK:> Description: def graphHasField(self, graph_name, field_name): """Return true if graph with name graph_name has field with name field_name. @param graph_name: Graph Name @param field_name: Field Name. @return: Boolean """
graph = self._graphDict.get(graph_name, True) return graph.hasField(field_name)
<SYSTEM_TASK:> Return true if subgraph with name graph_name with parent graph with <END_TASK> <USER_TASK:> Description: def subGraphHasField(self, parent_name, graph_name, field_name): """Return true if subgraph with name graph_name with parent graph with name parent_name has field with name field_name. @param parent_name: Root Graph Name @param graph_name: Subgraph Name @param field_name: Field Name. @return: Boolean """
subgraph = self._getSubGraph(parent_name, graph_name, True) return subgraph.hasField(field_name)
<SYSTEM_TASK:> Returns list of names of fields for graph with name graph_name. <END_TASK> <USER_TASK:> Description: def getGraphFieldList(self, graph_name): """Returns list of names of fields for graph with name graph_name. @param graph_name: Graph Name @return: List of field names for graph. """
graph = self._getGraph(graph_name, True) return graph.getFieldList()
<SYSTEM_TASK:> Returns number of fields for graph with name graph_name. <END_TASK> <USER_TASK:> Description: def getGraphFieldCount(self, graph_name): """Returns number of fields for graph with name graph_name. @param graph_name: Graph Name @return: Number of fields for graph. """
graph = self._getGraph(graph_name, True) return graph.getFieldCount()
<SYSTEM_TASK:> Returns list of names of fields for subgraph with name graph_name <END_TASK> <USER_TASK:> Description: def getSubgraphFieldList(self, parent_name, graph_name): """Returns list of names of fields for subgraph with name graph_name and parent graph with name parent_name. @param parent_name: Root Graph Name @param graph_name: Subgraph Name @return: List of field names for subgraph. """
graph = self._getSubGraph(parent_name, graph_name, True) return graph.getFieldList()
<SYSTEM_TASK:> Returns number of fields for subgraph with name graph_name and parent <END_TASK> <USER_TASK:> Description: def getSubgraphFieldCount(self, parent_name, graph_name): """Returns number of fields for subgraph with name graph_name and parent graph with name parent_name. @param parent_name: Root Graph Name @param graph_name: Subgraph Name @return: Number of fields for subgraph. """
graph = self._getSubGraph(parent_name, graph_name, True) return graph.getFieldCount()
<SYSTEM_TASK:> Implements Munin Plugin Graph Configuration. <END_TASK> <USER_TASK:> Description: def config(self): """Implements Munin Plugin Graph Configuration. Prints out configuration for graphs. Use as is. Not required to be overwritten in child classes. The plugin will work correctly as long as the Munin Graph objects have been populated. """
for parent_name in self._graphNames: graph = self._graphDict[parent_name] if self.isMultigraph: print "multigraph %s" % self._getMultigraphID(parent_name) print self._formatConfig(graph.getConfig()) print if (self.isMultigraph and self._nestedGraphs and self._subgraphDict and self._subgraphNames): for (parent_name, subgraph_names) in self._subgraphNames.iteritems(): for graph_name in subgraph_names: graph = self._subgraphDict[parent_name][graph_name] print "multigraph %s" % self.getMultigraphID(parent_name, graph_name) print self._formatConfig(graph.getConfig()) print return True
<SYSTEM_TASK:> Implements main entry point for plugin execution. <END_TASK> <USER_TASK:> Description: def run(self): """Implements main entry point for plugin execution."""
if len(self._argv) > 1 and len(self._argv[1]) > 0: oper = self._argv[1] else: oper = 'fetch' if oper == 'fetch': ret = self.fetch() elif oper == 'config': ret = self.config() if ret and self._dirtyConfig: ret = self.fetch() elif oper == 'autoconf': ret = self.autoconf() if ret: print "yes" else: print "no" ret = True elif oper == 'suggest': ret = self.suggest() else: raise AttributeError("Invalid command argument: %s" % oper) return ret
<SYSTEM_TASK:> Add field to Munin Graph <END_TASK> <USER_TASK:> Description: def addField(self, name, label, type=None, draw=None, info=None, #@ReservedAssignment extinfo=None, colour=None, negative=None, graph=None, min=None, max=None, cdef=None, line=None, #@ReservedAssignment warning=None, critical=None): """Add field to Munin Graph @param name: Field Name @param label: Field Label @param type: Stat Type: 'COUNTER' / 'ABSOLUTE' / 'DERIVE' / 'GAUGE' @param draw: Graph Type: 'AREA' / 'LINE{1,2,3}' / 'STACK' / 'LINESTACK{1,2,3}' / 'AREASTACK' @param info: Detailed Field Info @param extinfo: Extended Field Info @param colour: Field Colour @param negative: Mirror Value @param graph: Draw on Graph - True / False (Default: True) @param min: Minimum Valid Value @param max: Maximum Valid Value @param cdef: CDEF @param line: Adds horizontal line at value defined for field. @param warning: Warning Value @param critical: Critical Value """
if self._autoFixNames: name = self._fixName(name) if negative is not None: negative = self._fixName(negative) self._fieldAttrDict[name] = dict(((k,v) for (k,v) in locals().iteritems() if (v is not None and k not in ('self',)))) self._fieldNameList.append(name)