Skip to content

Record missing data in Bio.Phylo.PAML.codeml - #1012

Merged
peterjc merged 5 commits into
biopython:masterfrom
alpae:fix_codeml_param_parsing
Nov 29, 2016
Merged

peterjc merged 5 commits into
biopython:masterfrom
alpae:fix_codeml_param_parsing

Conversation

@alpae

@alpae alpae commented Nov 28, 2016

Copy link
Copy Markdown
Contributor

The long existing issue #483 was also a problem in one of my analysis. I've added a fix and a unittest. The codeml parser parses now all site parameters of a pairwise codeml analysis.

parse all site parameters of a pairwise codeml analysis
@codecov-io

codecov-io commented Nov 28, 2016 •

Copy link
Copy Markdown

Current coverage is 80.40% (diff: 100%)

Merging #1012 into master will increase coverage by 0.01%

@@             master      #1012   diff @@
==========================================
  Files           319        319          
  Lines         48798      48800     +2   
  Methods           0          0          
  Messages          0          0          
  Branches          0          0          
==========================================
+ Hits          39228      39238    +10   
+ Misses         9570       9562     -8   
  Partials          0          0          

Powered by Codecov. Last update 808eca9...0aae6f0

@peterjc

peterjc commented Nov 28, 2016

Copy link
Copy Markdown
Member

@brandoninvergo could you look at this please? There isn't a test file to look at as you requested on #483, but @alpae has included a unit test.

@brandoninvergo

brandoninvergo commented Nov 28, 2016 •

Copy link
Copy Markdown
Contributor

At first glance it seems OK, although it's been a while since I looked at the code.

The patch changes the code to use collections.defaultdict, which I don't think was an option when I wrote the module due to backwards-compatibility problems. Is it still an issue? Also, line 415 in the patch performs multiple definitions of different types on the same line, which I think is bad form. How does it fit with the Biopython coding standards?

Anyway, it seems to me that it could have just as easily been fixed by unindenting lines 423-437 by one level. That looks like it was the source of the bug (ah that Python "feature" of indentation-as-structural-delimiter can really bite you if you miss something). But if we go that route, please change 423 and 425 to read if seq1 not in pairwise and if seq2 not in pairwise, which is more Pythonic!

Comment thread Bio/Phylo/PAML/_parse_codeml.py Outdated
# t= 0.0126 S= 81.4 N= 140.6 dN/dS= 0.0010 dN= 0.0000 dS= 0.0115
pair_re = re.compile("\d+ \((.+)\) ... \d+ \((.+)\)")
pairwise = {}
pairwise, seq1, seq2 = collections.defaultdict(dict), None, None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As noted by @brandoninvergo using three separate lines would be more in line with the rest of Biopython here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, will do that

@alpae

alpae commented Nov 28, 2016

Copy link
Copy Markdown
Contributor Author

@brandoninvergo the change in line 423/425 is not the same whether you test that the seq1/seq2 are in pairwise or None. The logLiklihood value and the other values are not read from the same line. I'm happy do adapt line 415 to single assignment statements. The defaultdict has been introduced in python2.5. Given that Py2.6 is required for biopython, I guess that is fine.

@peterjc

peterjc commented Nov 28, 2016

Copy link
Copy Markdown
Member

We have no dependency problem using defaultdict now (or the ordered dict either).

@peterjc

peterjc commented Nov 28, 2016

Copy link
Copy Markdown
Member

Biopython 1.68 was our last release to support Python 2.6, so you can now assume Python 2.7 or Python 3.3 onwards.

Comment thread Tests/test_PAML_codeml.py Outdated
for param in ("t", "S", "N", "omega", "dN", "dS", "lnL"):
self.assertTrue(param in data, version_msg +
": '%s' not in parsed parameters" % param)
self.assertTrue(isinstance(data[param], numbers.Number))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we've ever used the numbers module before in Biopython (at least, searching for import numbers didn't show any matches). Maybe we should, or would checking against int and float work just as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this case for sure, testing for float would be just as good. numbers module came with Py2.6. probably that's why it is not yet used in biopython. But I'll change that one.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Please open an issue on taking advantage of the numbers module in Biopython if you think it would be useful.

@peterjc peterjc changed the title fixes #483 CEL file version 4 parser Nov 28, 2016
@peterjc peterjc changed the title CEL file version 4 parser Record missing data in Bio.Phylo.PAML.codeml Nov 28, 2016
@peterjc

peterjc commented Nov 28, 2016

Copy link
Copy Markdown
Member

