Skip to content

Minimal MEME format support in Bio.motifs.MEME parser #232

Closed

Description

@xguse

The MEME parser fails to even load X.meme files downloaded FROM MEME.

The complaint is:

ValueError("Unexpected end of stream: 'TRAINING SET' not found.")

Looking at the code, it will fail again even if that worked bc it expects **** to follow.

it seems the parser only understands the FULL MEME output format, not the minimal format that seems to be what MEME actually stores its motifs in. This seems a MAJOR oversight. At the very least it limits the usefulness of the module greatly.

Is there any plan to support the minimal MEME format? IS it supported? Am I just being a dunce? I am good at being a dunce.

Anyway thanks.

Activity

  1. peterjc commented on Sep 5, 2013

    @peterjc
    Member

    @mdehoon & @barwil - one for you

    P.S. Are you getting pull request notifications?

  2. mdehoon commented on Sep 6, 2013

    @mdehoon
    Contributor

    Hi @xguse, can you provide a patch to allow the MEME parser to parse the minimal MEME format?

  3. xguse commented on Sep 6, 2013

    @xguse
    Author

    Yeah I will work on it. I am in the homestretch of my dissertation though so it will be a couple weeks. But if the world has survived this long, it will probably be ok!

  4. peterjc commented on Dec 27, 2013

    @peterjc
    Member

    @xguse are you talking about the MEME motif database downloads from http://ebi.edu.au/ftp/software/MEME/Databases/motifs/ where the latest release is http://ebi.edu.au/ftp/software/MEME/Databases/motifs/motif_databases.10.3.tgz used below:

    $ python
    Python 2.7.5 (default, Aug 25 2013, 00:04:04) 
    [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from Bio import motifs
    >>> with open("hallikas2006.meme") as h:
    ...     for m in motifs.parse(h, "meme"): print m
    ... 
    Traceback (most recent call last):
      File "", line 2, in 
      File "/Library/Python/2.7/site-packages/Bio/motifs/__init__.py", line 72, in parse
        record = meme.read(handle)
      File "/Library/Python/2.7/site-packages/Bio/motifs/meme.py", line 29, in read
        __read_datafile(record, handle)
      File "/Library/Python/2.7/site-packages/Bio/motifs/meme.py", line 146, in __read_datafile
        raise ValueError("Unexpected end of stream: 'TRAINING SET' not found.")
    ValueError: Unexpected end of stream: 'TRAINING SET' not found.
  5. daquang commented on Jun 27, 2014

    @daquang

    Did this issue ever get resolved? I would like for the parser to read minimal MEME

  6. mdehoon commented on Jul 4, 2014

    @mdehoon
    Contributor

    Hi @daquang , @xguse , can either of you provide a patch to allow the MEME parser to parse the minimal MEME format?

  7. cbrueffer commented on Sep 4, 2014

    @cbrueffer
    Member

    The MEME files produced by XXmotif (see Bio/motifs/applications/_xxmotif.py) would be good to keep in mind as well, they can't be read by the current code either. Not sure whether the format corresponds to the minimal format referenced above.

  8. cviner commented on Jun 17, 2015

    @cviner

    Hi @xguse @mdehoon @barwil,

    This issue appears to still be outstanding. Is anyone working on or planning to work on this?

  9. saketkc commented on Jun 17, 2015

    @saketkc
    Contributor

    I think this was fixed in c6e8d02

    It should be in the next BioPython release(?)

  10. cviner commented on Jun 17, 2015

    @cviner

    Thanks for pointing out that commit and issue, @saketkc.

    I don't think that fixes this though, since that didn't have to do with getting the minimal MEME format to parse. In particular, line 188 of Bio/motifs/meme.py still raises an error when the training set is not found, as mentioned by @xguse, in the initial report for this issue.

  11. saketkc commented on Jun 17, 2015

    @saketkc
    Contributor

    Sorry, I misunderstood the point of this issue.

  12. cviner commented on Jun 17, 2015

    @cviner

    @saketkc,

    No problem; I appreciate your looking into it!

  13. xguse commented on Jun 18, 2015

    @xguse
    Author

    I began working on it but there was so much that needed to be integrated with existing BioPython structure (which is a bit quite overly convoluted IMHO) that I had to move on to other job related things. What works for me was MUCH simpler and would have been a massive style/convention shift for the code as it stood.

  14. cviner commented on Jun 18, 2015

    @cviner

    @xguse,

    That's too bad, but quite understandable. Thanks for your comments; they confirm my initial impression upon looking at the relevant code. I will likely avoid trying to implement this as well.

  15. egenomics commented on Aug 26, 2016

    @egenomics

    Same problem here. Anyone can suggest an alternative solution? I need to translate minimal meme to another format. Biopython also fails to read other meme output (count matrix or freq matrix or jaspar).

  16. 2 remaining items

  17. aralap commented on Sep 1, 2017

    @aralap
    Contributor

    Maybe meme minimal format can be treated as a different format.
    Below is a relatively functioning parser for minimal format.
    It's inspired on meme parser. I also made a writer function.

    from Bio.Alphabet import IUPAC
    from Bio import Seq
    from Bio import motifs
    import math
    
    def read(handle):
        """Parses the text output of the MEME program into a meme.Record object.
        Example:
        >>> from Bio.motifs import meme
        >>> with open("meme.output.txt") as f:
        ...     record = meme.read(f)
        >>> for motif in record:
        ...     for instance in motif.instances:
        ...         print(instance.motif_name, instance.sequence_name, instance.strand, instance.pvalue)
        """
        motif_number = 0	
        record = Record()
        __read_version(record, handle)
        __read_alphabet(record, handle)
        __read_background(record, handle)
    
        while True:
        	for line in handle:
    		if line.startswith('MOTIF'): 
    	    		break
    	else :
    		return record
    	name  = line.split()[1]
    	motif_number +=1
            length, num_occurrences, evalue  = __read_motif_statistics(line,handle)
            counts = __read_lpm(line,handle)
    	#{'A': 0.25, 'C': 0.25, 'T': 0.25, 'G': 0.25}
            motif = motifs.Motif(alphabet=record.alphabet,counts=counts)
    	motif.background = record.background
            motif.length = length
            motif.num_occurrences = num_occurrences
            motif.evalue = evalue
            motif.name = name
            record.append(motif)
            assert len(record) == motif_number
    	
    
        return record
    
    
    class Record(list):
        """A class for holding the results of a MEME run.    """
    
        def __init__(self):
            """__init__ (self)"""
            self.version = ""
            self.datafile = ""
            self.command = ""
            self.alphabet = None
    	self.background = {}
            self.sequences = []
    
        def __getitem__(self, key):
            if isinstance(key, str):
                for motif in self:
                    if motif.name == key:
                        return motif
            else:
                return list.__getitem__(self, key)
    
    
    # Everything below is private
    
    def __read_background(record, handle):
        for line in handle:
            if line.startswith('Background letter frequencies'):
                break
        else:
            raise ValueError("Improper input file. File should contain a line starting background frequencies.")
        try:
    	line = next(handle)	
        except StopIteration:
    	raise ValueError("Unexpected end of stream: Expected to find line starting background frequencies.") 	
        line = line.strip()
        ls = line.split()
        A,C,G,T = float(ls[1]),float(ls[3]),float(ls[5]),float(ls[7])	
        record.background = {'A':A,'C':C,'G':G,'T':T }
    
    
    def __read_version(record, handle):
        for line in handle:
            if line.startswith('MEME version'):
                break
        else:
            raise ValueError("Improper input file. File should contain a line starting MEME version.")
        line = line.strip()
        ls = line.split()
        record.version = ls[2]
    
    def __read_alphabet(record, handle):
        for line in handle:
            if line.startswith('ALPHABET'):
                break
        else:		    
            raise ValueError("Unexpected end of stream: Expected to find line starting with 'ALPHABET'")
        if not line.startswith('ALPHABET'):
            raise ValueError("Line does not start with 'ALPHABET':\n%s" % line)
        line = line.strip()
        line = line.replace('ALPHABET= ', '')
        if line == 'ACGT':
            al = IUPAC.unambiguous_dna
        else:
            al = IUPAC.protein
        record.alphabet = al
    
    def __read_lpm(line,handle):
    	counts = [[],[],[],[]]
        	for line in handle:
    		freqs =line.split() 
            	if len(freqs) != 4:
                		break
    		counts[0].append(int(float(freqs[0])*1000000))
    		counts[1].append(int(float(freqs[1])*1000000))
    		counts[2].append(int(float(freqs[2])*1000000))
    		counts[3].append(int(float(freqs[3])*1000000))
    	c = {}
    	c['A'] = counts[0]
    	c['C'] = counts[1]
    	c['G'] = counts[2]
    	c['T'] = counts[3]
    	return c
    
    def __read_motif_statistics(line,handle):
        # minimal :
        # 	 letter-probability matrix: alength= 4 w= 19 nsites= 17 E= 4.1e-009 	
        for line in handle:
            if line.startswith('letter-probability matrix:'):
                break	
        num_occurrences  = int(line.split("nsites=")[1].split()[0])	 
        length 	   = int(line.split("w=")[1].split()[0])	
        evalue         = float(line.split("E=")[1].split()[0])	
        return length, num_occurrences, evalue
        
    
    
    def __read_motif_name(handle):
        for line in handle:
            if 'sorted by position p-value' in line:
                break
        else:
            raise ValueError('Unexpected end of stream: Failed to find motif name')
        line = line.strip()
        words = line.split()
        name = " ".join(words[0:2])
        return name
  18. changed the title [-]Bio.motifs.MEME parser outdated?[/-] [+]Minimal MEME format support in Bio.motifs.MEME parser[/+] on Sep 1, 2017
  19. peterjc commented on Sep 1, 2017

    @peterjc
    Member

    What do you think @mdehoon, @barwil - should we ask @aralap to turn that into a pull request?

  20. mdehoon commented on Sep 11, 2017

    @mdehoon
    Contributor

    @aralap Is the difference between the full MEME output and the minimal MEME output a matter of how information is stored in the file? Or does the full MEME output store more information than the minimal MEME output? This can help us decide how to organize the code. For example, could we use the same Record class for both full and minimal MEME output?

  21. aralap commented on Sep 11, 2017

    @aralap
    Contributor

    The full MEME output contains instances, and these are required by the parser.
    The minimal MEME output only contains statistics with a pwm/log-odds matrix .
    Although the full MEME does contain pwm/log-odds matrix they are different in format.
    (For example, they are transversed in version 4.12.0)

  22. mdehoon commented on Sep 14, 2017

    @mdehoon
    Contributor

    If full MEME = minimal MEME + instances, then I would suggest to use the same module and parser, and update the parser such that it can handle both formats.

  23. j-andrews7 commented on Oct 23, 2017

    @j-andrews7
    Contributor

    @aralap did you plan to submit a pull request for this? If not, I will revise the existing parser to also handle the minimal MEME format.

  24. aralap commented on Dec 11, 2017

    @aralap
    Contributor

    @j-andrews7 I planned to do it but haven't found the time recently. Also i wasn't sure the approach i would take was the desired one. I already have a minimal format parser working and wouldn't bother to make a pull request with that.

  25. xguse commented on Dec 11, 2017

    @xguse
    Author
  26. aralap commented on Jul 11, 2018

    @aralap
    Contributor

    Initial commit of code #1734 to make this work, will add test for it soon.

  27. chebizarro commented on Jul 22, 2020

    @chebizarro
    Contributor

    Pull request #1734 has been merged successfully, can this issue be closed now or is additional work required for minimal MEME support?

  28. peterjc commented on Jul 22, 2020

    @peterjc
    Member

    Probably - do you agree @mdehoon ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions