示例#1
0
def test_list_pseudo_inverse():
    "Test of the pseudo-inverse"

    x = ufloat((1, 0.1))
    y = ufloat((2, 0.1))
    mat = unumpy.matrix([[x, x], [y, 0]])

    # Internal consistency: the inverse and the pseudo-inverse yield
    # the same result on square matrices:
    assert matrices_close(mat.I, unumpy.ulinalg.pinv(mat), 1e-4)
    assert matrices_close(
        unumpy.ulinalg.inv(mat),
        # Support for the optional pinv argument is
        # tested:
        unumpy.ulinalg.pinv(mat, 1e-15),
        1e-4)

    # Non-square matrices:
    x = ufloat((1, 0.1))
    y = ufloat((2, 0.1))
    mat1 = unumpy.matrix([[x, y]])  # "Long" matrix
    mat2 = unumpy.matrix([[x, y], [1, 3 + x], [y, 2 * x]])  # "Tall" matrix

    # Internal consistency:
    assert matrices_close(mat1.I, unumpy.ulinalg.pinv(mat1, 1e-10))
    assert matrices_close(mat2.I, unumpy.ulinalg.pinv(mat2, 1e-8))
示例#2
0
def test_list_pseudo_inverse():
    "Test of the pseudo-inverse"

    x = ufloat((1, 0.1))
    y = ufloat((2, 0.1))
    mat = unumpy.matrix([[x, x], [y, 0]])

    # Internal consistency: the inverse and the pseudo-inverse yield
    # the same result on square matrices:
    assert matrices_close(mat.I, unumpy.ulinalg.pinv(mat), 1e-4)
    assert matrices_close(
        unumpy.ulinalg.inv(mat),
        # Support for the optional pinv argument is
        # tested:
        unumpy.ulinalg.pinv(mat, 1e-15),
        1e-4,
    )

    # Non-square matrices:
    x = ufloat((1, 0.1))
    y = ufloat((2, 0.1))
    mat1 = unumpy.matrix([[x, y]])  # "Long" matrix
    mat2 = unumpy.matrix([[x, y], [1, 3 + x], [y, 2 * x]])  # "Tall" matrix

    # Internal consistency:
    assert matrices_close(mat1.I, unumpy.ulinalg.pinv(mat1, 1e-10))
    assert matrices_close(mat2.I, unumpy.ulinalg.pinv(mat2, 1e-8))
示例#3
0
def test_pseudo_inverse():
    "Tests of the pseudo-inverse"

    # Numerical version of the pseudo-inverse:
    pinv_num = core.wrap_array_func(numpy.linalg.pinv)

    ##########
    # Full rank rectangular matrix:
    m = unumpy.matrix([[ufloat((10, 1)), -3.1],
                       [0, ufloat((3, 0))],
                       [1, -3.1]])

    # Numerical and package (analytical) pseudo-inverses: they must be
    # the same:
    rcond = 1e-8  # Test of the second argument to pinv()
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)

    ##########
    # Example with a non-full rank rectangular matrix:
    vector = [ufloat((10, 1)), -3.1, 11]
    m = unumpy.matrix([vector, vector])
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)
    
    ##########
    # Example with a non-full-rank square matrix:
    m = unumpy.matrix([[ufloat((10, 1)), 0], [3, 0]])
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)
示例#4
0
def test_pseudo_inverse():
    "Tests of the pseudo-inverse"

    # Numerical version of the pseudo-inverse:
    pinv_num = core.wrap_array_func(numpy.linalg.pinv)

    ##########
    # Full rank rectangular matrix:
    m = unumpy.matrix([[ufloat((10, 1)), -3.1],
                       [0, ufloat((3, 0))],
                       [1, -3.1]])

    # Numerical and package (analytical) pseudo-inverses: they must be
    # the same:
    rcond = 1e-8  # Test of the second argument to pinv()
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)

    ##########
    # Example with a non-full rank rectangular matrix:
    vector = [ufloat((10, 1)), -3.1, 11]
    m = unumpy.matrix([vector, vector])
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)

    ##########
    # Example with a non-full-rank square matrix:
    m = unumpy.matrix([[ufloat((10, 1)), 0], [3, 0]])
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)
示例#5
0
def test_wrap_array_func():
    '''
    Test of numpy.wrap_array_func(), with optional arguments and
    keyword arguments.
    '''

    # Function that works with numbers with uncertainties in mat (if
    # mat is an uncertainties.unumpy.matrix):
    def f_unc(mat, *args, **kwargs):
        return mat.I + args[0] * kwargs['factor']

    # Test with optional arguments and keyword arguments:
    def f(mat, *args, **kwargs):
        # This function is wrapped: it should only be called with pure
        # numbers:
        assert not any(isinstance(v, uncert_core.UFloat) for v in mat.flat)
        return f_unc(mat, *args, **kwargs)

    # Wrapped function:
    f_wrapped = core.wrap_array_func(f)

    ##########
    # Full rank rectangular matrix:
    m = unumpy.matrix([[ufloat(10, 1), -3.1], [0, ufloat(3, 0)], [1, -3.1]])

    # Numerical and package (analytical) pseudo-inverses: they must be
    # the same:
    m_f_wrapped = f_wrapped(m, 2, factor=10)
    m_f_unc = f_unc(m, 2, factor=10)

    assert arrays_close(m_f_wrapped, m_f_unc)
示例#6
0
def inertia_components(jay, beta):
    '''Returns the 2D orthogonal inertia tensor.

    When at least three moments of inertia and their axes orientations are
    known relative to a common inertial frame of a planar object, the orthoganl
    moments of inertia relative the frame are computed.

    Parameters
    ----------
    jay : ndarray, shape(n,)
        An array of at least three moments of inertia. (n >= 3)
    beta : ndarray, shape(n,)
        An array of orientation angles corresponding to the moments of inertia
        in jay.

    Returns
    -------
    eye : ndarray, shape(3,)
        Ixx, Ixz, Izz

    '''
    sb = unumpy.sin(beta)
    cb = unumpy.cos(beta)
    betaMat = unumpy.matrix(np.vstack((cb**2, -2 * sb * cb, sb**2)).T)
    eye = np.squeeze(np.asarray(np.dot(betaMat.I, jay)))
    return eye
示例#7
0
def test_wrap_array_func():
    '''
    Test of numpy.wrap_array_func(), with optional arguments and
    keyword arguments.
    '''

    # Function that works with numbers with uncertainties in mat (if
    # mat is an uncertainties.unumpy.matrix):
    def f_unc(mat, *args, **kwargs):
        return mat.I + args[0]*kwargs['factor']

    # Test with optional arguments and keyword arguments:
    def f(mat, *args, **kwargs):
        # This function is wrapped: it should only be called with pure
        # numbers:
        assert not any(isinstance(v, uncert_core.UFloat) for v in mat.flat)
        return f_unc(mat, *args, **kwargs)


    # Wrapped function:
    f_wrapped = core.wrap_array_func(f)

    ##########
    # Full rank rectangular matrix:
    m = unumpy.matrix([[ufloat(10, 1), -3.1],
                       [0, ufloat(3, 0)],
                       [1, -3.1]])

    # Numerical and package (analytical) pseudo-inverses: they must be
    # the same:
    m_f_wrapped = f_wrapped(m, 2, factor=10)
    m_f_unc = f_unc(m, 2, factor=10)

    assert arrays_close(m_f_wrapped, m_f_unc)
示例#8
0
def calculation_prutoky_ze_zony(N, ridici_index, a, P, V, W):
    P_zaloha = P
    P = P[:-1, :]
    k = np.full(len(a), np.nan, dtype=object)

    pocet_neznamych = len(k)
    index1 = [ridici_index] * N
    index2 = []
    for j in np.arange(1, N + 2):
        if j != ridici_index:
            index2.append(j)

    #indexovani prutoku a jejich poloha v vektoru reseni, tj. v podstate takova funkce, mapovani
    prutoky_indexy = pd.DataFrame(np.array([index1, index2]).T,
                                  index=np.arange(1, pocet_neznamych + 1),
                                  columns=['vychozi zona', 'cilova zona'])

    Z = pd.DataFrame(np.zeros((N, pocet_neznamych)),
                     columns=np.arange(1, pocet_neznamych + 1),
                     dtype=object)
    Z.index += 1

    for m in np.arange(1, pocet_neznamych + 1):
        i, j = prutoky_indexy.loc[m]
        if i != j:
            Z.loc[i, m] = -a[i - 1]
            if j <= N:
                Z.loc[j, m] = a[i - 1]
    X = Z
    # print(det(unumpy.nominal_values(X)))

    l = ridici_index - 1
    y = np.full(len(a), np.nan, dtype=object)
    for i in np.arange(len(y)):
        if i == l:
            y[i] = -sum(a[:] * P[:, i]) + prem_kons_Rn * a[i] * V[i] - W[i]
        else:
            # y[i]=a[i]*sum(P[i, :])-sum(a[:l]*P[:l, i])-sum(a[l+1:]*P[l+1:, i])+prem_kons_Rn*a[i]*V[i]-W[i]
            y[i] = a[i] * sum(P[i, :]) - sum(
                a[:] *
                P[:, i]) + a[l] * P[l, i] + prem_kons_Rn * a[i] * V[i] - W[i]

    # X=unumpy.matrix(X)
    # X_inverse=X.I
    # prutoky1=np.dot(X_inverse,y)

    pom = unumpy.matrix(np.dot(X.T, X))
    I2 = pom.I
    prutoky = np.dot(I2, np.dot(X.T, y))  #toto je s nejistotami
    prutoky = np.array(prutoky)[0]

    # res_ols=sm.OLS(unumpy.nominal_values(y), unumpy.nominal_values(X)).fit()
    # print(res_ols.summary())
    # vysledek=solve(unumpy.nominal_values(X), unumpy.nominal_values(y))

    prutoky = np.append(
        prutoky, calculation_infiltrations(P_zaloha, prutoky[-1],
                                           ridici_index))
    return prutoky
示例#9
0
def proc(file):     
    numObj = np.load(file)
    [date, arr] = numObj
    A = unumpy.matrix(arr.flatten())
    # this SHOULD build a new array that's twice as big -
    # but everything is float values instead of strings (yay) and alternates
    # between nominal, std, nominal, std
    A_nom = np.ravel(A.nominal_values)
    outArr = np.reshape(A_nom, arr.shape)
    return [date, outArr]
示例#10
0
def process(file):
    try:
        numObj = np.load(data + '/' + file)
        [date, arr] = numObj
        A = unumpy.matrix(arr.flatten())
        A_nom = np.ravel(A.nominal_values)
        outArr = np.reshape(A_nom, arr.shape)
        return [date, outArr]
    except EOFError:
        return None
示例#11
0
def process(file):
    try:
        # Assumes shape of (X,X,i) for this array - otherwise unumpy array would be unable to cope
        numObj = np.load(file)
        [date, arr] = numObj
        A = unumpy.matrix(arr.flatten())
        A_nom = np.ravel(A.nominal_values)
        outArr = np.reshape(A_nom, arr.shape)
        return [date, outArr]
    except EOFError:
        return None
示例#12
0
def process(file, path_name):
    try:
        numObj = np.load(path_name + '/' + file, encoding='latin1')
        try:
            [date, arr] = numObj
        except ValueError:
            return numObj
        A = unumpy.matrix(arr.flatten())
        A_nom = np.ravel(A.nominal_values)
        outArr = np.reshape(A_nom, arr.shape)
        return [date, outArr]
    except EOFError:
        return None
示例#13
0
def rotation_matrix_from(A, B):
    A = A / unorm(A)
    B = B / unorm(B)

    v = np.cross(A, B)
    s = unorm(v)
    c = np.dot(A, B)

    ssm = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])

    R = np.eye(3) + ssm + np.matmul(ssm, ssm) / (1 + c)
    R = unp.matrix(R)
    return R
