Exemplo n.º 1
0
# license.  Please see the LICENSE file that should have been included
# as part of this package.
"""Unittests for Bio.Align.Applications interface for TCOFFEE."""

import sys
import os
import unittest
from Bio import AlignIO, SeqIO, MissingExternalDependencyError
from Bio.Align.Applications import TCoffeeCommandline

#Try to avoid problems when the OS is in another language
os.environ['LANG'] = 'C'

t_coffee_exe = None
if sys.platform == "win32":
    raise MissingExternalDependencyError(
        "Testing TCOFFEE on Windows not supported yet")
else:
    from Bio._py3k import getoutput
    output = getoutput("t_coffee -version")
    if "not found" not in output \
    and ("t_coffee" in output.lower() or "t-coffee" in output.lower()):
        t_coffee_exe = "t_coffee"

if not t_coffee_exe:
    raise MissingExternalDependencyError(
        "Install TCOFFEE if you want to use the Bio.Align.Applications wrapper."
    )


class TCoffeeApplication(unittest.TestCase):
    def setUp(self):
Exemplo n.º 2
0
#Tests simcoal related code. Note: this case requires simcoal
#test_PopGen_SimCoal_nodepend tests code that does not require simcoal

found = False
for path in os.environ['PATH'].split(os.pathsep):
    try:
        for filename in os.listdir(path):
            if filename.startswith('simcoal2') \
            or (filename.lower() == "simcoal2.exe") :
                found = True
                simcoal_dir = path
    except os.error:
        pass  #Path doesn't exist - correct to pass
if not found:
    raise MissingExternalDependencyError(\
        "Install SIMCOAL2 if you want to use Bio.PopGen.SimCoal.")


class AppTest(unittest.TestCase):
    """Tests simcoal execution via biopython.
    """
    def tearDown(self):
        if not os.path.isdir(os.path.join('PopGen', 'simple')):
            #Unit test must have failed to invoke simcaol,
            #and this it never created the directory.
            return
        for file in os.listdir(os.path.join('PopGen', 'simple')):
            os.remove(os.sep.join(['PopGen', 'simple', file]))
        os.rmdir(os.path.join('PopGen', 'simple'))

    def test_simcoal(self):
Exemplo n.º 3
0
exes_wanted = [
    "water", "needle", "seqret", "transeq", "seqmatchall", "embossversion"
]
exes = {}  # Dictionary mapping from names to exe locations

if "EMBOSS_ROOT" in os.environ:
    # Windows default installation path is C:\mEMBOSS which contains the exes.
    # EMBOSS also sets an environment variable which we will check for.
    path = os.environ["EMBOSS_ROOT"]
    if os.path.isdir(path):
        for name in exes_wanted:
            if os.path.isfile(os.path.join(path, name + ".exe")):
                exes[name] = os.path.join(path, name + ".exe")
        del name
    else:
        raise MissingExternalDependencyError(
            "$EMBOSS_ROOT=%r which does not exist!" % path)
    del path
if sys.platform != "win32":
    from subprocess import getoutput

    for name in exes_wanted:
        # This will "just work" if installed on the path as normal on Unix
        output = getoutput("%s -help" % name)
        if "not found" not in output and "not recognized" not in output:
            exes[name] = name
        del output
    del name

if len(exes) < len(exes_wanted):
    raise MissingExternalDependencyError(
        "Install EMBOSS if you want to use Bio.Emboss.")
Exemplo n.º 4
0
                                    hitlist_size=10,
                                    entrez_query=entrez_filter,
                                    expect=e_value,
                                    megablast="FALSE")
        else:
            handle = NCBIWWW.qblast(program,
                                    database,
                                    query,
                                    alignments=10,
                                    descriptions=10,
                                    hitlist_size=10,
                                    entrez_query=entrez_filter,
                                    expect=e_value)
    except HTTPError:
        # e.g. a proxy error
        raise MissingExternalDependencyError("internet connection failed")
    record = NCBIXML.read(handle)

    if record.query == "No definition line":
        # We used a sequence as the query
        assert len(query) == record.query_letters
    elif query.startswith(">"):
        # We used a FASTA record as the query
        assert query[1:].split("\n", 1)[0] == (record.query)
    else:
        # We used an identifier as the query
        assert query in record.query_id.split("|")

    # Check the recorded input parameters agree with those requested
    assert float(record.expect) == e_value
    assert record.application.lower() == program
Exemplo n.º 5
0
    fixers = refactor.get_fixers_from_package("lib2to3.fixes")
    fixers.remove("lib2to3.fixes.fix_print")  # Already using print function
    rt = refactor.RefactoringTool(fixers)
    assert rt.refactor_docstring(">>> print(2+2)\n4\n", "example1") == \
                                 ">>> print(2+2)\n4\n"
    assert rt.refactor_docstring('>>> print("Two plus two is", 2+2)\n'
                                 'Two plus two is 4\n', "example2") == \
                                 '>>> print("Two plus two is", 2+2)\nTwo plus two is 4\n'

tutorial = os.path.join(os.path.dirname(sys.argv[0]), "../Doc/Tutorial.tex")
if not os.path.isfile(tutorial) and sys.version_info[0] >= 3:
    tutorial = os.path.join(os.path.dirname(sys.argv[0]),
                            "../../../Doc/Tutorial.tex")
if not os.path.isfile(tutorial):
    from Bio import MissingExternalDependencyError
    raise MissingExternalDependencyError(
        "Could not find ../Doc/Tutorial.tex file")

tutorial_base = os.path.abspath(
    os.path.join(os.path.dirname(sys.argv[0]), "../Doc/"))
original_path = os.path.abspath(".")


def _extract(handle):
    line = handle.readline()
    if line != "\\begin{verbatim}\n":
        raise ValueError(
            "Any '%doctest' or '%cont-doctest' line should be followed by '\\begin{verbatim}'"
        )
    lines = []
    while True:
        line = handle.readline()
Exemplo n.º 6
0
# Copyright 2004-2008 by Michiel de Hoon.  All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.

# See the Biopython Tutorial for an explanation of the biological
# background of these tests.

try:
    import numpy
except ImportError:
    from Bio import MissingExternalDependencyError
    raise MissingExternalDependencyError(
        "Install NumPy if you want to use Bio.LogisticRegression.")

import unittest
import sys
from Bio import LogisticRegression

xs = [[-53, -200.78], [117, -267.14], [57, -163.47], [16, -190.30],
      [11, -220.94], [85, -193.94], [16, -182.71], [15, -180.41],
      [-26, -181.73], [58, -259.87], [126, -414.53], [191, -249.57],
      [113, -265.28], [145, -312.99], [154, -213.83], [147, -380.85],
      [93, -291.13]]

ys = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]


class TestLogisticRegression(unittest.TestCase):
    def test_calculate_model(self):
        model = LogisticRegression.train(xs, ys)
                exes[name] = os.path.join(path, name + ".exe")
    del path, name
if sys.platform != "win32":
    from subprocess import getoutput

    for name in exes_wanted:
        # This will "just work" if installed on the path as normal on Unix
        output = getoutput("%s -help" % name)
        if "not found" not in output and "not recognized" not in output:
            exes[name] = name
        del output
    del name

if len(exes) < len(exes_wanted):
    raise MissingExternalDependencyError(
        "Install the Emboss package 'PhylipNew' if you want to use the "
        "Bio.Emboss.Applications wrappers for phylogenetic tools.")

# #########################################################################


# A few top level functions that are called repeatedly in the test cases
def write_AlignIO_dna():
    """Convert opuntia.aln to a phylip file."""
    assert 1 == AlignIO.convert("Clustalw/opuntia.aln", "clustal",
                                "Phylip/opuntia.phy", "phylip")


def write_AlignIO_protein():
    """Convert hedgehog.aln to a phylip file."""
    assert 1 == AlignIO.convert("Clustalw/hedgehog.aln", "clustal",
Exemplo n.º 8
0
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Unit tests for Bio.Phylo functions with external dependencies."""

import unittest

from Bio._py3k import StringIO
from Bio import Phylo

# Check for any missing dependencies at the top level so we can skip
from Bio import MissingExternalDependencyError

try:
    import matplotlib
except ImportError:
    raise MissingExternalDependencyError(
        "Install matplotlib if you want to use Bio.Phylo._utils.")

# Don't use the Wx backend for matplotlib, use the simpler postscript
# backend -- we're not going to display or save the plot anyway, so it
# doesn't matter much, as long as it's not Wx.  See:
# http://lists.open-bio.org/pipermail/biopython-dev/2012-April/009559.html
matplotlib.use("ps")
try:
    from matplotlib import pyplot
except ImportError:
    # Can fail here with font problems
    raise MissingExternalDependencyError(
        "Install matplotlib if you want to use Bio.Phylo._utils.")

# Example PhyloXML file
EX_DOLLO = "PhyloXML/o_tol_332_d_dollo.xml"
Exemplo n.º 9
0
    # Since "not found" may be in another language, try and be sure this is
    # really the bwa tool's output
    bwa_found = False
    if "not found" not in output and "bwa" in output \
            and "alignment via Burrows-Wheeler transformation" in output:
        bwa_exe = "bwa"
    skip_aln_tests = False
    aln_output = getoutput("bwa aln")
    if "unrecognized" in aln_output:
        skip_aln_tests = True
        print("'bwa aln' is unrecognized, skipping aln/samse/sampe tests")

if not bwa_exe:
    raise MissingExternalDependencyError("Install bwa and correctly set"
                                         " the file path to the program if"
                                         " you want to use it from Biopython")


class BwaTestCase(unittest.TestCase):
    """Class for implementing BWA test cases"""
    def setUp(self):
        self.reference_file = "BWA/human_g1k_v37_truncated.fasta"
        self.reference_extensions = ['amb', 'ann', 'bwt', 'pac', 'sa']
        self.infile1 = "BWA/HNSCC1_1_truncated.fastq"
        self.infile2 = "BWA/HNSCC1_2_truncated.fastq"
        self.saifile1 = "BWA/1.sai"
        self.saifile2 = "BWA/2.sai"
        self.samfile1 = "BWA/1.sam"
        self.samfile2 = "BWA/2.sam"
        self.samfile = "BWA/out.sam"
Exemplo n.º 10
0
from Bio import MissingExternalDependencyError
from Bio.PopGen.GenePop.Controller import GenePopController

# Tests genepop related code. Note: this case requires genepop
# test_PopGen_GenePop_nodepend tests code that does not require genepop

found = False
for path in os.environ['PATH'].split(os.pathsep):
    try:
        for filename in os.listdir(path):
            if filename.startswith('Genepop'):
                found = True
    except os.error:
        pass  # Path doesn't exist - correct to pass
if not found:
    raise MissingExternalDependencyError(
        "Install GenePop if you want to use Bio.PopGen.GenePop.")


class AppTest(unittest.TestCase):
    """Tests genepop execution via biopython.
    """

    def test_allele_genotype_frequencies(self):
        """Test genepop execution on basic allele and genotype frequencies.
        """
        ctrl = GenePopController()
        pop_iter, locus_iter = ctrl.calc_allele_genotype_freqs("PopGen" + os.sep + "big.gen")
        # print("%s %s" % (pop, loci))
        # for popc in pop_iter:
        #    pop_name, loci_content = popc
        #    print(pop_name)
Exemplo n.º 11
0
    def run_qblast(
        self,
        program,
        database,
        query,
        e_value,
        entrez_filter,
        additional_args,
        expected_hits,
    ):
        """Do qblast searches with given parameters and analyze results."""
        try:
            if program == "blastn":
                # Check the megablast parameter is accepted
                handle = NCBIWWW.qblast(program,
                                        database,
                                        query,
                                        alignments=10,
                                        descriptions=10,
                                        hitlist_size=10,
                                        entrez_query=entrez_filter,
                                        expect=e_value,
                                        **additional_args)
            else:
                handle = NCBIWWW.qblast(program,
                                        database,
                                        query,
                                        alignments=10,
                                        descriptions=10,
                                        hitlist_size=10,
                                        entrez_query=entrez_filter,
                                        expect=e_value,
                                        **additional_args)
        except HTTPError:
            # e.g. a proxy error
            raise MissingExternalDependencyError(
                "internet connection failed") from None

        record = NCBIXML.read(handle)

        if record.query == "No definition line":
            # We used a sequence as the query
            self.assertEqual(len(query), record.query_letters)
        elif query.startswith(">"):
            # We used a FASTA record as the query
            expected = query[1:].split("\n", 1)[0]
            self.assertEqual(expected, record.query)
        elif (record.query_id.startswith("Query_")
              and len(query) == record.query_letters):
            # We used a sequence as the entry and it was given a placeholder name
            pass
        else:
            # We used an identifier as the query
            self.assertIn(
                query,
                record.query_id.split("|"),
                "Expected %r within query_id %r" % (query, record.query_id),
            )

        # Check the recorded input parameters agree with those requested
        self.assertEqual(float(record.expect), e_value)
        self.assertEqual(record.application.lower(), program)
        self.assertTrue(len(record.alignments) <= 10)
        self.assertTrue(len(record.descriptions) <= 10)

        # Check the expected result(s) are found in the alignments
        if expected_hits is None:
            self.assertEqual(len(record.alignments),
                             0)  # Expected no alignments!
        else:
            self.assertTrue(
                len(record.alignments) > 0)  # Expected some alignments!
            found_result = False
            for expected_hit in expected_hits:
                for alignment in record.alignments:
                    if expected_hit in alignment.hit_id.split("|"):
                        found_result = True
                        break
            self.assertTrue(
                found_result,
                "Missing all expected hits (%s), instead have: %s" % (
                    ", ".join(expected_hits),
                    ", ".join(a.hit_id for a in record.alignments),
                ),
            )

        # Check the expected result(s) are found in the descriptions
        if expected_hits is None:
            self.assertEqual(len(record.descriptions),
                             0)  # Expected no descriptions!
        else:
            self.assertTrue(
                len(record.descriptions) > 0)  # Expected some descriptions!
            found_result = False
            for expected_hit in expected_hits:
                for descr in record.descriptions:
                    if expected_hit == descr.accession or expected_hit in descr.title.split(
                            None, 1)[0].split("|"):
                        found_result = True
                        break
            assert found_result, "Missing all of %s in descriptions" % expected_hit
            self.assertTrue(found_result)
Exemplo n.º 12
0
try :
    from numpy import asarray
except ImportError :
    from Bio import MissingExternalDependencyError
    raise MissingExternalDependencyError(\
        "Install NumPy if you want to use Bio.MarkovModel.")

from Bio import MarkovModel

def print_mm(markov_model):
    print "STATES: %s" % ' '.join(markov_model.states)
    print "ALPHABET: %s" % ' '.join(markov_model.alphabet)
    print "INITIAL:"
    for i in range(len(markov_model.p_initial)):
        print "  %s: %.2f" % (
            markov_model.states[i], markov_model.p_initial[i])
    print "TRANSITION:"
    for i in range(len(markov_model.p_transition)):
        x = ["%.2f" % x for x in markov_model.p_transition[i]]
        print "  %s: %s" % (markov_model.states[i], ' '.join(x))
    print "EMISSION:"
    for i in range(len(markov_model.p_emission)):
        x = ["%.2f" % x for x in markov_model.p_emission[i]]
        print "  %s: %s" % (markov_model.states[i], ' '.join(x))



print "TESTING train_visible"
states = ["0", "1", "2", "3"]
alphabet = ["A", "C", "G", "T"]
training_data = [
Exemplo n.º 13
0
    # command, but this does cause them to quit cleanly.  Otherwise they prompt
    # the user for input (causing a lock up).
    output = getoutput("clustalw2 --version")
    # Since "not found" may be in another language, try and be sure this is
    # really the clustalw tool's output
    if "not found" not in output and "not recognized" not in output:
        if "CLUSTAL" in output and "Multiple Sequence Alignments" in output:
            clustalw_exe = "clustalw2"
    if not clustalw_exe:
        output = getoutput("clustalw --version")
        if "not found" not in output and "not recognized" not in output:
            if "CLUSTAL" in output and "Multiple Sequence Alignments" in output:
                clustalw_exe = "clustalw"

if not clustalw_exe:
    raise MissingExternalDependencyError(
        "Install clustalw or clustalw2 if you want to use it from Biopython.")


class ClustalWTestCase(unittest.TestCase):
    """Class implementing common functions for ClustalW tests."""

    def setUp(self):
        self.files_to_clean = set()

    def tearDown(self):
        for filename in self.files_to_clean:
            if os.path.isfile(filename):
                os.remove(filename)

    def standard_test_procedure(self, cline):
        """Shared test procedure used by all tests."""
Exemplo n.º 14
0
                                                  user=DBUSER,
                                                  passwd=DBPASSWD,
                                                  host=DBHOST)
            server.close()
            del server
    except Exception, e:
        message = "Connection failed, check settings if you plan to use BioSQL: %s" % str(
            e)
        raise MissingExternalDependencyError(message)

    DBSCHEMA = "biosqldb-" + DBTYPE + ".sql"
    SQL_FILE = os.path.join(os.getcwd(), "BioSQL", DBSCHEMA)

    if not os.path.isfile(SQL_FILE):
        message = "Missing SQL schema file: %s" % SQL_FILE
        raise MissingExternalDependencyError(message)


def _do_db_create():
    """Do the actual work of database creation. Relevant for MySQL and PostgreSQL
    """
    # first open a connection to create the database
    server = BioSeqDatabase.open_database(driver=DBDRIVER,
                                          user=DBUSER,
                                          passwd=DBPASSWD,
                                          host=DBHOST)

    if DBDRIVER == "pgdb":
        # The pgdb postgres driver does not support autocommit, so here we
        # commit the current transaction so that 'drop database' query will
        # be outside a transaction block
Exemplo n.º 15
0
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Unit tests for those parts of the Bio.PDB module using Bio.PDB.kdtrees."""

import unittest

try:
    from numpy import array, dot, sqrt, argsort
    from numpy.random import random
except ImportError:
    from Bio import MissingExternalDependencyError

    raise MissingExternalDependencyError(
        "Install NumPy if you want to use Bio.PDB.") from None

try:
    from Bio.PDB import kdtrees
except ImportError:
    from Bio import MissingExternalDependencyError

    raise MissingExternalDependencyError(
        "C module Bio.PDB.kdtrees not compiled") from None

from Bio.PDB.NeighborSearch import NeighborSearch


class NeighborTest(unittest.TestCase):
    def test_neighbor_search(self):
        """NeighborSearch: Find nearby randomly generated coordinates.
Exemplo n.º 16
0
dice, a fair dice that has 1/6 probability of rolling any number and
a loaded dice that has 1/2 probability to roll a 6, and 1/10 probability
to roll any other number. The probability of switching from the fair to
loaded dice is .05 and the probability of switching from loaded to fair is
.1.
"""

from __future__ import print_function

import os
if os.name == 'java':
    from Bio import MissingExternalDependencyError
    # This is a slight miss-use of MissingExternalDependencyError,
    # but it will do in the short term to skip this unit test on Jython
    raise MissingExternalDependencyError(
        "This test can cause a fatal error "
        "on Jython with some versions of Java")

# standard modules
import random

# biopython
from Bio import Alphabet
from Bio.Seq import MutableSeq
from Bio.Seq import Seq

# HMM stuff we are testing
from Bio.HMM import MarkovModel
from Bio.HMM import Trainer
from Bio.HMM import Utilities
Exemplo n.º 17
0
        #    print("Rejecting %r" % exe_name)
        del exe_name, name

# To avoid the name clash with legacy BLAST, Debian introduced rpsblast+ alias
wanted.remove("rpsblast+")
if "rpsblast+" in exe_names:
    exe_names["rpsblast"] = exe_names["rpsblast+"]
    del exe_names["rpsblast+"]

# We can cope with blast_formatter being missing, only added in BLAST 2.2.24+
# We can cope with deltablast being missing, only added in BLAST 2.2.26+
optional = ["blast_formatter", "deltablast"]
if len(set(exe_names).difference(optional)) < len(
        set(wanted).difference(optional)):
    raise MissingExternalDependencyError(
        "Install the NCBI BLAST+ command line "
        "tools if you want to use the "
        "Bio.Blast.Applications wrapper.")


class Pairwise(unittest.TestCase):
    def test_blastp(self):
        """Pairwise BLASTP search"""
        global exe_names
        cline = Applications.NcbiblastpCommandline(
            exe_names["blastp"],
            query="Fasta/rose.pro",
            subject="GenBank/NC_005816.faa",
            evalue=1)
        self.assertEqual(
            str(cline),
            _escape_filename(exe_names["blastp"]) +
Exemplo n.º 18
0
        os_path.extend(likely_dirs)
    for path in os.environ["PATH"].split(os.pathsep):
        exe_file = os.path.join(path, program)
        if is_exe(exe_file):
            return exe_file
    return None


# Find the PAML binaries
if sys.platform == "win32":
    binaries = ["codeml.exe", "baseml.exe", "yn00.exe"]
else:
    binaries = ["codeml", "baseml", "yn00"]
for binary in binaries:
    if which(binary) is None:
        raise MissingExternalDependencyError(
            "Install PAML if you want to use the Bio.Phylo.PAML wrapper.")


class Common(unittest.TestCase):
    """Base class for PAML unit tests."""

    del_files = []

    def __del__(self):
        """Just in case tool creates some junk files, do a clean-up."""
        del_files = self.del_files
        for filename in del_files:
            if os.path.exists(filename):
                os.remove(filename)

Exemplo n.º 19
0
                muscle_exe = os.path.join(folder, "muscle.exe")
                break
        if muscle_exe:
            break
else:
    from Bio._py3k import getoutput
    output = getoutput("muscle -version")
    # Since "not found" may be in another language, try and be sure this is
    # really the MUSCLE tool's output
    if "not found" not in output and "MUSCLE" in output \
       and "Edgar" in output:
        muscle_exe = "muscle"

if not muscle_exe:
    raise MissingExternalDependencyError(
        "Install MUSCLE if you want to use the Bio.Align.Applications wrapper."
    )

#################################################################


class MuscleApplication(unittest.TestCase):
    def setUp(self):
        self.infile1 = "Fasta/f002"
        self.infile2 = "Fasta/fa01"
        self.infile3 = "Fasta/f001"
        self.outfile1 = "Fasta/temp align out1.fa"  # with spaces!
        self.outfile2 = "Fasta/temp_align_out2.fa"
        self.outfile3 = "Fasta/temp_align_out3.fa"
        self.outfile4 = "Fasta/temp_align_out4.fa"
Exemplo n.º 20
0
#################################################################

# Try to avoid problems when the OS is in another language
os.environ["LANG"] = "C"

clustalo_exe = None
try:
    output = getoutput("clustalo --help")
    if output.startswith("Clustal Omega"):
        clustalo_exe = "clustalo"
except FileNotFoundError:
    pass

if not clustalo_exe:
    raise MissingExternalDependencyError(
        "Install clustalo if you want to use Clustal Omega from Biopython.")


class ClustalOmegaTestCase(unittest.TestCase):
    def setUp(self):
        self.files_to_clean = set()

    def tearDown(self):
        for filename in self.files_to_clean:
            if os.path.isfile(filename):
                os.remove(filename)

    def standard_test_procedure(self, cline):
        """Shared test procedure used by all tests."""
        # Overwrite existing files.
        cline.force = True
Exemplo n.º 21
0
from Bio.Phylo.Applications import RaxmlCommandline
from Bio import MissingExternalDependencyError

raxml_exe = None
try:
    from subprocess import getoutput
    output = getoutput("raxmlHPC -v")
    if "not found" not in output and "not recognized" not in output:
        if "This is RAxML" in output:
            raxml_exe = "raxmlHPC"
except FileNotFoundError:
    pass

if not raxml_exe:
    raise MissingExternalDependencyError(
        "Install RAxML (binary raxmlHPC) if you want to test the Bio.Phylo.Applications wrapper."
    )

# Example Phylip file with 4 aligned protein sequences
EX_PHYLIP = "Phylip/interlaced2.phy"


class AppTests(unittest.TestCase):
    """Tests for application wrappers."""
    def test_raxml(self):
        """Run RAxML using the wrapper."""
        cmd = RaxmlCommandline(raxml_exe,
                               sequences=EX_PHYLIP,
                               model="PROTCATWAG",
                               name="test")
        # The parsimony seed should be set automatically
Exemplo n.º 22
0
from Bio import AlignIO
from Bio import MissingExternalDependencyError
from Bio import SeqIO
from Bio.Align.Applications import MSAProbsCommandline
from Bio.Application import ApplicationError
from Bio._py3k import getoutput

#################################################################

# Try to avoid problems when the OS is in another language
os.environ['LANG'] = 'C'

msaprobs_exe = None
if sys.platform == "win32":
    # TODO
    raise MissingExternalDependencyError(
        "Testing this on Windows is not implemented yet")
else:
    output = getoutput("msaprobs -version")
    if output.startswith("MSAPROBS version"):
        msaprobs_exe = "msaprobs"

if not msaprobs_exe:
    raise MissingExternalDependencyError(
        "Install msaprobs if you want to use MSAProbs from Biopython.")


class MSAProbsTestCase(unittest.TestCase):
    def setUp(self):
        self.files_to_clean = set()

    def tearDown(self):
Exemplo n.º 23
0
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.

try:
    import numpy
except ImportError:
    from Bio import MissingExternalDependencyError
    raise MissingExternalDependencyError(
        "Install NumPy if you want to use Bio.KDTree.")

try:
    from Bio.KDTree import _CKDTree
except ImportError:
    from Bio import MissingExternalDependencyError
    raise MissingExternalDependencyError("C module in Bio.KDTree not compiled")

from Bio.KDTree.KDTree import _neighbor_test, _test

nr_points = 5000
dim = 3
bucket_size = 5
radius = 0.01

for i in range(0, 10):
    _neighbor_test(nr_points, dim, bucket_size, radius)
    _test(nr_points, dim, bucket_size, radius)
Exemplo n.º 24
0
# as part of this package.
"""Unittests for Bio.Align.Applications interface for PROBCONS."""

import sys
import os
import unittest
from Bio._py3k import StringIO
from Bio import AlignIO, SeqIO, MissingExternalDependencyError
from Bio.Align.Applications import ProbconsCommandline

# Try to avoid problems when the OS is in another language
os.environ['LANG'] = 'C'

probcons_exe = None
if sys.platform == "win32":
    raise MissingExternalDependencyError("PROBCONS not available on Windows")
else:
    from Bio._py3k import getoutput
    output = getoutput("probcons")
    if "not found" not in output and "probcons" in output.lower():
        probcons_exe = "probcons"

if not probcons_exe:
    raise MissingExternalDependencyError(
        "Install PROBCONS if you want to use the Bio.Align.Applications wrapper.")


class ProbconsApplication(unittest.TestCase):

    def setUp(self):
        self.infile1 = "Fasta/fa01"
"""Tests for online functionality of the KGML modules."""

# Builtins
import os
import unittest

# Biopython
from Bio.Graphics.ColorSpiral import ColorSpiral

# Do we have ReportLab?  Raise error if not present.
from Bio import MissingExternalDependencyError
try:
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.lib.pagesizes import A4
except ImportError:
    raise MissingExternalDependencyError(
        "Install reportlab if you want to use Bio.Graphics.") from None

# Do we have PIL?
try:
    from PIL import Image
except ImportError:
    raise MissingExternalDependencyError(
        "Install Pillow or its predecessor PIL (Python Imaging Library) "
        "if you want to use bitmaps from KGML.") from None


# Biopython Bio.KEGG.KGML
from Bio.KEGG.KGML.KGML_parser import read
from Bio.Graphics.KGML_vis import KGMLCanvas

# test_KGML_graphics module
Exemplo n.º 26
0
as part of this package.
"""

import sys
import os
import unittest
import subprocess
from Bio import MissingExternalDependencyError
from Bio.Align.Applications import MafftCommandline

#Try to avoid problems when the OS is in another language
os.environ['LANG'] = 'C'

mafft_exe = None
if sys.platform == "win32":
    raise MissingExternalDependencyError(
        "Testing with MAFFT not implemented on Windows yet")
else:
    import commands
    output = commands.getoutput("mafft -help")
    if "not found" not in output and "MAFFT" in output:
        mafft_exe = "mafft"
if not mafft_exe:
    raise MissingExternalDependencyError(\
        "Install MAFFT if you want to use the Bio.Align.Applications wrapper.")


def check_mafft_version(mafft_exe):
    child = subprocess.Popen("%s --help" % mafft_exe,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             universal_newlines=True,
# license.  Please see the LICENSE file that should have been included
# as part of this package.
"""Unittests for Bio.Align.Applications interface for DIALIGN2-2."""

import sys
import os
import unittest
from Bio import MissingExternalDependencyError
from Bio.Align.Applications import DialignCommandline

# Try to avoid problems when the OS is in another language
os.environ["LANG"] = "C"

dialign_exe = None
if sys.platform == "win32":
    raise MissingExternalDependencyError("DIALIGN2-2 not available on Windows")
else:
    from subprocess import getoutput

    output = getoutput("dialign2-2")
    if "not found" not in output and "not recognized" not in output:
        if "dialign2-2" in output.lower():
            dialign_exe = "dialign2-2"
            if "DIALIGN2_DIR" not in os.environ:
                raise MissingExternalDependencyError(
                    "Environment variable DIALIGN2_DIR for DIALIGN2-2 missing."
                )
            if not os.path.isdir(os.environ["DIALIGN2_DIR"]):
                raise MissingExternalDependencyError(
                    "Environment variable DIALIGN2_DIR for DIALIGN2-2 is not a valid directory."
                )
Exemplo n.º 28
0
                    fasttree_exe = os.path.join(prog_files, folder, filename)
                    break
            if fasttree_exe: break
else:
    import commands
    # Checking the -help argument
    output = commands.getoutput("fasttree -help")
    #Since "is not recognized" may be in another language, try and be sure this is
    #really the fasttree tool's output
    fasttree_found = False
    if "is not recognized" not in output and "protein_alignment" in output \
    and "nucleotide_alignment" in output:
        fasttree_exe = "fasttree"

if not fasttree_exe:
    raise MissingExternalDependencyError(\
        "Install fasttree and correctly set the file path to the program if you want to use it from Biopython.")

#################################################################

print "Checking error conditions"
print "========================="

print "Empty file"
input_file = "does_not_exist.fasta"
output_file = "test.fasta"
assert not os.path.isfile(input_file)
cline = FastTreeCommandline(fasttree_exe, input=input_file, out=output_file)
try:
    stdout, stderr = cline()
    assert False, "Should have failed, returned:\n%s\n%s" % (stdout, stderr)
except ApplicationError, err:
Exemplo n.º 29
0
# it right now, unless it starts to happen with real data! If anyone
# can figure out the data that causes it so I can avoid it, that'd be much
# appreciated.

# standard library
import os
import random
import unittest

from Bio import MissingExternalDependencyError
try:
    # Skip the test if reportlab is not installed
    import reportlab as r
    del r
except ImportError:
    raise MissingExternalDependencyError(
        "Install reportlab if you want to use Bio.Graphics.")

# the stuff we're testing
from Bio.Graphics.Comparative import ComparativeScatterPlot


class ComparativeTest(unittest.TestCase):
    """Do tests for modules involved with comparing data."""
    def setUp(self):
        self.min_num_points = 1
        self.max_num_points = 500

        self.min_point_num = 0
        self.max_point_num = 200

    def _make_random_points(self, num_two_d_lists):
Exemplo n.º 30
0
import os
import unittest
from Bio import SeqIO
from Bio import AlignIO
from Bio.Align.Applications import ClustalOmegaCommandline
from Bio.Application import ApplicationError

#################################################################

#Try to avoid problems when the OS is in another language
os.environ['LANG'] = 'C'

clustalo_exe = None
if sys.platform == "win32":
    #TODO
    raise MissingExternalDependencyError(
        "Testing this on Windows not implemented yet")
else:
    import commands
    output = commands.getoutput("clustalo --help")
    if output.startswith("Clustal Omega"):
        clustalo_exe = "clustalo"

if not clustalo_exe:
    raise MissingExternalDependencyError(\
        "Install clustalo if you want to use Clustal Omega from Biopython.")


class ClustalOmegaTestCase(unittest.TestCase):
    def setUp(self):
        self.files_to_clean = set()