def __init__(self, inputs, hidden, outputs):
        self.num_input_nodes = inputs
        self.num_hidden_nodes = hidden
        self.num_output_nodes = outputs

        self.weights_i = Matrix(self.num_hidden_nodes, self.num_input_nodes,
                                True)
        self.weights_h = Matrix(self.num_output_nodes, self.num_hidden_nodes,
                                True)
        self.bias_i = Matrix(self.num_hidden_nodes, 1, True)
        self.bias_h = Matrix(self.num_output_nodes, 1, True)
Exemple #2
0
 def __init__(self):
     self.verts = Matrix([
         [0.5, 0.5, 0.5, 0.5],  #0
         [0.5, 0.5, 0.5, -0.5],  #1
         [0.5, 0.5, -0.5, 0.5],  #2
         [0.5, 0.5, -0.5, -0.5],  #3
         [0.5, -0.5, 0.5, 0.5],  #4
         [0.5, -0.5, 0.5, -0.5],  #5
         [0.5, -0.5, -0.5, 0.5],  #6
         [0.5, -0.5, -0.5, -0.5],  #7
         [-0.5, 0.5, 0.5, 0.5],  #8
         [-0.5, 0.5, 0.5, -0.5],  #9
         [-0.5, 0.5, -0.5, 0.5],  #10
         [-0.5, 0.5, -0.5, -0.5],  #11
         [-0.5, -0.5, 0.5, 0.5],  #12
         [-0.5, -0.5, 0.5, -0.5],  #13
         [-0.5, -0.5, -0.5, 0.5],  #14
         [-0.5, -0.5, -0.5, -0.5]  #15
     ])
     self.center = [0, 0, 0, 0]
     self.edges = [[0, 1], [0, 2], [0, 4], [0, 8], [1, 3], [1, 5], [1, 9],
                   [2, 3], [2, 6], [2, 10], [3, 7], [3, 11], [4, 5], [4, 6],
                   [4, 12], [5, 7], [5, 13], [6, 7], [6, 14], [7,
                                                               15], [8, 9],
                   [8, 10], [8, 12], [9, 11], [9, 13], [10, 11], [10, 14],
                   [11, 15], [12, 13], [12, 14], [13, 15], [14, 15]]
     # it's wrong but unnecessary
     self.faces = [[1, 2, 3, 4]]
Exemple #3
0
def translationMatrix (x, y = 0, z = 0):
  if type(x) is Vector:
    y = x[1]
    z = x[2]
    x = x[0]
  return Matrix([[1, 0, 0, x],
                 [0, 1, 0, y],
                 [0, 0, 1, z],
                 [0, 0, 0, 1]])
Exemple #4
0
def rotate(points, axis, angle, hand="right"):
    """Takes a set of coordinates and rotates them around one of the axes by a
    specified angle. The rotation performed is right-handed, unless specified
    otherwise.

    The points must be a list (or tuple, or any collection) of
    coordinates in the form ``(x, y, z)``, *or* a list (etc.) of objects with
    x(), y() and z() methods.

    An example would be ``rotate([(1, 1, 1), (2, 2, 2)], "x", 45)``.

    :param points: A collection of (x, y, z) coordinates or appropriate objects.
    :param str axis: The axis to rotate around. Accepted values are `"x"`,\
    `"y"` or `"z"`.
    :param number angle: The angle in degrees to rotate by.
    :param str hand: specifies whether the rotation should be right-handed or\
    left-handed. The deafult is 'right'.
    :returns: The rotated coordinates."""

    if not is_numeric:
        raise TypeError("angle must be numeric, not '%s'" % str(angle))
    if not isinstance(hand, str):
        raise TypeError("hand must be str, not '%s'" % str(hand))
    elif hand not in ("left", "right"):
        raise ValueError("hand must be 'left' or 'right', not %s" % hand)
    elif hand == "left":
        angle = -angle
    angle = radians(angle)
    points = [create_vertex(*point) for point in points]
    matrix = None
    if axis == "x":
        matrix = Matrix((1, 0, 0), (0, cos(angle), -sin(angle)),
                        (0, sin(angle), cos(angle)))
    elif axis == "y":
        matrix = Matrix((cos(angle), 0, sin(angle)), (0, 1, 0),
                        (-sin(angle), 0, cos(angle)))
    elif axis == "z":
        matrix = Matrix((cos(angle), -sin(angle), 0),
                        (sin(angle), cos(angle), 0), (0, 0, 1))
    else:
        raise ValueError("axis can only be 'x', 'y' or 'z', not %s" % axis)
    new_points = [matrix * point for point in points]
    return tuple([point.columns()[0] for point in new_points])
Exemple #5
0
 def __init__(self):
     self.verts = Matrix([[0.5, 0.5, 0.5], [0.5, 0.5, -0.5],
                          [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5],
                          [0.5, -0.5, -0.5], [-0.5, -0.5, 0.5],
                          [-0.5, 0.5, -0.5], [-0.5, -0.5, -0.5]])
     self.center = [0, 0, 0]
     self.edges = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 6], [2, 4], [2, 5],
                   [3, 5], [3, 6], [4, 7], [5, 7], [6, 7]]
     # should faces point to edges or vertices? I feel like vertices would be easier
     self.faces = [[0, 1, 3, 6], [0, 1, 2, 4], [0, 2, 3, 5], [1, 4, 6, 7],
                   [2, 4, 5, 7], [3, 5, 6, 7]]
Exemple #6
0
    def __init__(self, size=200):
        self.SIZE = size
        self.POINT_RADIUS = 1 if self.SIZE < 400 else 2
        self.LINE_WIDTH = 1 if self.SIZE < 400 else 2
        self.ARROW_SIZE = 6 if self.SIZE < 400 else 8
        self.TRANSFORM = Matrix([[self.SIZE / 20, 0], [0, -self.SIZE / 20]])
        self.SHIFT = Vector(self.SIZE / 2, self.SIZE / 2)
        Canvas.canvasCounter += 1
        self.canvasID = "canvas_{}".format(Canvas.canvasCounter)
        display(
            Javascript("""
element.append("<canvas id='{}' width={} height={} style='background-color: #f0f0f0'></canvas>")
""".format(self.canvasID, self.SIZE, self.SIZE)))
Exemple #7
0
    def __init__(self):
        self.verts = Matrix(
            [[1 / math.sqrt(10), 1 / math.sqrt(6), 1 / math.sqrt(3), 1],
             [1 / math.sqrt(10), 1 / math.sqrt(6), 1 / math.sqrt(3), -1],
             [1 / math.sqrt(10), 1 / math.sqrt(6), -2 / math.sqrt(3), 0],
             [1 / math.sqrt(10), -math.sqrt(1.5), 0, 0],
             [-2 * math.sqrt(2 / 5), 0, 0, 0]])

        self.center = [0, 0, 0, 0]

        self.edges = [[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4],
                      [2, 3], [2, 4], [3, 4]]

        self.faces = [[1, 2, 3]]
Exemple #8
0
def skip_rows(mat):
    transposed = mat.transposed()
    fix_mat = Matrix.identity(mat.rows)
    unskipped_indexes = []
    need_unit_row = False
    for x, col in enumerate(transposed.content[:-1]):
        is_prev_value_used = False
        for y, elem in enumerate(col[:-1]):
            # Let's explicity check element's equality to zero
            # (in theory element can have another type than "int")
            if elem != 0:
                if y == x and elem == 1:
                    # Variable's value depends from previous value
                    is_prev_value_used = True
                else:
                    # Variable's value depends from values of another
                    # variables or depends from previous value but used
                    # multiplication
                    break
        else:
            if (
                    # If variable is unchanged
                (is_prev_value_used and col[-1] == 0) or
                    # Or variable has assigned to constant value
                    not is_prev_value_used):
                if not is_prev_value_used:
                    handle_mov(fix_mat.content, (VAR, x), (VALUE, col[-1]))

                for index, elem in enumerate(mat.content[x]):
                    if elem != 0 and index != x:
                        raise MatcodeFoldingError(
                            'Folded variable is used in calculations ' +
                            'of another variables')
                continue

        unskipped_indexes.append(x)
        if col[-1] != 0:
            need_unit_row = True
    if need_unit_row:
        unskipped_indexes.append(mat.rows - 1)

    lite_content = []
    for y in unskipped_indexes:
        row = []
        for x in unskipped_indexes:
            row.append(mat.content[y][x])
        lite_content.append(row)
    return Matrix(lite_content), unskipped_indexes, fix_mat
def q1():
    print('\n=== Question 1 ===')
    S1 = build_triangle_and_find_local_S([0, 0, 0.02], [0.02, 0, 0])
    S1.save_to_latex('report/matrices/S1.txt')
    print('S1: {}'.format(S1))

    S2 = build_triangle_and_find_local_S([0.02, 0, 0.02], [0.02, 0.02, 0])
    S2.save_to_latex('report/matrices/S2.txt')
    print('S2: {}'.format(S2))

    C = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1],
                [1, 0, 0, 0], [0, 0, 1, 0]])
    C.save_to_latex('report/matrices/C.txt')
    print('C: {}'.format(C))

    S = find_global_s_matrix(S1, S2, C)
    S.save_to_latex('report/matrices/S.txt')
    S.save_to_csv('report/csv/S.txt')
    print('S: {}'.format(S))
Exemple #10
0
    def __init__(self):
        self.verts = Matrix([
            [1, 0, 0, 0],  #0
            [0, 1, 0, 0],  #1
            [0, 0, 1, 0],  #2
            [0, 0, 0, 1],  #3
            [-1, 0, 0, 0],  #4
            [0, -1, 0, 0],  #5
            [0, 0, -1, 0],  #6
            [0, 0, 0, -1]
        ])  #7

        self.center = [0, 0, 0, 0]

        self.edges = [
            [0, 1],
            [0, 2],
            [0, 3],
            [0, 5],
            [0, 6],
            [0, 7],
            [1, 2],
            [1, 3],
            [1, 4],
            [1, 6],
            [1, 7],
            [2, 3],
            [2, 4],
            [2, 5],
            [2, 7],
            [3, 4],
            [3, 5],
            [3, 6],
            [4, 5],
            [4, 6],
            [4, 7],
            [5, 6],
            [5, 7],
            [6, 7],
        ]

        self.faces = [[1, 2, 3]]
Exemple #11
0
def skip_rows(mat):
    need_unit_row = False
    unskipped_indexes = []
    fix_mat = Matrix.identity(mat.rows)
    for index in xrange(mat.rows - 1):
        cur_row = mat.content[index]
        cur_col = [row[index] for row in mat.content]

        index_can_be_skipped = False
        prev_value_coeff = cur_col[index]
        const_coeff = cur_col[-1]
        # If an original value of a variable isn't used in calculations of
        # other variables and a new value doesn't depend on other variables
        if (
            all(elem == 0 for j, elem in enumerate(cur_row) if j != index) and
            all(elem == 0 for j, elem in enumerate(cur_col[:-1]) if j != index)
        ):
            # If a new variable value is a constant
            if prev_value_coeff == 0:
                handle_mov(fix_mat.content, (VAR, index), (VALUE, const_coeff))
                index_can_be_skipped = True
            # Or the value wasn't changed
            elif prev_value_coeff == 1 and const_coeff == 0:
                index_can_be_skipped = True

        if not index_can_be_skipped:
            unskipped_indexes.append(index)
            if const_coeff != 0:
                need_unit_row = True

    if need_unit_row:
        unskipped_indexes.append(mat.rows - 1)
    lite_content = []
    for y in unskipped_indexes:
        row = []
        for x in unskipped_indexes:
            row.append(mat.content[y][x])
        lite_content.append(row)
    return Matrix(lite_content), unskipped_indexes, fix_mat
Exemple #12
0
import sys
from matrices import Matrix
'''generates hadamard codes, using the hadamard matrix constructin, which are made using the sylvester construction
https://en.wikipedia.org/wiki/Hadamard_matrix
https://en.wikipedia.org/wiki/Hadamard_code'''

#the length of the codes will be 2 ** size
size = int(sys.argv[1])

H = Matrix([[1]])

while size:
    size -= 1

    H = H.append_right(H).append_under(H.append_right(H * -1))

for row in H.append_under(H * -1):
    for i in row:
        sys.stdout.write(str((i + 1) / 2))

    sys.stdout.write('\n')
Exemple #13
0
def matrix():
    result = None
    if request.method == 'POST':
        try:
            op = request.form.get('submit', None)
            acalc = request.form.get('a-submit', None)
            bcalc = request.form.get('b-submit', None)
            if acalc:
                letter = 'A'
                calc = acalc
            elif bcalc:
                letter = 'B'
                calc = bcalc
            else:
                mata = []
                for x in range(3):  #TODO make a function def to get a matrix
                    mata.append([])  #def get_mat(letter,x,y):
                    for y in range(3):
                        string = 'A' + str(x) + str(y)
                        mata[x].append(Fraction(request.form[string]))
                matb = []
                for x in range(3):
                    matb.append([])
                    for y in range(3):
                        string = 'B' + str(x) + str(y)
                        matb[x].append(Fraction(request.form[string]))
                a = Matrix(mata)
                b = Matrix(matb)
                if op == 'X':
                    matresult = a * b
                if op == '-':
                    matresult = a - b
                if op == '+':
                    matresult = a + b
                result = matresult.tostr().rows
                return render_template('matrix.html',
                                       matrix_result=result,
                                       det_result=None,
                                       Error=None)

            mat = []
            for x in range(3):
                mat.append([])
                for y in range(3):
                    string = letter + str(x) + str(y)
                    mat[x].append(Fraction(request.form[string]))
            m = Matrix(mat)
            if 'Determinant' in calc:
                result = str(m.determinant())
                return render_template('matrix.html',
                                       matrix_result=None,
                                       det_result=result,
                                       Error=None)
            elif 'Inverse' in calc:
                result = m.inverse().tostr().rows
                return render_template('matrix.html',
                                       matrix_result=result,
                                       det_result=None,
                                       Error=None)
            elif 'Transpose' in calc:
                result = m.transpose().tostr().rows
                return render_template('matrix.html',
                                       matrix_result=result,
                                       det_result=None,
                                       Error=None)
            elif 'Triangle' in calc:
                result = m.triangle().tostr().rows
                return render_template('matrix.html',
                                       matrix_result=result,
                                       det_result=None,
                                       Error=None)

            else:
                return render_template('matrix.html',
                                       matrix_result=None,
                                       det_result=None,
                                       Error=None)
        except Exception as e:
            print(e)
            error = 'Invalid Matrix, Try again'
            return render_template('matrix.html',
                                   matrix_result=None,
                                   det_result=None,
                                   Error=error)

    return render_template('matrix.html', matrix_result=result)
Exemple #14
0
def matrix_main():
    matrix = Matrix([[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]])

    r = matrix.reverse()
    print(r)
Exemple #15
0
def zRotationMatrix(angle):
    return Matrix([[cos(angle), -sin(angle), 0, 0],
                   [sin(angle), cos(angle), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
Exemple #16
0
def yRotationMatrix(angle):
    return Matrix([[cos(angle), 0, sin(angle), 0], [0, 1, 0, 0],
                   [-sin(angle), 0, cos(angle), 0], [0, 0, 0, 1]])
Exemple #17
0
def xRotationMatrix(angle):
    return Matrix([[1, 0, 0, 0], [0, cos(angle), -sin(angle), 0],
                   [0, sin(angle), cos(angle), 0], [0, 0, 0, 1]])
from __future__ import division

from csv_saver import save_rows_to_csv
from linear_networks import solve_linear_network, csv_to_network_branch_matrices
from choleski import choleski_solve
from matrices import Matrix

NETWORK_DIRECTORY = 'network_data'

L_2 = Matrix([[5, 0], [1, 3]])
L_3 = Matrix([[3, 0, 0], [1, 2, 0], [8, 5, 1]])
L_4 = Matrix([[1, 0, 0, 0], [2, 8, 0, 0], [5, 5, 4, 0], [7, 2, 8, 7]])
matrix_2 = L_2 * L_2.transpose()
matrix_3 = L_3 * L_3.transpose()
matrix_4 = L_4 * L_4.transpose()
positive_definite_matrices = [matrix_2, matrix_3, matrix_4]

x_2 = Matrix.column_vector([8, 3])
x_3 = Matrix.column_vector([9, 4, 3])
x_4 = Matrix.column_vector([5, 4, 1, 9])
xs = [x_2, x_3, x_4]


def q1():
    """
    Question 1
    """
    q1b()
    q1c()
    q1d()
Exemple #19
0
def run_matcode(settings, matcode, vector):
    mat = run_loop(settings, matcode, 0, len(vector))[0]
    return (Matrix([vector]) * mat).content[0]
Exemple #20
0
def scalingMatrix(sx, sy, sz):
    return Matrix([[sx, 0, 0, 0], [0, sy, 0, 0], [0, 0, sz, 0], [0, 0, 0, 1]])