示例#14
0
def test_matrix():
    "Matrices of numbers with uncertainties"
    # Matrix inversion:

    # Matrix with a mix of Variable objects and regular
    # Python numbers:

    m = unumpy.matrix([[ufloat((10, 1)), -3.1],
                       [0, ufloat((3, 0))]])
    m_nominal_values = unumpy.nominal_values(m)

    # Test of the nominal_value attribute:
    assert numpy.all(m_nominal_values == m.nominal_values)

    assert type(m[0, 0]) == uncertainties.Variable
示例#15
0
def test_component_extraction():
    "Extracting the nominal values and standard deviations from an array"

    arr = unumpy.uarray(([1, 2], [0.1, 0.2]))

    assert numpy.all(unumpy.nominal_values(arr) == [1, 2])
    assert numpy.all(unumpy.std_devs(arr) == [0.1, 0.2])

    # unumpy matrices, in addition, should have nominal_values that
    # are simply numpy matrices (not unumpy ones, because they have no
    # uncertainties):
    mat = unumpy.matrix(arr)
    assert numpy.all(unumpy.nominal_values(mat) == [1, 2])
    assert numpy.all(unumpy.std_devs(mat) == [0.1, 0.2])
    assert type(unumpy.nominal_values(mat)) == numpy.matrix
示例#16
0
def test_component_extraction():
    "Extracting the nominal values and standard deviations from an array"

    arr = unumpy.uarray(([1, 2], [0.1, 0.2]))

    assert numpy.all(unumpy.nominal_values(arr) == [1, 2])
    assert numpy.all(unumpy.std_devs(arr) == [0.1, 0.2])

    # unumpy matrices, in addition, should have nominal_values that
    # are simply numpy matrices (not unumpy ones, because they have no
    # uncertainties):
    mat = unumpy.matrix(arr)
    assert numpy.all(unumpy.nominal_values(mat) == [1, 2])
    assert numpy.all(unumpy.std_devs(mat) == [0.1, 0.2])
    assert type(unumpy.nominal_values(mat)) == numpy.matrix
示例#17
0
 def GetData(self):
     c = [[],[],[],[],[],[]]
     for row in range(6):
         for col in range(6):
             try:
                 c[row].append(String_to_float(self.item(row,col).text()))
             except:
                 msg = QMessageBox()
                 msg.setIcon(QMessageBox.Information)
                 msg.setText("Check number in row:" + str(row+1)+"column:" + str(col+1))
                 msg.setWindowTitle("MessageBox")
                 msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
                 if msg.exec_()== QMessageBox.Yes:
                     return True
                 else:
                     return False  
     self.c = unumpy.matrix(c)
示例#18
0
def test_matrix():
    "Matrices of numbers with uncertainties"
    # Matrix inversion:

    # Matrix with a mix of Variable objects and regular
    # Python numbers:

    m = unumpy.matrix([[ufloat(10, 1), -3.1], [0, ufloat(3, 0)]])
    m_nominal_values = unumpy.nominal_values(m)

    # Test of the nominal_value attribute:
    assert numpy.all(m_nominal_values == m.nominal_values)

    assert type(m[0, 0]) == uncert_core.Variable

    # Test of scalar multiplication, both sides:
    3 * m
    m * 3
示例#19
0
def test_matrix():
    "Matrices of numbers with uncertainties"
    # Matrix inversion:

    # Matrix with a mix of Variable objects and regular
    # Python numbers:

    m = unumpy.matrix([[ufloat(10, 1), -3.1],
                       [0, ufloat(3, 0)]])
    m_nominal_values = unumpy.nominal_values(m)

    # Test of the nominal_value attribute:
    assert numpy.all(m_nominal_values == m.nominal_values)

    assert type(m[0, 0]) == uncert_core.Variable

    # Test of scalar multiplication, both sides:
    3*m
    m*3
示例#20
0
def process(file):
    try:
        # Assumes shape of (X,X,i) for this array - otherwise unumpy array would be unable to cope
        if args["regex"] is not None:
            p = re.compile(re.escape(str(args["regex"])))
            if p.search(file) is None:
                return None  #We need to think of a way to skip this
        #print(file)
        numObj = np.load(file)
        [date, arr] = numObj
        A = unumpy.matrix(arr.flatten())
        # this SHOULD build a new array that's twice as big -
        # but everything is float values instead of strings (yay) and alternates
        # between nominal, std, nominal, std
        A_nom = np.ravel(A.nominal_values)
        outArr = np.reshape(A_nom, arr.shape)
        return [date, outArr]
    except EOFError:
        return None
示例#21
0
def center_of_mass(slopes, intercepts):
    '''Returns the center of mass relative to the slopes and intercepts
    coordinate system.

    Parameters
    ----------
    slopes : ndarray, shape(n,)
        The slope of every line used to calculate the center of mass.
    intercepts : ndarray, shape(n,)
        The intercept of every line used to calculate the center of mass.

    Returns
    -------
    x : float
        The abscissa of the center of mass.
    y : float
        The ordinate of the center of mass.

    '''
    num = range(len(slopes))
    allComb = cartesian((num, num))
    comb = []
    # remove doubles
    for row in allComb:
        if row[0] != row[1]:
            comb.append(row)
    comb = np.array(comb)

    # initialize the matrix to store the line intersections
    lineX = np.zeros((len(comb), 2), dtype='object')
    # for each line intersection...
    for j, row in enumerate(comb):
        sl = np.array([slopes[row[0]], slopes[row[1]]])
        a = unumpy.matrix(np.vstack((-sl, np.ones((2)))).T)
        b = np.array([intercepts[row[0]], intercepts[row[1]]])
        lineX[j] = np.dot(a.I, b)
    com = np.mean(lineX, axis=0)

    return com[0], com[1]
示例#22
0
def center_of_mass(slopes, intercepts):
    '''Returns the center of mass relative to the slopes and intercepts
    coordinate system.

    Parameters
    ----------
    slopes : ndarray, shape(n,)
        The slope of every line used to calculate the center of mass.
    intercepts : ndarray, shape(n,)
        The intercept of every line used to calculate the center of mass.

    Returns
    -------
    x : float
        The abscissa of the center of mass.
    y : float
        The ordinate of the center of mass.

    '''
    num = range(len(slopes))
    allComb = cartesian((num, num))
    comb = []
    # remove doubles
    for row in allComb:
        if row[0] != row[1]:
            comb.append(row)
    comb = np.array(comb)

    # initialize the matrix to store the line intersections
    lineX = np.zeros((len(comb), 2), dtype='object')
    # for each line intersection...
    for j, row in enumerate(comb):
        sl = np.array([slopes[row[0]], slopes[row[1]]])
        a = unumpy.matrix(np.vstack((-sl, np.ones((2)))).T)
        b = np.array([intercepts[row[0]], intercepts[row[1]]])
        lineX[j] = np.dot(a.I, b)
    com = np.mean(lineX, axis=0)

    return com[0], com[1]
示例#23
0
def test_list_inverse():
    "Test of the inversion of a square matrix"

    mat_list = [[1, 1], [1, 0]]

    # numpy.linalg.inv(mat_list) does calculate the inverse even
    # though mat_list is a list of lists (and not a matrix).  Can
    # ulinalg do the same?  Here is a test:
    mat_list_inv = unumpy.ulinalg.inv(mat_list)

    # More type testing:
    mat_matrix = numpy.asmatrix(mat_list)
    assert isinstance(unumpy.ulinalg.inv(mat_matrix),
                      type(numpy.linalg.inv(mat_matrix)))

    # unumpy.ulinalg should behave in the same way as numpy.linalg,
    # with respect to types:
    mat_list_inv_numpy = numpy.linalg.inv(mat_list)
    assert type(mat_list_inv) == type(mat_list_inv_numpy)

    # The resulting matrix does not have to be a matrix that can
    # handle uncertainties, because the input matrix does not have
    # uncertainties:
    assert not isinstance(mat_list_inv, unumpy.matrix)

    # Individual element check:
    assert isinstance(mat_list_inv[1, 1], float)
    assert mat_list_inv[1, 1] == -1

    x = ufloat((1, 0.1))
    y = ufloat((2, 0.1))
    mat = unumpy.matrix([[x, x], [y, 0]])

    # Internal consistency: ulinalg.inv() must coincide with the
    # unumpy.matrix inverse, for square matrices (.I is the
    # pseudo-inverse, for non-square matrices, but inv() is not).
    assert matrices_close(unumpy.ulinalg.inv(mat), mat.I)
示例#24
0
def test_list_inverse():
    "Test of the inversion of a square matrix"

    mat_list = [[1, 1], [1, 0]]

    # numpy.linalg.inv(mat_list) does calculate the inverse even
    # though mat_list is a list of lists (and not a matrix).  Can
    # ulinalg do the same?  Here is a test:
    mat_list_inv = unumpy.ulinalg.inv(mat_list)

    # More type testing:
    mat_matrix = numpy.asmatrix(mat_list)
    assert isinstance(unumpy.ulinalg.inv(mat_matrix),
                      type(numpy.linalg.inv(mat_matrix)))

    # unumpy.ulinalg should behave in the same way as numpy.linalg,
    # with respect to types:
    mat_list_inv_numpy = numpy.linalg.inv(mat_list)
    assert type(mat_list_inv) == type(mat_list_inv_numpy)

    # The resulting matrix does not have to be a matrix that can
    # handle uncertainties, because the input matrix does not have
    # uncertainties:
    assert not isinstance(mat_list_inv, unumpy.matrix)

    # Individual element check:
    assert isinstance(mat_list_inv[1,1], float)    
    assert mat_list_inv[1,1] == -1

    x = ufloat((1, 0.1))
    y = ufloat((2, 0.1))
    mat = unumpy.matrix([[x, x], [y, 0]])
    
    # Internal consistency: ulinalg.inv() must coincide with the
    # unumpy.matrix inverse, for square matrices (.I is the
    # pseudo-inverse, for non-square matrices, but inv() is not).
    assert matrices_close(unumpy.ulinalg.inv(mat), mat.I)
示例#25
0
d6 = genfromtxt(f6, delimiter=',')

ar8 = unumpy.uarray(d6[:,0],d6[:,1])
ar08 = unumpy.uarray(d1[:,0],d1[:,1])
ar008 = unumpy.uarray(d2[:,0],d2[:,1])
arabs = unumpy.uarray(d3[:,0],d3[:,1])
aragua = unumpy.uarray(d4[:,0],d4[:,1])
arVBC = unumpy.uarray(d5[:,0],d4[:,1])


vol = (ar8 + ar08 + ar008 + aragua + arVBC)
mol = (ar8 * 0.8 + ar08 *0.08 + ar008 *0.008)

conc = mol/vol

mT = unumpy.matrix(conc)
filename = "resconc.csv"
numpy.savetxt(filename, mT, fmt='%r', delimiter='\n')

XB = arabs/(0.757)

mT = unumpy.matrix(XB)
filename = "resXB.csv"
numpy.savetxt(filename, mT, fmt='%r', delimiter='\n')

XHB = 1 - XB

mT = unumpy.matrix(XHB)
filename = "resXHB.csv"
numpy.savetxt(filename, mT, fmt='%r', delimiter='\n')
示例#26
0
def test_inverse():
    "Tests of the matrix inverse"

    m = unumpy.matrix([[ufloat((10, 1)), -3.1],
                       [0, ufloat((3, 0))]])
    m_nominal_values = unumpy.nominal_values(m)

    # "Regular" inverse matrix, when uncertainties are not taken
    # into account:
    m_no_uncert_inv = m_nominal_values.I

    # The matrix inversion should not yield numbers with uncertainties:
    assert m_no_uncert_inv.dtype == numpy.dtype(float)

    # Inverse with uncertainties:
    m_inv_uncert = m.I  # AffineScalarFunc elements
    # The inverse contains uncertainties: it must support custom
    # operations on matrices with uncertainties:
    assert isinstance(m_inv_uncert, unumpy.matrix)
    assert type(m_inv_uncert[0, 0]) == uncertainties.AffineScalarFunc

    # Checks of the numerical values: the diagonal elements of the
    # inverse should be the inverses of the diagonal elements of
    # m (because we started with a triangular matrix):
    assert _numbers_close(1/m_nominal_values[0, 0],
                          m_inv_uncert[0, 0].nominal_value), "Wrong value"
    
    assert _numbers_close(1/m_nominal_values[1, 1],
                          m_inv_uncert[1, 1].nominal_value), "Wrong value"


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

    # Checks of the covariances between elements:
    x = ufloat((10, 1))
    m = unumpy.matrix([[x, x],
                       [0, 3+2*x]])

    m_inverse = m.I
    
    # Check of the properties of the inverse:
    m_double_inverse = m_inverse.I
    # The initial matrix should be recovered, including its
    # derivatives, which define covariances:
    assert _numbers_close(m_double_inverse[0, 0].nominal_value,
                          m[0, 0].nominal_value)
    assert _numbers_close(m_double_inverse[0, 0].std_dev(),
                          m[0, 0].std_dev())

    assert matrices_close(m_double_inverse, m)

    # Partial test:
    assert _derivatives_close(m_double_inverse[0, 0], m[0, 0])
    assert _derivatives_close(m_double_inverse[1, 1], m[1, 1])

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

    # Tests of covariances during the inversion:

    # There are correlations if both the next two derivatives are
    # not zero:
    assert m_inverse[0, 0].derivatives[x]
    assert m_inverse[0, 1].derivatives[x]

    # Correlations between m and m_inverse should create a perfect
    # inversion:
    assert matrices_close(m * m_inverse,  numpy.eye(m.shape[0]))
示例#27
0
U_CU_C, U_CU_H, U_CU_M, U_AL_C, U_AL_H, U_AL_M = np.loadtxt("Messdaten/Messung_Material.txt",
                                                            unpack=True)

# Erstellen der Fehlerbehaftete Spannungen
uU_CU_C = unp.uarray(U_CU_C, len(U_CU_C)*[U_ERR])
uU_CU_H = unp.uarray(U_CU_H, len(U_CU_H)*[U_ERR])
uU_CU_M = unp.uarray(U_CU_M, len(U_CU_M)*[U_ERR])

uU_AL_C = unp.uarray(U_AL_C, len(U_AL_C)*[U_ERR])
uU_AL_H = unp.uarray(U_AL_H, len(U_AL_H)*[U_ERR])
uU_AL_M = unp.uarray(U_AL_M, len(U_AL_M)*[U_ERR])

# Erstellen von 3x3 Matrizen für die Werte von Cu und Al
# Spalte entspricht einer Versuchsreihe, Zeile: Entspricht einer Größe

uU_CU = unp.matrix([uU_CU_C, uU_CU_H, uU_CU_M])
uU_AL = unp.matrix([uU_AL_C, uU_AL_H, uU_AL_M])


# Umrechnung der Spannungen in Temperaturen

uT_CU = TensToTemp(uU_CU)
uT_AL = TensToTemp(uU_AL)

TEST = True
if TEST:
    for i in range(3):
        for j in range(3):
            uT_CU[i,j] = ufloat(noms(uT_CU[i,j]), stds(uT_CU[i,j]))

if TEST:
示例#28
0
def Restframe(string, name):
    dirName = f'{name}'
    dirName = dirName.split('/')[0]

    if not os.path.exists(dirName):
        os.mkdir(dirName)
        print("Directory ", dirName, " Created ")
    else:
        print("Directory ", dirName, " already exists")

    #Creating a line dict from NIST
    line_dict = {
        'CIV_1548': [1548.202, 0.01, r'C \Rn{4} $\lambda$ 1548'],
        'SiIV_1402': [1402.77, 0.1, r'Si \Rn{4} $\lambda$ 1403'],
        'Ly_a': [1215.6701, 0.0021, r'Ly-$\alpha$ $\lambda$ 1216'],
        'CIII_1897': [1897.57, 0.1, r'C \Rn{3} $\lambda$ 1898'],
        'MgII_2796': [2795.528, 0.01, r'Mg \Rn{2} $\lambda$ 2796'],
        'MgII_2803': [2802.705, 0.01, r'Mg \Rn{2} $\lambda$ 2803'],
        'OIII_5007': [5006.843, 0.01, r'O \Rn{3} $\lambda$ 5007'],
        'H_b': [4861.283363, 0.000024, r'H-$\beta$ $\lambda$ 4861'],
        'H_a': [6562.85117, 0.00003, r'H-$\alpha$ $\lambda$ 6563'],
        'SiII_989': [989.87, 0.1, r'Si \Rn{2} $\lambda$ 989'],
        'BeIII_4487': [4487.30, 0.10, r'Be \Rn{3} $\lambda$ 4487'],
        'AlII_1670': [1670.7874, 0.001, r'Al \Rn{2} $\lambda$ 1670'],
        'NV_1239': [1238.8210, 0.01, r'N \Rn{5} $\lambda$ 1239'],
        'CuII_10852': [10852.401, 0.004, r'Cu \Rn{2} $\lambda$ 10852'],
        'CuII_5007': [5006.79978, 0.00015, r'Cu \Rn{2} $\lambda$ 5007'],
        'TiIII_4971': [4971.194, 0.010, r'Ti \Rn{3} $\lambda$ 4971'],
        'ZnII_2026': [2025.4845, 0.001, r'Zn \Rn{2} $\lambda$ 2026'],
        'ZnII_2062': [2062.0011, 0.0010, r'Zn \Rn{2} $\lambda$ 2062'],
        'ZnII_2064': [2064.2266, 0.0010, r'Zn \Rn{2} $\lambda$ 2064'],
        'SiII_1808': [1808.00, 0.10, r'Si \Rn{2} $\lambda$ 1808'],
        'FeII_1611': [1610.9229, 0.0005, r'Fe \Rn{2} $\lambda$ 1611'],
        'FeII_2249': [2249.05864, 0.00011, r'Fe \Rn{2} $\lambda$ 2249'],
        'FeII_2260': [2260.5173, 0.0019, r'Fe \Rn{2} $\lambda$ 2260'],
        'SiII_1526': [1526.734, 0.10, r'Si \Rn{2} $\lambda$ 1526'],
        'FeI_3021': [3021.0725, 0.0003, r'Fe \Rn{2} $\lambda$ 3021'],
        'FeII_2344': [2344.9842, 0.0001, r'Fe \Rn{2} $\lambda$ 2344'],
        'FeII_2374': [2374.6530, 0.0001, r'Fe \Rn{2} $\lambda$ 2374'],
        'FeII_2382': [2382.0373, 0.0001, r'Fe \Rn{2} $\lambda$ 2382'],
        'FeII_2586': [2585.8756, 0.0001, r'Fe \Rn{2} $\lambda$ 2586'],
        'CrII_2026': [2025.6186, 0.0001, r'Cr \Rn{2} $\lambda$ 2026'],
        'CrII_2062': [2061.57673, 0.00007, r'Cr \Rn{2} $\lambda$ 2062'],
        'CrII_2056': [2055.59869, 0.00006, r'Cr \Rn{2} $\lambda$ 2056'],
        'CrII_2066': [2065.50389, 0.00007, r'Cr \Rn{2} $\lambda$ 2066'],
        'MnII_1162': [1162.0150, 0.0001, r'Mn \Rn{2} $\lambda$ 1162'],
        'MnII_1197': [1197.1840, 0.0001, r'Mn \Rn{2} $\lambda$ 1197'],
        'MnII_1199': [1199.3910, 0.0001, r'Mn \Rn{2} $\lambda$ 1199'],
        'MnII_1201': [1201.1180, 0.0001, r'Mn \Rn{2} $\lambda$ 1201'],
        'MnII_2576': [2576.8770, 0.0001, r'Mn \Rn{2} $\lambda$ 2576'],
        'MnII_2594': [2594.4990, 0.0001, r'Mn \Rn{2} $\lambda$ 2594'],
        'MnII_2606': [2606.4630, 0.0001, r'Mn \Rn{2} $\lambda$ 2606'],
        'NiII_1317': [1317.2170, 0.0001, r'Ni \Rn{2} $\lambda$ 1317'],
        'NiII_1345': [1345.8780, 0.0001, r'Ni \Rn{2} $\lambda$ 1345'],
        'NiII_1370': [1370.1320, 0.0001, r'Ni \Rn{2} $\lambda$ 1370'],
        'NiII_1393': [1393.3240, 0.0001, r'Ni \Rn{2} $\lambda$ 1393'],
        'NiII_1454': [1454.8420, 0.0001, r'Ni \Rn{2} $\lambda$ 1454'],
        'NiII_1502': [1502.1480, 0.0001, r'Ni \Rn{2} $\lambda$ 1502'],
        'NiII_1703': [1703.4050, 0.0001, r'Ni \Rn{2} $\lambda$ 1703'],
        'NiII_1709': [1709.6000, 0.0001, r'Ni \Rn{2} $\lambda$ 1709'],
        'NiII_1741': [1741.5490, 0.0001, r'Ni \Rn{2} $\lambda$ 1741'],
        'NiII_1751': [1751.9100, 0.0001, r'Ni \Rn{2} $\lambda$ 1751'],
        'NiII_1773': [1773.9490, 0.0001, r'Ni \Rn{2} $\lambda$ 1773'],
        'NiII_1804': [1804.4730, 0.0001, r'Ni \Rn{2} $\lambda$ 1804'],
        'CrII_1058': [1058.7320, 0.0001, r'Cr \Rn{2} $\lambda$ 1058'],
        'CrII_1059': [1059.7320, 0.0001, r'Cr \Rn{2} $\lambda$ 1059'],
        'CrII_1064': [1064.1240, 0.0001, r'Cr \Rn{2} $\lambda$ 1064'],
        'CrII_1066': [1066.7760, 0.0001, r'Cr \Rn{2} $\lambda$ 1066'],
        'SiII_1020': [1020.6989, 0.1, r'Si \Rn{2} $\lambda$ 1020'],
        'SiIV_1062': [1062.66, 0.1, r'Si \Rn{4} $\lambda$ 1062'],
        'SiII_1190': [1190.4158, 0.1, r'Si \Rn{2} $\lambda$ 1190'],
        'SiII_1193': [1193.2897, 0.1, r'Si \Rn{2} $\lambda$ 1193'],
        'SiIII_1206': [1206.5000, 0.1, r'Si \Rn{3} $\lambda$ 1206'],
        'SiII_1260': [1260.4221, 0.1, r'Si \Rn{2} $\lambda$ 1260'],
        'SiII_1304': [1304.3702, 0.1, r'Si \Rn{2} $\lambda$ 1304'],
        'SiI_1554': [1554.2960, 0.1, r'Si \Rn{1} $\lambda$ 1554'],
        'SiI_1562': [1562.0020, 0.1, r'Si \Rn{1} $\lambda$ 1562'],
        'SiI_1625': [1625.7051, 0.1, r'Si \Rn{1} $\lambda$ 1625'],
        'SiI_1631': [1631.1705, 0.1, r'Si \Rn{1} $\lambda$ 1631'],
        'SiIV_1693': [1693.2935, 0.1, r'Si \Rn{4} $\lambda$ 1693'],
        'SiI_2515': [2515.0725, 0.1, r'Si \Rn{1} $\lambda$ 2515'],
        'SiI_2208': [2208.6665, 0.1, r'Si \Rn{1} $\lambda$ 2208'],
        'SiIII_1892': [1892.0300, 0.1, r'Si \Rn{3} $\lambda$ 1892'],
        'SiI_1845': [1845.5202, 0.1, r'Si \Rn{1} $\lambda$ 1845'],
        'FeII_935': [935.5175, 0.001, r'Fe \Rn{2} $\lambda$ 935'],
        'FeII_937': [937.6520, 0.001, r'Fe \Rn{2} $\lambda$ 937'],
        'FeII_1055': [1055.2617, 0.001, r'Fe \Rn{2} $\lambda$ 1055'],
        'FeII_1062': [1062.1520, 0.001, r'Fe \Rn{2} $\lambda$ 1062'],
        'FeII_1081': [1081.8750, 0.001, r'Fe \Rn{2} $\lambda$ 1081'],
        'FeII_1083': [1083.4200, 0.001, r'Fe \Rn{2} $\lambda$ 1083'],
        'FeII_1096': [1096.8769, 0.001, r'Fe \Rn{2} $\lambda$ 1096'],
        'FeIII_1122': [1122.5360, 0.001, r'Fe \Rn{3} $\lambda$ 1122'],
        'FeII_1144': [1144.9379, 0.001, r'Fe \Rn{2} $\lambda$ 1144'],
        'FeII_1260': [1260.5330, 0.001, r'Fe \Rn{2} $\lambda$ 1260'],
        'FeII_1608': [1608.4511, 0.001, r'Fe \Rn{2} $\lambda$ 1608'],
        'FeII_1611': [1611.2005, 0.001, r'Fe \Rn{2} $\lambda$ 1611'],
        'FeI_1934': [1934.5351, 0.001, r'Fe \Rn{1} $\lambda$ 1934'],
        'FeI_1937': [1937.2682, 0.001, r'Fe \Rn{1} $\lambda$ 1937'],
        'FeI_2167': [2167.4531, 0.001, r'Fe \Rn{1} $\lambda$ 2167'],
        'FeII_2344': [2344.2140, 0.001, r'Fe \Rn{2} $\lambda$ 2344'],
        'FeII_2382': [2382.7650, 0.001, r'Fe \Rn{2} $\lambda$ 2382'],
        'FeII_2484': [2484.0211, 0.001, r'Fe \Rn{2} $\lambda$ 2484'],
        'FeI_2523': [2523.6083, 0.001, r'Fe \Rn{1} $\lambda$ 2523'],
        'FeII_2600': [2600, 0.001, r'Fe \Rn{2} $\lambda$ 2600'],
        'FeI_2719': [2719.8331, 0.001, r'Fe \Rn{1} $\lambda$ 2719'],
        'FeI_3021': [3021.5189, 0.001, r'Fe \Rn{1} $\lambda$ 3021'],
        'AlIII_1854': [1854.7164, 0.1, r'Al \Rn{3} $\lambda$ 1854'],
        'AlIII_1862': [1862.7895, 0.1, r'Al \Rn{3} $\lambda$ 1862'],
        'MgI_2852': [2852.1370, 0.1, r'Mg \Rn{1} $\lambda$ 2852'],
        'MgI_2026': [2026.4768, 0.1, r'Mg \Rn{1} $\lambda$ 2026'],
        'PII_1152': [1152.8180, 0.001, r'P \Rn{2} $\lambda$ 1152'],
        'CuII_1358': [1358.7730, 0.001, r'Cu \Rn{2} $\lambda$ 1358']
    }
    time_signature = datetime.now().strftime("%m%d-%H%M")
    name = name.replace('.txt', '')
    output_name = f'Final_table_{time_signature}_{dirName}.txt'

    numify = lambda x: float(''.join(
        char for char in x if char.isdigit() or char == "." or char == "-"))

    tex_table = string

    tex_document = r"""
\begin{table}[H] 
\begin{tabular}{cccccccc}
Transition & EW$_r$ [Å] & Redshift\\
\hline
"""

    approx_z = float(input('What is the approximate redshift?'))

    lines = tex_table.split(r"\\")[0:-1]

    data = []

    text = []

    # Interactive way of categorising the lines
    for line in lines:
        [_, wave, eq, _] = line.strip().split("&")
        [wave, wave_err] = wave.split(r"\pm")
        [eq, eq_err] = eq.split(r"\pm")

        line_exp = unc.ufloat(numify(wave), numify(wave_err)) / (1 + approx_z)
        ordered_dict = collections.OrderedDict(
            sorted(line_dict.items(), key=lambda v: v[1]))
        line_true = input(
            f'\n What is this line {line_exp}? Please choose from: \n {ordered_dict.keys()}: '
        )

        data.append([
            unc.ufloat(numify(wave), numify(wave_err)),
            unc.ufloat(numify(eq), numify(eq_err)),
            unc.ufloat(line_dict[f'{line_true}'][0],
                       line_dict[f'{line_true}'][1])
        ])

        text.append(line_dict[f'{line_true}'][2])

    data = unumpy.matrix(data)

    z = (data[:, 0] / data[:, 2] - 1)

    # The errors and their contribution to the weighted redshift avarage
    z_avg = np.mean(z)
    var = sum(pow(i - z_avg, 2) for i in z) / len(z)
    var = var[0, 0]
    z_avg_std = math.sqrt(var.nominal_value)

    ew_r = (data[:, 1] / (z_avg + 1))

    # Creating a LaTeX table for the results

    tex_begin = "\\noindent The weighted avarage of the redshift is $z = {:.1uL}$".format(
        z_avg)

    for i in range(len(z)):
        eq_value = ew_r[i, 0]

        z_value = z[i, 0]

        tex_document += " {0} & ${1:.1uL}$ & ${2:.1uL}$ \\\\".format(
            text[i], eq_value, z_value)

    tex_footer = r"""
\hline
\end{tabular}
\end{table}
"""
    output_name = dirName + "/" + output_name
    with open(output_name, "w+") as outfile:
        outfile.write(tex_begin + tex_document + tex_footer)

    # When the file is saved, it is also printed and inserted in the clip board
    print(tex_begin + tex_document + tex_footer)
    copy(tex_begin + tex_document + tex_footer)
示例#29
0
            Z_s.loc[(k, i), m] = -C.loc[k, i].s
            if j <= N:
                Z.loc[(k, j), m] = C.loc[k, i]
                Z_n.loc[(k, j), m] = C.loc[k, i].n
                Z_s.loc[(k, j), m] = C.loc[k, i].s

#nalezeni prutoku metodou nejmensich ctvercu
X = Z_n
y = -M

X2 = Z
y2 = -M

#rucne
I1 = np.linalg.inv(np.dot(X.T, X))
pom = unumpy.matrix(np.dot(X2.T, X2))
I2 = pom.I

prutoky1 = np.dot(I1, np.dot(X.T, y))  #bez nejistot
prutoky2 = np.dot(I2, np.dot(X2.T, y))  #toto je s nejistotami
prutoky2 = np.array(prutoky2)[0]

#scipy lsq_linear
# prutoky2=lsq_linear(X, y)
# prutoky2_n=prutoky2.x

#statsmodel
res_ols = sm.OLS(y, X).fit()
print(res_ols.summary())
prutoky3_n = res_ols.params
# prutoky3_s=res_ols.bse
示例#30
0
def test_inverse():
    "Tests of the matrix inverse"

    m = unumpy.matrix([[ufloat((10, 1)), -3.1],
                       [0, ufloat((3, 0))]])
    m_nominal_values = unumpy.nominal_values(m)

    # "Regular" inverse matrix, when uncertainties are not taken
    # into account:
    m_no_uncert_inv = m_nominal_values.I

    # The matrix inversion should not yield numbers with uncertainties:
    assert m_no_uncert_inv.dtype == numpy.dtype(float)

    # Inverse with uncertainties:
    m_inv_uncert = m.I  # AffineScalarFunc elements
    # The inverse contains uncertainties: it must support custom
    # operations on matrices with uncertainties:
    assert isinstance(m_inv_uncert, unumpy.matrix)
    assert type(m_inv_uncert[0, 0]) == uncertainties.AffineScalarFunc

    # Checks of the numerical values: the diagonal elements of the
    # inverse should be the inverses of the diagonal elements of
    # m (because we started with a triangular matrix):
    assert _numbers_close(1/m_nominal_values[0, 0],
                          m_inv_uncert[0, 0].nominal_value), "Wrong value"

    assert _numbers_close(1/m_nominal_values[1, 1],
                          m_inv_uncert[1, 1].nominal_value), "Wrong value"


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

    # Checks of the covariances between elements:
    x = ufloat((10, 1))
    m = unumpy.matrix([[x, x],
                       [0, 3+2*x]])

    m_inverse = m.I

    # Check of the properties of the inverse:
    m_double_inverse = m_inverse.I
    # The initial matrix should be recovered, including its
    # derivatives, which define covariances:
    assert _numbers_close(m_double_inverse[0, 0].nominal_value,
                          m[0, 0].nominal_value)
    assert _numbers_close(m_double_inverse[0, 0].std_dev(),
                          m[0, 0].std_dev())

    assert matrices_close(m_double_inverse, m)

    # Partial test:
    assert _derivatives_close(m_double_inverse[0, 0], m[0, 0])
    assert _derivatives_close(m_double_inverse[1, 1], m[1, 1])

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

    # Tests of covariances during the inversion:

    # There are correlations if both the next two derivatives are
    # not zero:
    assert m_inverse[0, 0].derivatives[x]
    assert m_inverse[0, 1].derivatives[x]

    # Correlations between m and m_inverse should create a perfect
    # inversion:
    assert matrices_close(m * m_inverse,  numpy.eye(m.shape[0]))
示例#31
0
d5 = genfromtxt(f5, delimiter=',')
d6 = genfromtxt(f6, delimiter=',')

ar8 = unumpy.uarray(d6[:, 0], d6[:, 1])
ar08 = unumpy.uarray(d1[:, 0], d1[:, 1])
ar008 = unumpy.uarray(d2[:, 0], d2[:, 1])
arabs = unumpy.uarray(d3[:, 0], d3[:, 1])
aragua = unumpy.uarray(d4[:, 0], d4[:, 1])
arVBC = unumpy.uarray(d5[:, 0], d4[:, 1])

vol = (ar8 + ar08 + ar008 + aragua + arVBC)
mol = (ar8 * 0.8 + ar08 * 0.08 + ar008 * 0.008)

conc = mol / vol

mT = unumpy.matrix(conc)
filename = "resconc.csv"
numpy.savetxt(filename, mT, fmt='%r', delimiter='\n')

XB = arabs / (0.757)

mT = unumpy.matrix(XB)
filename = "resXB.csv"
numpy.savetxt(filename, mT, fmt='%r', delimiter='\n')

XHB = 1 - XB

mT = unumpy.matrix(XHB)
filename = "resXHB.csv"
numpy.savetxt(filename, mT, fmt='%r', delimiter='\n')
示例#32
0
def calculation_OAR_rucne(K, Q):
    K = K[:, :-1]
    K = unumpy.matrix(K)
    K_inverse = K.I
    return -np.dot(K_inverse, Q)
示例#33
0
U_CU_C, U_CU_H, U_CU_M, U_AL_C, U_AL_H, U_AL_M = np.loadtxt(
    "Messdaten/Messung_Material.txt", unpack=True)

# Erstellen der Fehlerbehaftete Spannungen
uU_CU_C = unp.uarray(U_CU_C, len(U_CU_C) * [U_ERR])
uU_CU_H = unp.uarray(U_CU_H, len(U_CU_H) * [U_ERR])
uU_CU_M = unp.uarray(U_CU_M, len(U_CU_M) * [U_ERR])

uU_AL_C = unp.uarray(U_AL_C, len(U_AL_C) * [U_ERR])
uU_AL_H = unp.uarray(U_AL_H, len(U_AL_H) * [U_ERR])
uU_AL_M = unp.uarray(U_AL_M, len(U_AL_M) * [U_ERR])

# Erstellen von 3x3 Matrizen für die Werte von Cu und Al
# Spalte entspricht einer Versuchsreihe, Zeile: Entspricht einer Größe

uU_CU = unp.matrix([uU_CU_C, uU_CU_H, uU_CU_M])
uU_AL = unp.matrix([uU_AL_C, uU_AL_H, uU_AL_M])

# Umrechnung der Spannungen in Temperaturen

uT_CU = TensToTemp(uU_CU)
uT_AL = TensToTemp(uU_AL)

TEST = True
if TEST:
    for i in range(3):
        for j in range(3):
            uT_CU[i, j] = ufloat(noms(uT_CU[i, j]), stds(uT_CU[i, j]))

if TEST:
    for i in range(3):