Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
实现python时出错';s测试函数_Python_Numpy_Pytest - Fatal编程技术网

实现python时出错';s测试函数

实现python时出错';s测试函数,python,numpy,pytest,Python,Numpy,Pytest,虽然在尝试pytest.main(“-xgausselimination.py”)时无法有效地测试该代码,但该代码已在类中显示 我收到以下错误消息: TypeError:args参数应为字符串的列表或元组,得到:'-x GaussElimination.py'(类型:) 这是我第一次使用pytest,我不确定使用的参数是否正确,但这就是我们在课堂上看到的,它当时起作用了。我也试着上网看看,但找不到简单的例子 谢谢 Trypytest.main([“-x”,“GaussElimination.py

虽然在尝试
pytest.main(“-xgausselimination.py”)
时无法有效地测试该代码,但该代码已在类中显示

我收到以下错误消息:

TypeError:
args
参数应为字符串的列表或元组,得到:'-x GaussElimination.py'(类型:)

这是我第一次使用
pytest
,我不确定使用的参数是否正确,但这就是我们在课堂上看到的,它当时起作用了。我也试着上网看看,但找不到简单的例子

谢谢

Try
pytest.main([“-x”,“GaussElimination.py]”)

如果你检查以下参考链接,你就会明白它为什么起作用

参考链接:


引用链接:“您可以传入选项和参数:
pytest.main([“-x”,“mytestdir”])

尝试
pytest.main(“-x GaussElimination.py)”)
。包含单个元素的元组是用Python编写的
(e,)
。我已经尝试过,现在返回:
错误:用法:GaussElimination.py[options][file\u或\u dir][file\u或\u dir][…]GaussElimination.py:错误:参数-x/--exitfirst:忽略显式参数“GaussElimination.py”
。谢谢你的建议,仔细想想
pytest.main([“-x”,“GaussElimination.py]”)
@Alper谢谢你的建议!你有没有理由认为这会奏效?它需要是数组/列表形状,因为正在使用两个字符串参数?我使用了“help()函数,它检索了
main(args=None,plugins=None)
,其中args需要命令行参数列表。试图理解逻辑。非常感谢!我看到了此参考,但直到最后才阅读它!这很有意义!
import numpy
import numpy.linalg

def MyBackSubstitution(A, b):
    """
    Solve the upper triangular linear system A x = b.

    Parameters
    ----------

    A : array of float
        real square matrix
    b : vector of float
        real vector

    Returns
    -------

    x : vector of float
        solution

    Notes
    -----

    Simplified method with limited error checking.
    """

    assert(numpy.all(numpy.isreal(b))), "b must be real"
    assert(numpy.all(numpy.isfinite(b))), "b must be finite"
    assert(numpy.ndim(b) == 1), "b must be a vector"
    n = len(b)

    assert(numpy.all(numpy.isreal(A))), "A must be real"
    assert(numpy.all(numpy.isfinite(A))), "A must be finite"
    assert(numpy.ndim(A) == 2), "A must be a matrix"
    assert(A.shape == (n, n)), "A must be a square matrix compatible with b"

    x = numpy.zeros_like(b)

    for i in range(n-1,-1,-1):
        x[i] = b[i] / A[i, i]
        for k in range(i+1,n):
            x[i] -=  A[i, k] * x[k] / A[i, i]

    return x

def MyGaussianElimination(A, b):
    """
    Solve the linear system A x = b using Gaussian Elimination without pivoting.

    Parameters
    ----------

    A : array of float
        real square matrix
    b : vector of float
        real vector

    Returns
    -------

    x : vector of float
        solution

    Notes
    -----

    Simplified method with limited error checking.
    """

    # Error checking here
    assert(numpy.all(numpy.isreal(b))), "b must be real"
    assert(numpy.all(numpy.isfinite(b))), "b must be finite"
    assert(numpy.ndim(b) == 1), "b must be a vector"
    n = len(b)

    assert(numpy.all(numpy.isreal(A))), "A must be real"
    assert(numpy.all(numpy.isfinite(A))), "A must be finite"
    assert(numpy.ndim(A) == 2), "A must be a matrix"
    assert(A.shape == (n, n)), "A must be a square matrix compatible with b"

    # Construct augmented matrix. Slightly tedious.
    aug = numpy.hstack((A, numpy.reshape(b, [len(b), 1])))

    # Put the augmented matrix in triangular form.
    #assert(False), "Code needed here"

    for i in range(n):
        assert(numpy.abs(aug[i,i]) > 1e-20), "Diagonal element zero!"
        for k in range(i+1,n):
            pivot = aug[k,i] / aug[i,i]
            aug[k,:] -= pivot * aug[i,:]

    # Solve using back substitution.
    x = MyBackSubstitution(aug[:, :-1], aug[:, -1])

    return x