(I've given the pull request a more descriptive name, although I did muddle this with another open issue first - whoops)

@peterjc

peterjc commented Nov 28, 2016

Copy link
Copy Markdown
Member

@brandoninvergo are you happy for this to be merged now? Is the proposed test enough?

@brandoninvergo brandoninvergo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test doesn't catch the problem...

Comment thread Tests/test_PAML_codeml.py Outdated
% version.replace('_', '.')
results_path = os.path.join(res_dir, results_file)
results = codeml.read(results_path)
for seq2 in results['pairwise'].values():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test doesn't actually catch the problem as written. Changing 484-485 to this should work:

        for seq in results["pairwise"]:
            seq_vals = results["pairwise"][seq]
            self.assertTrue(len(seq_vals) > 0, "no parsed parameters for '%s'" \
                            % seq)
            for data in seq_vals:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hang on, my suggestion seems to be buggy too.

@peterjc

peterjc commented Nov 28, 2016

Copy link
Copy Markdown
Member

@alpae: Once this is ready to merge, are you happy to dual licence your contributions under both the Biopython License Agreement and the BSD 3-Clause License? See #898.

Also, would you be happy to be thanked by name in the NEWS and CONTRIB files?

thanks to Brandon Invergo for spotting this
@brandoninvergo

brandoninvergo commented Nov 28, 2016 •

Copy link
Copy Markdown
Contributor

Here's a working, simplified (flat is better than nested...) version of the test. Also, the original testPairwise was broken, so it's fixed here. There's a bit of overlap between the two tests. Oh well

def testParsePairwise(self):
    res_dir = os.path.join(self.results_dir, "codeml", "pairwise")
    for results_file in os.listdir(res_dir):
        version = results_file.split('-')[1].split('.')[0]
        version_msg = "Improper parsing for version %s" \
                    % version.replace('_', '.')
        results_path = os.path.join(res_dir, results_file)
        results = codeml.read(results_path)
        # Pairwise models have an extra top-level item: pairwise
        self.assertEqual(len(results), 5, version_msg)
        self.assertTrue("pairwise" in results, version_msg)
        pairwise = results["pairwise"]
        self.assertEqual(len(pairwise), 2, version_msg +
                         ": should be two species")
        seq1, seq2 = list(pairwise.keys())
        self.assertEqual(len(pairwise[seq1][seq2]), 7, version_msg +
                         ": wrong number of parameters parsed")
        self.assertEqual(len(pairwise[seq2][seq1]), 7, version_msg +
                         ": wrong number of parameters parsed")

def testParseSitesParamsForPairwise(self):
    """Verify that pairwise site estimates are indeed parsed. Fixes #483"""
    res_dir = os.path.join(self.results_dir, "codeml", "pairwise")
    for results_file in os.listdir(res_dir):
        version = results_file.split('-')[1].split('.')[0]
        version_msg = "Improper parsing for version %s" \
                    % version.replace('_', '.')
        results_path = os.path.join(res_dir, results_file)
        results = codeml.read(results_path)
        self.assertTrue("pairwise" in results)
        self.assertEqual(len(results["pairwise"]), 2)
        seq1, seq2 = list(results["pairwise"].keys())
        params = results["pairwise"][seq1][seq2]
        self.assertEqual(len(params), 7,
                        version_msg + ": wrong number of parsed parameters" +
                         " for %s-%s" % (seq1, seq2))
        for param in ("t", "S", "N", "omega", "dN", "dS", "lnL"):
            self.assertTrue(param in params, version_msg +
                            ": '%s' not in parsed parameters" \
                            % (param))
            self.assertTrue(isinstance(params[param], float))
            if param != "lnL":
                self.assertTrue(params[param] >= 0)

@alpae

alpae commented Nov 28, 2016

Copy link
Copy Markdown
Contributor Author

@peterjc dual licence: of course, fine with me, also about being mentioned in news/contribs. my real name is Adrian Altenhoff. ;-)

@brandoninvergo

Copy link
Copy Markdown
Contributor

As for the defaultdict question, the problem is that the rest of the code does it the old-fashioned way. I'd rather see all of it updated at once to defaultdict.

@brandoninvergo

Copy link
Copy Markdown
Contributor

