示例#1
0
def rotate(q, vec):
    i = conjugate(q)
    p = [0, vec[0], vec[1], vec[2]]

    # [w, v] = [q] * [p] = [a, b] * [c, d]
    a = q[0]
    b = [q[1], q[2], q[3]]

    c = p[0]
    d = [p[1], p[2], p[3]]

    w = a * c - matrix.innerProduct(b, d)
    v = matrix.crossProduct(b, d)
    v = matrix.add(v, matrix.scalarProduct(a, d))
    v = matrix.add(v, matrix.scalarProduct(c, b))

    # # [s, t] = [w, v] * [i[0], [i[1], i[2], i[3]]] = [w, v] * [j, k]
    j = i[0]
    k = [i[1], i[2], i[3]]

    s = w * j - matrix.innerProduct(v, k)
    t = matrix.crossProduct(v, k)
    t = matrix.add(t, matrix.scalarProduct(w, k))
    t = matrix.add(t, matrix.scalarProduct(j, v))

    return [s, t[0], t[1], t[2]]
示例#2
0
文件: gauss.py 项目: lucas8/MPSI
def solve(m, bs, p):
    """
    Solve a triangularized linear system, writing the solutions to bs, p being the number of variables.
    Returns False if there are no solutions.
    """
    for i in range(len(m) - 1, -1, -1):
        z = first_nonzero(m[i])
        if z > p:
            continue
        elif z == p:
            return False
        bs[z][0] = m[i][p]
        for j in range(z+1, p):
            matrix.add(bs, z, -m[i][j], j)
        matrix.mult(bs, z, 1.0/m[i][z])
    return True
示例#3
0
文件: 2D.py 项目: peaceland/math-ia
def main():
    P = [[40], [40]]
    V0 = [[30], [30]]
    V1 = [[40], [70]]
    V2 = [[50], [30]]
    points = [V0, V1, V2]
    aspect_correct = [[1, 0], [0, 4 / 7]]
    home = "\N{escape}[H"
    wakeup_time = time.time()
    print(home + "\N{escape}[J\N{escape}[?25l")
    t = 0
    try:
        while True:
            kanvas = canvas.Canvas()
            rot = matrix.rotate_2D(t * 0.5)
            r_points = []
            for point in points:
                C = matrix.sub(point, P)
                C = matrix.mult(rot, C)
                C = matrix.add(P, C)
                C = matrix.mult(aspect_correct, C)
                r_points.append(C)
            t += 1
            kanvas.triangle(round(r_points[0][0][0]), round(r_points[0][1][0]),
                            round(r_points[1][0][0]), round(r_points[1][1][0]),
                            round(r_points[2][0][0]), round(r_points[2][1][0]))
            image = home + kanvas.get_image()
            print(image)
            wakeup_time += 0.05
            time.sleep(max(0, wakeup_time - time.time()))
    finally:
        print(home + "\N{escape}[J \N{escape}[?25h")
示例#4
0
 def draw_everything(self):
     super(PygameInterpreter, self).draw_everything()
     
     #~ if self.waiting and self.darkening < self.DARKENING_MAX:
         #~ self.darkening += self.DARKENING_INC
         #~ 
     #~ # black filter behind text
     #~ black = pygame.Surface(self.resolution)
     #~ black.set_alpha(self.darkening)
     #~ self._surface.blit( black, (0, 0) )
     
     
     # text display
     for topleft, s in self.text:
         text_size = self.font.size(s)
         text_area = pygame.Rect(topleft, text_size)
         
         # once in black, to outline it
         outline_topleft = matrix.add(topleft, [1, 1])
         text = self.font.render(s, True, self.colors[OUTLINE_COLOR])
         self._surface.blit( text, outline_topleft )
         
         # and once normally
         text = self.font.render(s, True, self.colors[TEXT_COLOR])
         self._surface.blit( text, topleft )
示例#5
0
 def draw_offset_mult(offset, blend, mult, mask):
     for y in range(min(f.height, pic.size[1])):
         for x in range(min(f.width, pic.size[0])):
             pix = matrix.add(
                 matrix.cmultiply(matrix.multiply(pic.getpixel((x + offset, y))[:3], mult * (1-blend)), mask),
                 matrix.cmultiply(matrix.multiply(pic.getpixel((x + offset + 1, y))[:3], mult * blend), mask)
                 )
             f.point(x, y, pix)
示例#6
0
def main():
    P = [[40],
         [40],
         [0]]
    Axis = [[10],
            [5],
            [3]]
#    V0 = [[30],
#          [30],
#          [0]]
#    V1 = [[40],
#          [70],
#          [0]]
#    V2 = [[50],
#          [30],
#          [0]]
#    points = [V0, V1, V2]
    points = []
    for i in range(15):
        points.append([[random.randint(20, 60)],
                       [random.randint(30, 60)],
                       [random.randint(-20, 20)]])

    aspect_correct = [[1, 0, 0],
                      [0, 4/7, 0],
                      [0, 0, 1]]
    home = "\N{escape}[H"
    wakeup_time = time.time()
    print(home + "\N{escape}[J\N{escape}[?25l")
    t = 0
    try:
        while True:
            kanvas = canvas.Canvas()
            rot = matrix.rotate_3D(t * 0.1, Axis)
            r_points = [] 
            for point in points:
                C = matrix.sub(point, P)
                C = matrix.mult(rot, C)
                C = matrix.add(P, C)
                C = matrix.mult(aspect_correct, C)
                r_points.append(C)
            t += 1
            for r_point in r_points:
                kanvas.dab(round(r_point[0][0]),
                           round(r_point[1][0]))

#            kanvas.triangle(round(r_points[0][0][0]),
#                            round(r_points[0][1][0]),
#                            round(r_points[1][0][0]),
#                            round(r_points[1][1][0]),
#                            round(r_points[2][0][0]),
#                            round(r_points[2][1][0]))
            image = home + kanvas.get_image()
            print(image)
            wakeup_time += 0.05
            time.sleep(max(0, wakeup_time - time.time()))
    finally:
        print(home + "\N{escape}[J \N{escape}[?25h")
示例#7
0
文件: gauss.py 项目: lucas8/MPSI
def remove(m, x, y):
    """
    Remove the x-eme element in lines ]y,end[
    Returns false if it was already removed
    """
    piv = None
    for j in range(y, len(m)):
        if is_zero(m[j][x]):
            continue
        if not piv:
            piv = m[j][x]
            if j != y:
                matrix.swap(m, j, y)
            continue
        matrix.add(m, j, -m[j][x]/piv, y)
    if piv:
        return True
    else:
        return False
示例#8
0
 def add_word(self, s):
     needed = self.font.size(s)[0]
     
     if needed > self.remaining_row:
         self._next_line()
         
     topleft = self.get_pixelpos(self.linenumber, self.remaining_row)
     topleft = matrix.add(topleft, self.text_topleft)
     
     self.text.append( (topleft, s) )
     
     self.remaining_row -= needed
示例#9
0
    def add_word(self, s):
        needed = self.font.size(s)[0]

        if needed > self.remaining_row:
            self._next_line()

        topleft = self.get_pixelpos(self.linenumber, self.remaining_row)
        topleft = matrix.add(topleft, self.text_topleft)

        self.text.append((topleft, s))

        self.remaining_row -= needed
