Convert MEME output to motifs
        
        Parameters
        ----------
        fo : file-like
            File object containing MEME output.

        Returns
        -------
        motifs : list
            List of Motif instances.
167589
def parse(self, fo):
        
        motifs = []
        nucs = {"A":0,"C":1,"G":2,"T":3}

        p = re.compile('MOTIF.+MEME-(\d+)\s*width\s*=\s*(\d+)\s+sites\s*=\s*(\d+)')
        pa = re.compile('\)\s+([A-Z]+)')
        line = fo.readline()
        while line:
            m = p.search(line)
            align = []
            pfm = None  
            if m:
                #print(m.group(0))
                id = "%s_%s_w%s" % (self.name, m.group(1), m.group(2))
                while not line.startswith("//"):
                    ma = pa.search(line)
                    if ma:
                        #print(ma.group(0))
                        l = ma.group(1)
                        align.append(l)
                        if not pfm:
                            pfm = [[0 for x in range(4)] for x in range(len(l))]
                        for pos in range(len(l)):
                            if l[pos] in nucs:
                                pfm[pos][nucs[l[pos]]] += 1
                            else:
                                for i in range(4):
                                    pfm[pos][i] += 0.25
                    
                    line = fo.readline()
                
                motifs.append(Motif(pfm[:]))
                motifs[-1].id = id
                motifs[-1].align = align[:]
            line = fo.readline()

        return motifs
1372783
def create_denovo_motif_report(inputfile, pwmfile, fgfa, background, locfa, outdir, params, stats=None):
    """"""
    logger.info("creating reports")

    motifs = read_motifs(pwmfile, fmt="pwm")
    
    # ROC plots
    create_roc_plots(pwmfile, fgfa, background, outdir)
    
    # Closest match in database
    mc = MotifComparer()
    closest_match = mc.get_closest_match(motifs)
    
    if stats is None:
        stats = {}
        for bg, bgfa in background.items():
            for m, s in calc_stats(motifs, fgfa, bgfa).items():
                if m not in stats:
                    stats[m] = {}
                stats[m][bg] = s

    stats = add_star(stats)

    if not params:
        params = {}
    cutoff_fpr = params.get('cutoff_fpr', 0.9)
    lwidth = np.median([len(seq) for seq in Fasta(locfa).seqs])

    # Location plots
    logger.debug("Creating localization plots")
    for motif in motifs:
        logger.debug("  {} {}".format(motif.id, motif))
        outfile = os.path.join(outdir, "images/{}_histogram.svg".format(motif.id))
        motif_localization(locfa, motif, lwidth, outfile, cutoff=cutoff_fpr)

    # Create reports
    _create_text_report(inputfile, motifs, closest_match, stats, outdir)
    _create_graphical_report(inputfile, pwmfile, background, closest_match, outdir, stats)
255119
def _generate_examples(self, archive):
    

    for fname, fobj in archive:
      res = _NAME_RE.match(fname)
      if not res:  # if anything other than .png; skip
        continue
      label = res.group(2).lower()
      yield {
          "image": fobj,
          "label": label,
      }
339846
def fromfile(fname):
    
    fig = SVGFigure()
    with open(fname) as fid:
        svg_file = etree.parse(fid)

    fig.root = svg_file.getroot()
    return fig
1014386
def get_fscore(self, fmap=''):
        
        trees = self.get_dump(fmap)
        fmap = {}
        for tree in trees:
            for line in tree.split('\n'):
                arr = line.split('[')
                if len(arr) == 1:
                    continue
                fid = arr[1].split(']')[0]
                fid = fid.split('<')[0]
                if fid not in fmap:
                    fmap[fid] = 1
                else:
                    fmap[fid] += 1
        return fmap
526195
def _get_platform_patterns(spec, package, src_dir):
        
        raw_patterns = itertools.chain(
            spec.get('', []),
            spec.get(package, []),
        )
        return (
            # Each pattern has to be converted to a platform-specific path
            os.path.join(src_dir, convert_path(pattern))
            for pattern in raw_patterns
        )
26442
def get_annotations(fname, prefix=None):
    ""
    annot_dict = json.load(open(fname))
    id2images, id2bboxes, id2cats = {}, collections.defaultdict(list), collections.defaultdict(list)
    classes = {}
    for o in annot_dict['categories']:
        classes[o['id']] = o['name']
    for o in annot_dict['annotations']:
        bb = o['bbox']
        id2bboxes[o['image_id']].append([bb[1],bb[0], bb[3]+bb[1], bb[2]+bb[0]])
        id2cats[o['image_id']].append(classes[o['category_id']])
    for o in annot_dict['images']:
        if o['id'] in id2bboxes:
            id2images[o['id']] = ifnone(prefix, '') + o['file_name']
    ids = list(id2images.keys())
    return [id2images[k] for k in ids], [[id2bboxes[k], id2cats[k]] for k in ids]
1092211
def _load_from_file_object(self, f):
    
    subtoken_strings = []
    for line in f:
      s = line.strip()
      # Some vocab files wrap words in single quotes, but others don't
      if ((s.startswith("'") and s.endswith("'")) or
          (s.startswith("\"") and s.endswith("\""))):
        s = s[1:-1]
      subtoken_strings.append(native_to_unicode(s))
    self._init_subtokens_from_list(subtoken_strings)
    self._init_alphabet_from_tokens(subtoken_strings)