And what about this for a fix to the parse_pairwise function, which retains the current coding style of the rest of the file? (sorry, I don't know how to properly use Github in cases like this)

def parse_pairwise(lines, results):
    """Parse results from pairwise comparisons.
    """
    # Find pairwise comparisons
    # Example:
    # 2 (Pan_troglo) ... 1 (Homo_sapie)
    # lnL = -291.465693
    #  0.01262 999.00000  0.00100
    #
    # t= 0.0126  S=    81.4  N=   140.6  dN/dS= 0.0010  dN= 0.0000  dS= 0.0115
    pair_re = re.compile("\d+ \((.+)\) ... \d+ \((.+)\)")
    pairwise = {}
    seq1 = None
    seq2 = None
    for line in lines:
        # Find all floating point numbers in this line
        if not seq1 and not seq2:
            pair_res = pair_re.match(line)
            if pair_res:
                seq1 = pair_res.group(1)
                seq2 = pair_res.group(2)
                pairwise[seq1] = {seq2: {}}
                pairwise[seq2] = {seq1: {}}
                continue
        else:
            line_floats_res = line_floats_re.findall(line)
            line_floats = [_nan_float(val) for val in line_floats_res]
            if len(line_floats) == 1:
                pairwise[seq1][seq2].update({"lnL": line_floats[0]})
                pairwise[seq2][seq1] = pairwise[seq1][seq2]
            elif len(line_floats) == 6:
                pairwise[seq1][seq2].update({"t": line_floats[0],
                                             "S": line_floats[1],
                                             "N": line_floats[2],
                                             "omega": line_floats[3],
                                             "dN": line_floats[4],
                                             "dS": line_floats[5]})
                pairwise[seq2][seq1] = pairwise[seq1][seq2]
    if pairwise:
        results["pairwise"] = pairwise
    return results

@alpae

alpae commented Nov 28, 2016

Copy link
Copy Markdown
Contributor Author

@brandoninvergo your suggested test changes do not work, as in the test files the pairwise runs are done with more than 2 sequences. then you end up with several pairs, so the len(pairwise)==2 check generally fails. Also, because in a result file generally you find more than one pairwise result, only checking initially if seq1/seq2 are None is not enough: you need to test multiple times, but ignore float-lines until you have the first matching sequence pair...

I kept the spirit of your suggestions for both test and parse code, including the standard dict instead of the defaultdict (valid point that all other functions don't use it). Hope this is ok.
Cheers

@brandoninvergo

brandoninvergo commented Nov 28, 2016 •

Copy link
Copy Markdown
Contributor

Ah right, I see my mistake with the updated tests. You're correct. Sorry, I've never used codeml in pairwise mode and I didn't look closely at the test results file.

Thanks for the fix!

@peterjc everything looks ok to me now.

@peterjc
peterjc merged commit 81a6355 into biopython:master Nov 29, 2016
peterjc added a commit that referenced this pull request Nov 29, 2016
@alpae
alpae deleted the fix_codeml_param_parsing branch November 29, 2016 11:38
MarkusPiotrowski pushed a commit to MarkusPiotrowski/biopython that referenced this pull request Oct 31, 2017
Squashed commit from pull request biopython#1012, fixes biopython#483.

The codeml parser parses now all site parameters of a pairwise codeml analysis.

Thanks to Brandon Invergo for his input and review.
MarkusPiotrowski pushed a commit to MarkusPiotrowski/biopython that referenced this pull request Oct 31, 2017
peterjc added a commit to peterjc/biopython that referenced this pull request Nov 1, 2019
Original author Brandon Invergo and contributors since as
tracked with version control have all agreed:

 - Adrian Altenhoff (@alpae)
   biopython#1012 (comment)
 - Brandon Invergo (@brandoninvergo)
   biopython#898 (comment)
 - Brian Osborne (@bosborne)
   biopython#898 (comment)
 - Carlos Pena (@carlosp420)
   biopython#898 (comment)
 - Christian Brueffer (@cbrueffer)
   biopython#898 (comment)
 - Eric Talevich (@etal)
   biopython#898 (comment)
 - Jeremy LaBarge (@biojerm)
   biopython#1847 (comment)
 - @morrme
   biopython#1172 (comment)
 - Peter Cock (@peterjc)
   biopython#898 (comment)
 - Sergio Valqui (@svalqui)
   biopython#1749
@peterjc peterjc mentioned this pull request Nov 29, 2019
3 tasks done
peterjc added a commit to peterjc/biopython that referenced this pull request Nov 29, 2019
Original author Brandon Invergo and contributors since as
tracked with version control have all agreed:

 - Adrian Altenhoff (@alpae)
   biopython#1012 (comment)
 - Brandon Invergo (@brandoninvergo)
   biopython#898 (comment)
 - Brian Osborne (@bosborne)
   biopython#898 (comment)
 - Carlos Pena (@carlosp420)
   biopython#898 (comment)
 - Christian Brueffer (@cbrueffer)
   biopython#898 (comment)
 - Eric Talevich (@etal)
   biopython#898 (comment)
 - Jeremy LaBarge (@biojerm)
   biopython#1847 (comment)
 - @morrme
   biopython#1172 (comment)
 - Peter Cock (@peterjc)
   biopython#898 (comment)
 - Sergio Valqui (@svalqui)
   biopython#1749
peterjc added a commit that referenced this pull request Nov 29, 2019
Original author Brandon Invergo and contributors since as
tracked with version control have all agreed:

 - Adrian Altenhoff (@alpae)
   #1012 (comment)
 - Brandon Invergo (@brandoninvergo)
   #898 (comment)
 - Brian Osborne (@bosborne)
   #898 (comment)
 - Carlos Pena (@carlosp420)
   #898 (comment)
 - Christian Brueffer (@cbrueffer)
   #898 (comment)
 - Eric Talevich (@etal)
   #898 (comment)
 - Jeremy LaBarge (@biojerm)
   #1847 (comment)
 - @morrme
   #1172 (comment)
 - Peter Cock (@peterjc)
   #898 (comment)
 - Sergio Valqui (@svalqui)
   #1749
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants