Python scipy 模块,__version__() 实例源码

我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用scipy.__version__()

项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_rank_methods_frame(self):
        tm.skip_if_no_package('scipy', '0.13', 'scipy.stats.rankdata')
        import scipy
        from scipy.stats import rankdata

        xs = np.random.randint(0, 21, (100, 26))
        xs = (xs - 10.0) / 10.0
        cols = [chr(ord('z') - i) for i in range(xs.shape[1])]

        for vals in [xs, xs + 1e6, xs * 1e-6]:
            df = DataFrame(vals, columns=cols)

            for ax in [0, 1]:
                for m in ['average', 'min', 'max', 'first', 'dense']:
                    result = df.rank(axis=ax, method=m)
                    sprank = np.apply_along_axis(
                        rankdata, ax, vals,
                        m if m != 'first' else 'ordinal')
                    sprank = sprank.astype(np.float64)
                    expected = DataFrame(sprank, columns=cols)

                    if LooseVersion(scipy.__version__) >= '0.17.0':
                        expected = expected.astype('float64')
                    tm.assert_frame_equal(result, expected)
项目:Psi-staircase    作者:NNiehof    | 项目源码 | 文件源码
def meta_data(self):
        import time
        import sys
        metadata = {}
        date = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()))
        metadata['date'] = date
        metadata['Version'] = self.version
        metadata['Python Version'] = sys.version
        metadata['Numpy Version'] = np.__version__
        metadata['Scipy Version '] = scipy.__version__
        metadata['psyFunction'] = self.psyfun
        metadata['thresholdGrid'] = self.threshold.tolist()
        metadata['thresholdPrior'] = self.thresholdPrior
        metadata['slopeGrid'] = self.slope.tolist()
        metadata['slopePrior'] = self.slopePrior
        metadata['gammaGrid'] = self.guessRate.tolist()
        metadata['gammaPrior'] = self.guessPrior
        metadata['lapseGrid'] = self.lapseRate.tolist()
        metadata['lapsePrior'] = self.lapsePrior
        return metadata
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def test_scipy(pyi_builder):
    pyi_builder.test_source(
        """
        from distutils.version import LooseVersion

        # Test top-level SciPy importability.
        import scipy
        from scipy import *

        # Test hooked SciPy modules.
        import scipy.io.matlab
        import scipy.sparse.csgraph

        # Test problematic SciPy modules.
        import scipy.linalg
        import scipy.signal

        # SciPy >= 0.16 privatized the previously public "scipy.lib" package as
        # "scipy._lib". Since this package is problematic, test its
        # importability regardless of SciPy version.
        if LooseVersion(scipy.__version__) >= LooseVersion('0.16.0'):
            import scipy._lib
        else:
            import scipy.lib
        """)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_rank_methods_series(self):
        tm.skip_if_no_package('scipy', '0.13', 'scipy.stats.rankdata')
        import scipy
        from scipy.stats import rankdata

        xs = np.random.randn(9)
        xs = np.concatenate([xs[i:] for i in range(0, 9, 2)])  # add duplicates
        np.random.shuffle(xs)

        index = [chr(ord('a') + i) for i in range(len(xs))]

        for vals in [xs, xs + 1e6, xs * 1e-6]:
            ts = Series(vals, index=index)

            for m in ['average', 'min', 'max', 'first', 'dense']:
                result = ts.rank(method=m)
                sprank = rankdata(vals, m if m != 'first' else 'ordinal')
                expected = Series(sprank, index=index)

                if LooseVersion(scipy.__version__) >= '0.17.0':
                    expected = expected.astype('float64')
                tm.assert_series_equal(result, expected)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def skip_if_no_ne(engine='numexpr'):
    import nose
    _USE_NUMEXPR = pd.computation.expressions._USE_NUMEXPR

    if engine == 'numexpr':
        try:
            import numexpr as ne
        except ImportError:
            raise nose.SkipTest("numexpr not installed")

        if not _USE_NUMEXPR:
            raise nose.SkipTest("numexpr disabled")

        if ne.__version__ < LooseVersion('2.0'):
            raise nose.SkipTest("numexpr version too low: "
                                "%s" % ne.__version__)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _plot(cls, ax, y, style=None, bw_method=None, ind=None,
              column_num=None, stacking_id=None, **kwds):
        from scipy.stats import gaussian_kde
        from scipy import __version__ as spv

        y = remove_na(y)

        if LooseVersion(spv) >= '0.11.0':
            gkde = gaussian_kde(y, bw_method=bw_method)
        else:
            gkde = gaussian_kde(y)
            if bw_method is not None:
                msg = ('bw_method was added in Scipy 0.11.0.' +
                       ' Scipy version in use is %s.' % spv)
                warnings.warn(msg)

        y = gkde.evaluate(ind)
        lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)
        return lines
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:operalib    作者:operalib    | 项目源码 | 文件源码
def get_scipy_status():
    """
    Return a dictionary containing a boolean specifying whether SciPy
    is up-to-date, along with the version string (empty string if
    not installed).
    """
    scipy_status = {}
    try:
        import scipy
        scipy_version = scipy.__version__
        scipy_status['up_to_date'] = parse_version(
            scipy_version) >= parse_version(scipy_min_version)
        scipy_status['version'] = scipy_version
    except ImportError:
        scipy_status['up_to_date'] = False
        scipy_status['version'] = ""
    return scipy_status
项目:operalib    作者:operalib    | 项目源码 | 文件源码
def get_numpy_status():
    """
    Return a dictionary containing a boolean specifying whether NumPy
    is up-to-date, along with the version string (empty string if
    not installed).
    """
    numpy_status = {}
    try:
        import numpy
        numpy_version = numpy.__version__
        numpy_status['up_to_date'] = parse_version(
            numpy_version) >= parse_version(numpy_min_version)
        numpy_status['version'] = numpy_version
    except ImportError:
        numpy_status['up_to_date'] = False
        numpy_status['version'] = ""
    return numpy_status
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:mac-package-build    作者:persepolisdm    | 项目源码 | 文件源码
def test_scipy(pyi_builder):
    pyi_builder.test_source(
        """
        from distutils.version import LooseVersion

        # Test top-level SciPy importability.
        import scipy
        from scipy import *

        # Test hooked SciPy modules.
        import scipy.io.matlab
        import scipy.sparse.csgraph

        # Test problematic SciPy modules.
        import scipy.linalg
        import scipy.signal

        # SciPy >= 0.16 privatized the previously public "scipy.lib" package as
        # "scipy._lib". Since this package is problematic, test its
        # importability regardless of SciPy version.
        if LooseVersion(scipy.__version__) >= LooseVersion('0.16.0'):
            import scipy._lib
        else:
            import scipy.lib
        """)
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def get_scipy_status():
    """
    Returns a dictionary containing a boolean specifying whether SciPy
    is up-to-date, along with the version string (empty string if
    not installed).
    """
    scipy_status = {}
    try:
        import scipy
        scipy_version = scipy.__version__
        scipy_status['up_to_date'] = parse_version(
            scipy_version) >= parse_version(scipy_min_version)
        scipy_status['version'] = scipy_version
    except ImportError:
        scipy_status['up_to_date'] = False
        scipy_status['version'] = ""
    return scipy_status
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def get_numpy_status():
    """
    Returns a dictionary containing a boolean specifying whether NumPy
    is up-to-date, along with the version string (empty string if
    not installed).
    """
    numpy_status = {}
    try:
        import numpy
        numpy_version = numpy.__version__
        numpy_status['up_to_date'] = parse_version(
            numpy_version) >= parse_version(numpy_min_version)
        numpy_status['version'] = numpy_version
    except ImportError:
        numpy_status['up_to_date'] = False
        numpy_status['version'] = ""
    return numpy_status
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
def _show_system_info(self):
        nose = import_nose()

        import numpy
        print("NumPy version %s" % numpy.__version__)
        relaxed_strides = numpy.ones((10, 1), order="C").flags.f_contiguous
        print("NumPy relaxed strides checking option:", relaxed_strides)
        npdir = os.path.dirname(numpy.__file__)
        print("NumPy is installed in %s" % npdir)

        if 'scipy' in self.package_name:
            import scipy
            print("SciPy version %s" % scipy.__version__)
            spdir = os.path.dirname(scipy.__file__)
            print("SciPy is installed in %s" % spdir)

        pyversion = sys.version.replace('\n', '')
        print("Python version %s" % pyversion)
        print("nose version %d.%d.%d" % nose.__versioninfo__)
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_pandas_status():
    try:
        import pandas as pd
        return _check_version(pd.__version__, pandas_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_sklearn_status():
    try:
        import sklearn as sk
        return _check_version(sk.__version__, sklearn_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_numpy_status():
    try:
        import numpy as np
        return _check_version(np.__version__, numpy_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_scipy_status():
    try:
        import scipy as sc
        return _check_version(sc.__version__, scipy_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_h2o_status():
    try:
        import h2o
        return _check_version(h2o.__version__, h2o_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def _numpy_tester():
    if hasattr(np, "__version__") and ".dev0" in np.__version__:
        mode = "develop"
    else:
        mode = "release"
    return NoseTester(raise_warnings=mode, depth=1)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def _numpy_tester():
    if hasattr(np, "__version__") and ".dev0" in np.__version__:
        mode = "develop"
    else:
        mode = "release"
    return NoseTester(raise_warnings=mode, depth=1)
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def check_dependencies():
    try:
        import nose
        logger.debug("\tNose: %s\n" % str(nose.__version__))
    except ImportError:
        raise ImportError("Nose cannot be imported. Are you sure it's "
                          "installed?")
    try:
        import networkx
        logger.debug("\tnetworkx: %s\n" % str(networkx.__version__))
    except ImportError:
        raise ImportError("Networkx cannot be imported. Are you sure it's "
                          "installed?")
    try:
        import pymongo
        logger.debug("\tpymongo: %s\n" % str(pymongo.version))
        from bson.objectid import ObjectId
    except ImportError:
        raise ImportError("Pymongo cannot be imported. Are you sure it's"
                          " installed?")
    try:
        import numpy
        logger.debug("\tnumpy: %s" % str(numpy.__version__))
    except ImportError:
        raise ImportError("Numpy cannot be imported. Are you sure that it's"
                          " installed?")
    try:
        import scipy
        logger.debug("\tscipy: %s" % str(scipy.__version__))
    except ImportError:
        raise ImportError("Scipy cannot be imported. Are you sure that it's"
                          " installed?")
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def check_dependencies():
    try:
        import nose
        logger.debug("\tNose: %s\n" % str(nose.__version__))
    except ImportError:
        raise ImportError("Nose cannot be imported. Are you sure it's "
                          "installed?")
    try:
        import networkx
        logger.debug("\tnetworkx: %s\n" % str(networkx.__version__))
    except ImportError:
        raise ImportError("Networkx cannot be imported. Are you sure it's "
                          "installed?")
    try:
        import pymongo
        logger.debug("\tpymongo: %s\n" % str(pymongo.version))
        from bson.objectid import ObjectId
    except ImportError:
        raise ImportError("Pymongo cannot be imported. Are you sure it's"
                          " installed?")
    try:
        import numpy
        logger.debug("\tnumpy: %s" % str(numpy.__version__))
    except ImportError:
        raise ImportError("Numpy cannot be imported. Are you sure that it's"
                          " installed?")
    try:
        import scipy
        logger.debug("\tscipy: %s" % str(scipy.__version__))
    except ImportError:
        raise ImportError("Scipy cannot be imported. Are you sure that it's"
                          " installed?")
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def check_dependencies():
    try:
        import nose
        logger.debug("\tNose: %s\n" % str(nose.__version__))
    except ImportError:
        raise ImportError("Nose cannot be imported. Are you sure it's "
                          "installed?")
    try:
        import networkx
        logger.debug("\tnetworkx: %s\n" % str(networkx.__version__))
    except ImportError:
        raise ImportError("Networkx cannot be imported. Are you sure it's "
                          "installed?")
    try:
        import pymongo
        logger.debug("\tpymongo: %s\n" % str(pymongo.version))
        from bson.objectid import ObjectId
    except ImportError:
        raise ImportError("Pymongo cannot be imported. Are you sure it's"
                          " installed?")
    try:
        import numpy
        logger.debug("\tnumpy: %s" % str(numpy.__version__))
    except ImportError:
        raise ImportError("Numpy cannot be imported. Are you sure that it's"
                          " installed?")
    try:
        import scipy
        logger.debug("\tscipy: %s" % str(scipy.__version__))
    except ImportError:
        raise ImportError("Scipy cannot be imported. Are you sure that it's"
                          " installed?")
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def _check_modules():
    """Checks whether all dependencies are installed"""

    try:
        import numpy
        if numpy.__version__ < "1.6.0":
            logger.warning("WARNING: You are using a numpy %s < 1.6.0. This "
                           "might not work", numpy.__version__)
    except:
        raise ImportError("Numpy cannot be imported. Are you sure that it's installed?")

    try:
        import scipy
        if scipy.__version__ < "0.12.0":
            logger.warning("WARNING: You are using a scipy %s < 0.12.0. "
                           "This might not work", scipy.__version__)
    except:
        raise ImportError("Scipy cannot be imported. Are you sure that it's installed?")

    try:
        import theano
        logger.debug("\tTheano: %s" % str(theano.__version__))
    except ImportError:
        logger.warning("Theano not found. You might need this to run some "
                       "more complex benchmarks!")

    if 'cuda' not in os.environ['PATH']:
        logger.warning("CUDA not in $PATH")
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_corr_rank(self):
        tm._skip_if_no_scipy()

        import scipy
        import scipy.stats as stats

        # kendall and spearman
        A = tm.makeTimeSeries()
        B = tm.makeTimeSeries()
        A[-5:] = A[:5]
        result = A.corr(B, method='kendall')
        expected = stats.kendalltau(A, B)[0]
        self.assertAlmostEqual(result, expected)

        result = A.corr(B, method='spearman')
        expected = stats.spearmanr(A, B)[0]
        self.assertAlmostEqual(result, expected)

        # these methods got rewritten in 0.8
        if scipy.__version__ < LooseVersion('0.9'):
            raise nose.SkipTest("skipping corr rank because of scipy version "
                                "{0}".format(scipy.__version__))

        # results from R
        A = Series(
            [-0.89926396, 0.94209606, -1.03289164, -0.95445587, 0.76910310, -
             0.06430576, -2.09704447, 0.40660407, -0.89926396, 0.94209606])
        B = Series(
            [-1.01270225, -0.62210117, -1.56895827, 0.59592943, -0.01680292,
             1.17258718, -1.06009347, -0.10222060, -0.89076239, 0.89372375])
        kexp = 0.4319297
        sexp = 0.5853767
        self.assertAlmostEqual(A.corr(B, method='kendall'), kexp)
        self.assertAlmostEqual(A.corr(B, method='spearman'), sexp)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_interp_alt_scipy(self):
        tm._skip_if_no_scipy()
        df = DataFrame({'A': [1, 2, np.nan, 4, 5, np.nan, 7],
                        'C': [1, 2, 3, 5, 8, 13, 21]})
        result = df.interpolate(method='barycentric')
        expected = df.copy()
        expected.ix[2, 'A'] = 3
        expected.ix[5, 'A'] = 6
        assert_frame_equal(result, expected)

        result = df.interpolate(method='barycentric', downcast='infer')
        assert_frame_equal(result, expected.astype(np.int64))

        result = df.interpolate(method='krogh')
        expectedk = df.copy()
        expectedk['A'] = expected['A']
        assert_frame_equal(result, expectedk)

        _skip_if_no_pchip()
        import scipy
        result = df.interpolate(method='pchip')
        expected.ix[2, 'A'] = 3

        if LooseVersion(scipy.__version__) >= '0.17.0':
            expected.ix[5, 'A'] = 6.0
        else:
            expected.ix[5, 'A'] = 6.125

        assert_frame_equal(result, expected)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _skip_if_mpl_1_5():
    import matplotlib
    v = matplotlib.__version__
    if v > LooseVersion('1.4.3') or v[0] == '0':
        import nose
        raise nose.SkipTest("matplotlib 1.5")
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _skip_if_no_xarray():
    try:
        import xarray
    except ImportError:
        import nose
        raise nose.SkipTest("xarray not installed")

    v = xarray.__version__
    if v < LooseVersion('0.7.0'):
        import nose
        raise nose.SkipTest("xarray not version is too low: {0}".format(v))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _incompat_bottleneck_version(method):
    """ skip if we have bottleneck installed
    and its >= 1.0
    as we don't match the nansum/nanprod behavior for all-nan
    ops, see GH9422
    """
    if method not in ['sum','prod']:
        return False
    try:
        import bottleneck as bn
        return bn.__version__ >= LooseVersion('1.0')
    except ImportError:
        return False
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
def __init__(self, package=None, raise_warnings=None):
        if raise_warnings is None and (
                not hasattr(np, '__version__') or '.dev0' in np.__version__):
            raise_warnings = "develop"
        elif raise_warnings is None:
            raise_warnings = "release"

        package_name = None
        if package is None:
            f = sys._getframe(1)
            package_path = f.f_locals.get('__file__', None)
            if package_path is None:
                raise AssertionError
            package_path = os.path.dirname(package_path)
            package_name = f.f_locals.get('__name__', None)
        elif isinstance(package, type(os)):
            package_path = os.path.dirname(package.__file__)
            package_name = getattr(package, '__name__', None)
        else:
            package_path = str(package)

        self.package_path = package_path

        # Find the package name under test; this name is used to limit coverage
        # reporting (if enabled).
        if package_name is None:
            package_name = get_package_name(package_path)
        self.package_name = package_name

        # Set to "release" in constructor in maintenance branches.
        self.raise_warnings = raise_warnings
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
def _numpy_tester():
    if hasattr(np, "__version__") and ".dev0" in np.__version__:
        mode = "develop"
    else:
        mode = "release"
    return NoseTester(raise_warnings=mode, depth=1)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
def _numpy_tester():
    if hasattr(np, "__version__") and ".dev0" in np.__version__:
        mode = "develop"
    else:
        mode = "release"
    return NoseTester(raise_warnings=mode, depth=1)
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
def _fix_fill(fill):
    """Helper to fix bug on old scipy"""
    if LooseVersion(scipy.__version__) < LooseVersion('0.12'):
        fill = fill[:, np.newaxis]
    return fill
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def check_cdist(self, metric, kwargs, D_true):
        if metric == 'canberra' and cmp_version(scipy.__version__, '0.9') <= 0:
            raise SkipTest("Canberra distance incorrect in scipy < 0.9")
        dm = DistanceMetric.get_metric(metric, **kwargs)
        D12 = dm.pairwise(self.X1, self.X2)
        assert_array_almost_equal(D12, D_true)
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def check_pdist(self, metric, kwargs, D_true):
        if metric == 'canberra' and cmp_version(scipy.__version__, '0.9') <= 0:
            raise SkipTest("Canberra distance incorrect in scipy < 0.9")
        dm = DistanceMetric.get_metric(metric, **kwargs)
        D12 = dm.pairwise(self.X1)
        assert_array_almost_equal(D12, D_true)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
def _numpy_tester():
    if hasattr(np, "__version__") and ".dev0" in np.__version__:
        mode = "develop"
    else:
        mode = "release"
    return NoseTester(raise_warnings=mode, depth=1)
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def main(pkl_list, name_list, cut=sys.maxint):
    pickles = plot_util.load_pickles(name_list, pkl_list)
    best_dict, idx_dict, keys = plot_util.get_best_dict(name_list, pickles,
                                                       cut=cut)

    for k in keys:
        sys.stdout.write("%10s: %s experiment(s)\n" % (k, len(best_dict[k])))

    sys.stdout.write("Unpaired t-tests-----------------------------------------------------\n")
    # TODO: replace by itertools
    for idx, k in enumerate(keys):
        if len(keys) > 1:
            for j in keys[idx+1:]:
                t_true, p_true = stats.ttest_ind(best_dict[k], best_dict[j])
                rounded_t_true, rounded_p_true = stats.ttest_ind(numpy.round(best_dict[k], 3),
                                                                 numpy.round(best_dict[j], 3))

                sys.stdout.write("%10s vs %10s\n" % (k, j))
                sys.stdout.write("Standard independent 2 sample test, equal population variance\n")
                sys.stdout.write(" "*24 + "  T: %10.5e, p-value: %10.5e (%5.3f%%) \n" %
                                (t_true, p_true, p_true*100))
                sys.stdout.write("Rounded:                ")
                sys.stdout.write("  T: %10.5e, p-value: %10.5e (%5.3f%%)\n" %
                                (rounded_t_true, rounded_p_true, rounded_p_true*100))
                if tuple(map(int, (scipy.__version__.split(".")))) >= (0, 11, 0):
                    # print scipy.__version__ >= '0.11.0'
                    t_false, p_false = stats.ttest_ind(best_dict[k], best_dict[j], equal_var=False)
                    rounded_t_false, rounded_p_false = stats.ttest_ind(numpy.round(best_dict[k], 3),
                                                                       numpy.round(best_dict[j], 3),
                                                                       equal_var=False)
                    sys.stdout.write("Welch's t-test, no equal population variance\n")
                    sys.stdout.write(" "*24)
                    sys.stdout.write(": T: %10.5e, p-value: %10.5e (%5.3f%%)\n" %
                                    (t_false, p_false, p_false*100))
                    sys.stdout.write("Rounded:                ")
                    sys.stdout.write(": T: %10.5e, p-value: %10.5e (%5.3f%%)\n" %
                                    (rounded_t_false, rounded_p_false, rounded_p_false*100))
                sys.stdout.write("\n")

    sys.stdout.write("Best Value-----------------------------------------------------------\n")
    for k in keys:
        sys.stdout.write("%10s: %10.5f (min: %10.5f, max: %10.5f, std: %5.3f)\n" %
                        (k, float(numpy.mean(best_dict[k])), float(numpy.min(best_dict[k])),
                         numpy.max(best_dict[k]), float(numpy.std(best_dict[k]))))

    sys.stdout.write("Needed Trials--------------------------------------------------------\n")
    for k in keys:
        sys.stdout.write("%10s: %10.5f (min: %10.5f, max: %10.5f, std: %5.3f)\n" %
                        (k, float(numpy.mean(idx_dict[k])), float(numpy.min(idx_dict[k])),
                         numpy.max(idx_dict[k]), float(numpy.std(idx_dict[k]))))

    sys.stdout.write("------------------------------------------------------------------------\n")
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def package_check(pkg_name, version=None, app='pandas', checker=LooseVersion,
                  exc_failed_import=ImportError,
                  exc_failed_check=RuntimeError):
    """Check that the minimal version of the required package is installed.

    Parameters
    ----------
    pkg_name : string
        Name of the required package.
    version : string, optional
        Minimal version number for required package.
    app : string, optional
        Application that is performing the check.  For instance, the
        name of the tutorial being executed that depends on specific
        packages.
    checker : object, optional
        The class that will perform the version checking.  Default is
        distutils.version.LooseVersion.
    exc_failed_import : Exception, optional
        Class of the exception to be thrown if import failed.
    exc_failed_check : Exception, optional
        Class of the exception to be thrown if version check failed.

    Examples
    --------
    package_check('numpy', '1.3')
    package_check('networkx', '1.0', 'tutorial1')

    """

    if app:
        msg = '%s requires %s' % (app, pkg_name)
    else:
        msg = 'module requires %s' % pkg_name
    if version:
        msg += ' with version >= %s' % (version,)
    try:
        mod = __import__(pkg_name)
    except ImportError:
        raise exc_failed_import(msg)
    if not version:
        return
    try:
        have_version = mod.__version__
    except AttributeError:
        raise exc_failed_check('Cannot find version for %s' % pkg_name)
    if checker(have_version) < checker(version):
        raise exc_failed_check(msg)
项目:treetime    作者:neherlab    | 项目源码 | 文件源码
def optimal_t_compressed(self, seq_pair, multiplicity):
        """
        Find the optimal distance between the two sequences
        """

        def _neg_prob(t, seq_pair, multiplicity):
            """
            Probability to observe child given the the parent state, transition
            matrix and the time of evolution (branch length).

            Parameters
            ----------

             t : double
                Branch length (time between sequences)

             parent :  numpy.array
                Parent sequence

             child : numpy.array
                Child sequence

             tm :  GTR
                Model of evolution

            Returns
            -------

             prob : double
                Negative probability of the two given sequences
                to be separated by the time t.
            """
            return -1.0*self.prob_t_compressed(seq_pair, multiplicity,t, return_log=True)

        try:
            from scipy.optimize import minimize_scalar
            opt = minimize_scalar(_neg_prob,
                    bounds=[0,ttconf.MAX_BRANCH_LENGTH],
                    method='bounded',
                    args=(seq_pair, multiplicity), options={'xatol':1e-8})
            new_len = opt["x"]
        except:
            import scipy
            print('legacy scipy', scipy.__version__)
            from scipy.optimize import fminbound
            new_len = fminbound(_neg_prob,
                    0,ttconf.MAX_BRANCH_LENGTH,
                    args=(seq_pair, multiplicity))
            opt={'success':True}

        if new_len > .9 * ttconf.MAX_BRANCH_LENGTH:
            self.logger("WARNING: GTR.optimal_t_compressed -- The branch length seems to be very long!", 4, warn=True)

        if opt["success"] != True:
            # return hamming distance: number of state pairs where state differs/all pairs
            new_len =  np.sum(multiplicity[seq_pair[:,1]!=seq_pair[:,0]])/np.sum(multiplicity)

        return new_len