示例#10
0
    def draw_everything(self):
        super(PygameInterpreter, self).draw_everything()

        #~ if self.waiting and self.darkening < self.DARKENING_MAX:
        #~ self.darkening += self.DARKENING_INC
        #~
        #~ # black filter behind text
        #~ black = pygame.Surface(self.resolution)
        #~ black.set_alpha(self.darkening)
        #~ self._surface.blit( black, (0, 0) )

        # text display
        for topleft, s in self.text:
            text_size = self.font.size(s)
            text_area = pygame.Rect(topleft, text_size)

            # once in black, to outline it
            outline_topleft = matrix.add(topleft, [1, 1])
            text = self.font.render(s, True, self.colors[OUTLINE_COLOR])
            self._surface.blit(text, outline_topleft)

            # and once normally
            text = self.font.render(s, True, self.colors[TEXT_COLOR])
            self._surface.blit(text, topleft)
示例#11
0
def main(x, hidden, b, learning, test, w, g, n_d):
    random.seed(1)
    training_data = x[:]
    noise_data = n_d[:]

    # Adding bias to training data
    training_data.append([])
    noise_data.append([])

    for _ in x[0]:
        training_data[1].append(b)
        noise_data[1].append(b)

    # Random weights for synapses
    synapses0 = []
    synapses1 = []

    for _ in range(hidden):
        synapses0.append([random.uniform(w, -w), random.uniform(w, -w)])  # second rand for bias synapses
    for j in range(hidden + 1):  # +1 for bias
        synapses1.append([random.uniform(w, -w)])

    sig_layer2 = []

    global loading_message
    global loading_progress
    # learning loop (learning = iterations)
    for i in xrange(learning):
        temp = i+1
        loading_progress = round((float(temp) / float(iterations)) * 100, 1)

        # loading_progress = (temp / learning) * 100
        # # # Forward pass
        # # Input Layer

        layer1 = matrix.multiply(synapses0, training_data)

        # Activation level
        sig_layer1 = matrix.sig(layer1)

        # # Hidden Layer
        # Adding bias to layer1

        b_sig_layer1 = sig_layer1[:]

        b_sig_layer1.append([])

        for _ in b_sig_layer1[0]:
            b_sig_layer1[len(b_sig_layer1) - 1].append(b)

        layer2 = matrix.multiply(matrix.transpose(synapses1), b_sig_layer1)

        sig_layer2 = matrix.sig(layer2)

        # Calculate net error
        error = [matrix.subtract(test, matrix.transpose(sig_layer2))]

        # if i % 25000 == 0:
        #     temp = 0
        #     for j in range(len(error)):
        #         temp += temp + error[0][j]
        #     print i, temp

        # Delta for neuron in output layer (1 for each training data)
        deriv_sig_layer2 = matrix.derivative(sig_layer2)
        delta_layer2 = [[]]

        for j in range(len(error[0])):
            delta_layer2[0].append(deriv_sig_layer2[0][j] * error[0][j] * g)

        # Delta for neurons in hidden layer
        deriv_sig_layer1 = matrix.derivative(sig_layer1)
        delta_layer1 = []
        delta_weight_sum = []

        for k in range(len(synapses1)):
            delta_weight_sum.append([])
            for j in range(len(delta_layer2[0])):
                delta_weight_sum[k].append(synapses1[k][0] * delta_layer2[0][j])

        for k in range(len(deriv_sig_layer1)):
            delta_layer1.append([])
            for j in range(len(deriv_sig_layer1[0])):
                delta_layer1[k].append(deriv_sig_layer1[k][j] * delta_weight_sum[k][j] * g)

        delta_w_oh = matrix.multiply(delta_layer2, matrix.transpose(b_sig_layer1))
        delta_w_hi = matrix.multiply(delta_layer1, matrix.transpose(training_data))

        # # Update weights
        synapses1 = matrix.add(synapses1, matrix.transpose(delta_w_oh))

        synapses0 = matrix.add(synapses0, delta_w_hi)

        if i > learning * 0.5:
            if i > learning * 0.95:
                loading_message = "I'm nearly done, good training."
            else:
                loading_message = "Well, I'm halfway through."

    # Testing net with noised data
    sig_noise = []
    if len(n_d) > 0:
        # print "testing with noise data"

        l1 = matrix.multiply(synapses0, noise_data)

        sig_l1 = matrix.sig(l1)

        b_sig_l1 = sig_l1[:]

        b_sig_l1.append([])

        for _ in b_sig_l1[0]:
            b_sig_l1[len(b_sig_l1) - 1].append(b)

        l2 = matrix.multiply(matrix.transpose(synapses1), b_sig_l1)

        sig_noise = matrix.sig(l2)

    # formatting net output for plot
    result1 = []  # training data
    result2 = []  # noised data
    for i in range(len(sig_layer2[0])):
        result1.append(sig_layer2[0][i] * 2 - 1)
        result2.append(sig_noise[0][i] * 2 - 1)

    # Plot
    # Some code lines from: https://matplotlib.org/users/legend_guide.html
    neuron_patch = mpatches.Patch(label='Neurons: ' + str(hidden))
    bias_patch = mpatches.Patch(label='Bias: ' + str(b))
    iteration_patch = mpatches.Patch(label='Iterations: ' + str(learning))
    epsilon_patch = mpatches.Patch(label='Epsilon: ' + str(g))
    weight_patch = mpatches.Patch(label='Weight range (0 +/-): ' + str(w))
    time_patch = mpatches.Patch(label=str(round((time.time() - start_time) / 60, 2)) + " min")
    first_legend = plt.legend(
        handles=[bias_patch, time_patch, epsilon_patch, neuron_patch, iteration_patch, weight_patch],
        bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
        ncol=3, mode="expand", borderaxespad=0.)

    line1, = plt.plot(inputData[0], result1, label="Training Data", linewidth=0.75)
    line2, = plt.plot(inputData[0], result2, label="Test Data", linestyle=':', linewidth=0.75)
    line3, = plt.plot(x_data, y_data, label="sin(x)", linestyle='--', linewidth=0.75)
    ax = plt.gca().add_artist(first_legend)
    plt.legend(handles=[line1, line2, line3])
    plt.savefig('./plots/plot' + str(time.time())[2:10] + '.png')

    plt.clf()
    plt.cla()
    plt.close()
示例#12
0
def main(x, hidden, b, epochs, test, w, g, n_d, m, p_m):
    random.seed(1)
    training_data = x[:]
    noise_data = n_d[:]

    # Adding bias to training data
    training_data.append([])
    noise_data.append([])

    for _ in x[0]:
        training_data[len(training_data)-1].append(b)
        noise_data[len(noise_data)-1].append(b)

    # Random weights for synapses
    synapses0 = []
    synapses1 = []

    for f in range(hidden):
        synapses0.append([])
        for _ in range(len(training_data)):
            synapses0[f].append(random.uniform(w, -w))  # second rand for bias synapses
    for j in range(hidden + 1):  # +1 for bias
        synapses1.append([random.uniform(w, -w)])

    sig_layer2 = []
    error_log = []
    error_log2 = []
    gamma_log = []
    global loading_message
    global loading_progress

    # learning loop (learning = iterations)
    for i in xrange(epochs):
        loading_progress = round((float(i) / float(iterations)) * 100, 1)

        # # # Forward pass
        # # Input Layer
        layer1 = matrix.multiply(synapses0, training_data)

        # Activation level
        sig_layer1 = matrix.sig(layer1)

        # # Hidden Layer
        # Adding bias to layer1
        b_sig_layer1 = sig_layer1[:]

        b_sig_layer1.append([])

        for _ in b_sig_layer1[0]:
            b_sig_layer1[len(b_sig_layer1) - 1].append(b)

        layer2 = matrix.multiply(matrix.transpose(synapses1), b_sig_layer1)

        sig_layer2 = matrix.sig(layer2)

        # # # ----------------
        # # Calculate net error
        error = [matrix.subtract(test, matrix.transpose(sig_layer2))]
        # error = [matrix.error(test, matrix.transpose(sig_layer2))]
        # if i % 5000 == 0:
        #     print(error)

        temp = 0
        for j in range(len(error)):
            temp += temp + error[0][j]

        error_log.append(temp/len(error))

        # Test with test data
        sig_noise = []
        l1 = matrix.multiply(synapses0, noise_data)
        sig_l1 = matrix.sig(l1)
        b_sig_l1 = sig_l1[:]
        b_sig_l1.append([])

        for _ in b_sig_l1[0]:
            b_sig_l1[len(b_sig_l1) - 1].append(b)

        l2 = matrix.multiply(matrix.transpose(synapses1), b_sig_l1)
        sig_noise = matrix.sig(l2)

        error2 = [matrix.subtract(test, matrix.transpose(sig_noise))]

        temp2 = 0
        for j in range(len(error2)):
            temp2 += temp2 + error2[0][j]

        error_log2.append(temp2 / len(error2))

        # # # ----------------
        # # Calculating weight updates
        # Delta for neuron in output layer (1 for each training data)
        deriv_sig_layer2 = matrix.derivative(sig_layer2)
        delta_layer2 = [[]]

        # temp_g = (g/(i+1))
        # gamma_log.append(temp_g)

        for j in range(len(error[0])):
            delta_layer2[0].append(deriv_sig_layer2[0][j] * error[0][j] * g)

        # Delta for neurons in hidden layer
        deriv_sig_layer1 = matrix.derivative(sig_layer1)
        delta_layer1 = []
        delta_weight_sum = []

        for k in range(len(synapses1)):
            delta_weight_sum.append([])
            for j in range(len(delta_layer2[0])):
                delta_weight_sum[k].append(synapses1[k][0] * delta_layer2[0][j])

        for k in range(len(deriv_sig_layer1)):
            delta_layer1.append([])
            for j in range(len(deriv_sig_layer1[0])):
                delta_layer1[k].append(deriv_sig_layer1[k][j] * delta_weight_sum[k][j] * g)

        delta_w_oh = matrix.multiply(delta_layer2, matrix.transpose(b_sig_layer1))
        delta_w_hi = matrix.multiply(delta_layer1, matrix.transpose(training_data))

        # # # Backwards pass
        # # Update weights
        synapses1 = matrix.add(synapses1, matrix.transpose(delta_w_oh))

        synapses0 = matrix.add(synapses0, delta_w_hi)

        if i > epochs * 0.5:
            if i > epochs * 0.95:
                loading_message = "I'm nearly done, good training."
            else:
                loading_message = "Well, I'm halfway through."

        # # # End of learning

    # Testing net with noised/test data
    sig_noise = []
    l1 = matrix.multiply(synapses0, noise_data)
    sig_l1 = matrix.sig(l1)
    b_sig_l1 = sig_l1[:]
    b_sig_l1.append([])

    for _ in b_sig_l1[0]:
        b_sig_l1[len(b_sig_l1) - 1].append(b)

    l2 = matrix.multiply(matrix.transpose(synapses1), b_sig_l1)
    sig_noise = matrix.sig(l2)

    # formatting net output for plot
    result1 = []  # training data
    result2 = []  # noised data
    for i in range(len(sig_layer2[0])):
        result1.append(sig_layer2[0][i] * 2 - 1)
        result2.append(sig_noise[0][i] * 2 - 1)

    if m == "sin":
        # Plot
        # Some code lines from: https://matplotlib.org/users/legend_guide.html
        neuron_patch = mpatches.Patch(label='Neurons: ' + str(hidden))
        bias_patch = mpatches.Patch(label='Bias: ' + str(b))
        iteration_patch = mpatches.Patch(label='Iterations: ' + str(epochs))
        epsilon_patch = mpatches.Patch(label='Gamma: ' + str(g))
        weight_patch = mpatches.Patch(label='Weight range: +/- ' + str(w))
        time_patch = mpatches.Patch(label=str(round((time.time() - start_time) / 60, 2)) + " min")
        first_legend = plt.legend(
            handles=[bias_patch, time_patch, epsilon_patch, neuron_patch, iteration_patch, weight_patch],
            bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
            ncol=3, mode="expand", borderaxespad=0.)

        line4, = plt.plot(error_axis[0], error_log, label="Error", linewidth=0.5)
        line6, = plt.plot(error_axis[0], error_log2, label="Error2", linewidth=0.5)
        line1, = plt.plot(inputData[0], result1, label="Training Data", linewidth=0.75)
        line2, = plt.plot(inputData[0], result2, label="Test Data", linestyle=':', linewidth=0.75)
        line3, = plt.plot(x_data, y_data, label="sin(x)", linestyle='--', linewidth=0.75)
        line5, = plt.plot(x_axis, y_axis, label="Axis", linewidth=0.5)
        ax = plt.gca().add_artist(first_legend)
        plt.legend(handles=[line4, line1, line2, line3, line5, line6])

        if p_m:
            plt.savefig('./plots/' + str(time.time())[2:10] + '.png')
        else:
            plt.show()

        plt.clf()
        plt.cla()
        plt.close()

    elif m == "xor":
        print("-----")
        for i in range(len(sig_noise[0])):
            print "Input: " + str(round(noise_data[0][i], 0)) + " & " \
                  + str(round(noise_data[1][i], 0)) + " = " + str(round(sig_noise[0][i], 0)) + " (" \
                  + str(round(sig_noise[0][i] * 100, 4)) + "% for True)"
示例#13
0
文件: invert.py 项目: lucas8/MPSI
    latex_line(mat)

    # Eliminating
    for i in range(len(mat)):
        if is_zero(mat[i][i]):
            print("Can't invert the matrix.")
            latex.output("\\end{array}")
            latex.enq()
            latex.output("\\\\Can't invert the matrix.\n")
            latex.end("Inverting the matrix")
            exit()
        matrix.mult(mat, i, 1/mat[i][i])
        for j in range(len(mat)):
            if j == i:
                continue
            matrix.add(mat, j, -mat[j][i], i)
        latex_line(mat)

    # Output
    invert = []
    for i in range(len(mat)):
        invert += [[0] * size]
        for j in range(size):
            invert[i][j] = mat[i][j + size]
    matrix.output(invert)

    # LaTeX output
    latex.output("\\end{array}")
    latex.enq()
    latex.output("\\\\Inverse :\n")
    latex.beq()
示例#14
0
        # Если это цифра - добавить в список вызываемых функций
        if param.isdigit():
            calls.append(param)
        # Иначе - это путь к файлу со входными данными
        else:
            path = param

    # Чтение JSON со входными данными
    with open(path) as f:
        data = json.load(f)

    # Словарь функций
    dictionary = {
        '1':
        matrix.add(data['first_matrix_dimensions'],
                   data['second_matrix_dimensions'], data['first_matrix'],
                   data['second_matrix']),
        '2':
        matrix.sub(data['first_matrix_dimensions'],
                   data['second_matrix_dimensions'], data['first_matrix'],
                   data['second_matrix']),
        '3':
        matrix.mult(data['first_matrix_dimensions'],
                    data['second_matrix_dimensions'], data['first_matrix'],
                    data['second_matrix']),
        '4':
        matrix.det(data['number'], data['first_matrix'])
    }

    # Вызов функции из словоря по списку входных данных
    for param in calls:
示例#15
0
 def global_rect(topleft, width):
     # They have to be global positions
     return pygame.Rect( matrix.add(self.text_topleft, topleft), width )
示例#16
0
 def global_rect(topleft, width):
     # They have to be global positions
     return pygame.Rect(matrix.add(self.text_topleft, topleft), width)
示例#17
0
 def write_new(self, location):
     return matrix.add(location)