886732
def process_pattern(fn):
    
    directory, pattern = validate_pattern(fn)
    if directory is not None:
        filenames = fnmatch.filter(auto(listdir, directory), pattern)
        if filenames:
            return [directory + '/' + sfn for sfn in filenames]
        else:
            print_err("cannot access '{}': No such file or directory".format(fn))
433644
def parse_record( self, lines ):
        
        # Break lines up
        temp_lines = []
        for line in lines:
            fields = line.rstrip( "\r\n" ).split( None, 1 )
            if len( fields ) == 1:
                fields.append( "" )
            temp_lines.append( fields )
        lines = temp_lines
        # Fill in motif from lines
        motif = TransfacMotif()
        current_line = 0
        while 1:
            # Done parsing if no more lines to consume
            if current_line >= len( lines ):
                break
            # Remove prefix and first separator from line
            prefix, rest = lines[ current_line ]
            # No action for this prefix, just ignore the line
            if prefix not in self.parse_actions:
                current_line += 1
                continue
            # Get action for line
            action = self.parse_actions[ prefix ]
            # Store a single line value
            if action[0] == "store_single":
                key = action[1]
                setattr( motif, key, rest )
                current_line += 1
            # Add a single line value to a list
            if action[0] == "store_single_list":
                key = action[1]
                if not getattr( motif, key ):
                    setattr( motif, key, [] )
                getattr( motif, key ).append( rest )
                current_line += 1
            # Add a single line value to a dictionary
            if action[0] == "store_single_key_value":
                key = action[1]
                k, v = rest.strip().split( '=', 1 )
                if not getattr( motif, key ):
                    setattr( motif, key, {} )
                getattr( motif, key )[k] = v
                current_line += 1
            # Store a block of text
            if action[0] == "store_block":
                key = action[1]
                value = []
                while current_line < len( lines ) and lines[ current_line ][0] == prefix:
                    value.append( lines[current_line][1] )
                    current_line += 1
                setattr( motif, key, str.join( "\n", value ) )
            # Store a matrix
            if action[0] == "store_matrix":
                # First line is alphabet
                alphabet = rest.split()
                alphabet_size = len( alphabet )
                rows = []
                pattern = ""
                current_line += 1
                # Next lines are the rows of the matrix (we allow 0 rows)
                while current_line < len( lines ):
                    prefix, rest = lines[ current_line ]
                    # Prefix should be a two digit 0 padded row number
                    if not prefix.isdigit():
                        break
                    # The first `alphabet_size` fields are the row values
                    values = rest.split()
                    rows.append( [ float(_) for _ in values[:alphabet_size] ] )
                    # TRANSFAC includes an extra column with the IUPAC code
                    if len( values ) > alphabet_size:
                        pattern += values[alphabet_size]
                    current_line += 1
                # Only store the pattern if it is the correct length (meaning
                # that every row had an extra field)
                if len( pattern ) != len( rows ):
                    pattern = None
                matrix = FrequencyMatrix.from_rows( alphabet, rows )
                setattr( motif, action[1], matrix )
        # Only return a motif if we saw at least ID or AC or NA
        if motif.id or motif.accession or motif.name:
            return motif
1219989
def rank_motifs(stats, metrics=("roc_auc", "recall_at_fdr")):
    """"""
    rank = {}
    combined_metrics = []
    motif_ids = stats.keys()
    background = list(stats.values())[0].keys()
    for metric in metrics:
        mean_metric_stats = [np.mean(
            [stats[m][bg][metric] for bg in background]) for m in motif_ids]
        ranked_metric_stats = rankdata(mean_metric_stats)
        combined_metrics.append(ranked_metric_stats)
    
    for motif, val in zip(motif_ids, np.mean(combined_metrics, 0)):
        rank[motif] = val

    return rank
184972
function(f) {
				f.mime && f.mime !== 'directory' && !addedBadges[f.mime] && addBadgeStyle(f.mime, f.name);
				return templates[list ? 'row' : 'icon']
						.replace(/\{([a-z0-9_]+)\}/g, function(s, e) { 
							return replacement[e] ? replacement[e](f, fm) : (f[e] ? f[e] : ''); 
						});
			}
624999
def as_dict( self, key="id" ):
        
        rval = {}
        for motif in self:
            rval[ getattr( motif, key ) ] = motif
        return rval
1099306
def _ptn2fn(self, pattern):
        '''  '''
        return [pattern.format(wd=self.working_dir, n=self.__name, mode=self.__mode),
                pattern.format(wd=self.working_dir, n='{}.{}'.format(self.__name, self.__mode), mode=self.__mode)]
1138024
def to_fp(self, sort, rm=None):
        
        if rm is None:
            rm = fp.RM.default()

        return fpToFP(rm, self, sort)
785098
def from_file(cls, fp, is_outlook=False):
        
        log.debug("Parsing email from file {!r}".format(fp))

        with ported_open(fp) as f:
            message = email.message_from_file(f)

        if is_outlook:
            log.debug("Removing temp converted Outlook email {!r}".format(fp))
            os.remove(fp)

        return cls(message)
522981
def convert(self, pattern: str) -> str:
        """"""
        parameters = OrderedDict()
        for parameter in self.signature.parameters.values():
            annotation = self.convert_type_to_parse_type(parameter)
            parameters[parameter.name] = "{%s:%s}" % (parameter.name, annotation)

        formatter = GoatFormatter()

        # We have to use vformat here to ensure that kwargs will be OrderedDict
        values = parameters.values()
        parameter_list = list(values)
        converted_pattern = formatter.vformat(pattern, parameter_list, parameters)

        self.context_params = formatter.unused_args
        return converted_pattern