def MyGaussianEliminationWithPivoting(A, b):
    """
    Solve the linear system A x = b using Gaussian Elimination with pivoting.

    Parameters
    ----------

    A : array of float
        real square matrix
    b : vector of float
        real vector

    Returns
    -------

    x : vector of float
        solution

    Notes
    -----

    Simplified method with limited error checking.
    """

    # Error checking here
    assert(numpy.all(numpy.isreal(b))), "b must be real"
    assert(numpy.all(numpy.isfinite(b))), "b must be finite"
    assert(numpy.ndim(b) == 1), "b must be a vector"
    n = len(b)

    assert(numpy.all(numpy.isreal(A))), "A must be real"
    assert(numpy.all(numpy.isfinite(A))), "A must be finite"
    assert(numpy.ndim(A) == 2), "A must be a matrix"
    assert(A.shape == (n, n)), "A must be a square matrix compatible with b"

    # Construct augmented matrix. Slightly tedious.
    aug = numpy.hstack((A, numpy.reshape(b, [len(b), 1])))

    # Put the augmented matrix in triangular form.
    #assert(False), "Code needed here"

    for i in range(n):
        # Find the location of the pivot
        ind = numpy.argmax(numpy.abs(aug[i:, i]))
        if ind != i:
            # One liner to swap the rows; think carefully!
            aug[[i,ind+i],:] = aug[[ind+i, i],:]
        for k in range(i+1,n):
            pivot = aug[k,i] / aug[i,i]
            aug[k,:] -= pivot * aug[i,:]

    # Solve using back substitution.
    x = MyBackSubstitution(aug[:, :-1], aug[:, -1])

    return x

# What follows are testing functions to validate the code   
import pytest

def test_diagonal():
    A = numpy.eye(2)
    b = numpy.array([1.0, 2.0])
    x_my = MyGaussianElimination(A, b)
    check = numpy.allclose(x_my, b)
    assert check

def test_triangular():
    A = numpy.array([[1.0, 2.0], [0.0, 1.0]])
    b = numpy.array([4.0, 1.0])
    x_my = MyGaussianElimination(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

def test_full():
    A = numpy.array([[1.0, 2.0], [3.0, 4.0]])
    b = numpy.array([5.0, 6.0])
    x_my = MyGaussianElimination(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

def test_threebythree():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 6.0]])
    b = numpy.array([4.0, 10.0, 15.0])
    x_my = MyGaussianElimination(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

def test_incompatible():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 6.0]])
    b = numpy.array([4.0, 10.0])
    with pytest.raises(AssertionError):
        MyGaussianElimination(A, b)

def test_input():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 6.0]])
    b = "dog"
    with pytest.raises(AssertionError):
        MyGaussianElimination(A, b)

def test_singular():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 5.0]])
    b = numpy.array([4.0, 10.0])
    with pytest.raises(AssertionError):
        MyGaussianElimination(A, b)

def test_finite():
    A = numpy.array([[1.0, 1.0, 1.0], [0.0, 0.0, 2.0], [0.0, 1.0, 1.0]])
    b = numpy.array([1.0, 1.0, 2.0])
    with pytest.raises(AssertionError):
        MyGaussianElimination(A, b)

def test_needs_pivoting():
    A = numpy.array([[1.0e-20, 1.0], [1.0, 1.0]])
    b = numpy.array([1.0, 2.0])
    with pytest.raises(AssertionError):
        MyGaussianElimination(A, b)

# Test with pivoting

def test_diagonal_pivoting():
    A = numpy.eye(2)
    b = numpy.array([1.0, 2.0])
    x_my = MyGaussianEliminationWithPivoting(A, b)
    check = numpy.allclose(x_my, b)
    assert check

def test_triangular_pivoting():
    A = numpy.array([[1.0, 2.0], [0.0, 1.0]])
    b = numpy.array([4.0, 1.0])
    x_my = MyGaussianEliminationWithPivoting(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

def test_full_pivoting():
    A = numpy.array([[1.0, 2.0], [3.0, 4.0]])
    b = numpy.array([5.0, 6.0])
    x_my = MyGaussianEliminationWithPivoting(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

def test_threebythree_pivoting():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 6.0]])
    b = numpy.array([4.0, 10.0, 15.0])
    x_my = MyGaussianEliminationWithPivoting(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

def test_incompatible_pivoting():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 6.0]])
    b = numpy.array([4.0, 10.0])
    with pytest.raises(AssertionError):
        MyGaussianEliminationWithPivoting(A, b)

def test_input_pivoting():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 6.0]])
    b = "dog"
    with pytest.raises(AssertionError):
        MyGaussianEliminationWithPivoting(A, b)

def test_singular_pivoting():
    A = numpy.array([[3.0, 0.0, 1.0], [6.0, 2.0, 4.0], [9.0, 2.0, 5.0]])
    b = numpy.array([4.0, 10.0])
    with pytest.raises(AssertionError):
        MyGaussianEliminationWithPivoting(A, b)

def test_finite_pivoting():
    A = numpy.array([[1.0, 1.0, 1.0], [0.0, 0.0, 2.0], [0.0, 1.0, 1.0]])
    b = numpy.array([1.0, 1.0, 2.0])
    with pytest.raises(AssertionError):
        MyGaussianEliminationWithPivoting(A, b)

def test_needs_pivoting_pivoting():
    A = numpy.array([[1.0e-20, 1.0], [1.0, 1.0]])
    b = numpy.array([1.0, 2.0])
    x_my = MyGaussianEliminationWithPivoting(A, b)
    x_exact = numpy.linalg.solve(A, b)
    check = numpy.allclose(x_my, x_exact)
    assert check

# Run all the tests
pytest.main("-x GaussElimination.py")