def triangles(self): aux2 = multiply(self.adjMatrix, self.adjMatrix) aux3 = multiply(self.adjMatrix, aux2) trace = getTrace(aux3) return trace // 6
def conmf_cost(Vs, Ws, Hs, weights, regu_weights, norm, method): """ Calculate the value of cost function(Frobenius form) of CoNMF. Two parts of the cost function: factorization part and regularization part, are calculated seperately. """ # Factorization part sum1 = 0 for k in range(0, len(weights)): V, W, H = Vs[k], Ws[k], Hs[k] dot_WH = dot(W, H) R = V - dot_WH sum1 = sum1 + weights[k] * multiply(R, R).sum() # Regularization part sum2 = 0 for k in range(0, len(weights)): for t in range(0, len(weights)): if k == t: continue if k < t: lambda_kt = regu_weights[k][t] if k > t: lambda_kt = regu_weights[t][k] if method == "pair-wise": R = Ws[k] - Ws[t] sum2 = sum2 + lambda_kt * multiply(R, R).sum() if method == "cluster-wise": R = dot(Ws[k].T, Ws[k]) - dot(Ws[t].T, Ws[t]) sum2 = sum2 + lambda_kt * multiply(R, R).sum() return sum1 + sum2
def conmf_update(Vs, Ws, Hs, weights, regu_weights, norm, method): """ The iterative rules of CoNMF. Details in paper [1] Section 4.3 and 4.4. :param Vs (type: list<csr_matrix>). Data of each view. :param Ws (type: list<csr_matrix). W matrix of each view. :param Hs (type: list<csr_matrix). H matrix of each view. :param weights (type: list<int>). Regularization parameters \lambda_s. :param regu_weights (type: list, 2 dimension). Regularization parameters \lambda_st. :param norm (type: string). Normalization scheme in CoNMF initialization and factorization. Values can be 'l2', 'l1' and 'l0': 'l2': each item vector is normalized by its euclidean length (i.e. l2 distance). 'l1': each item vector is normalized by its sum of all elements (i.e. l1 distance). 'l0': the whole matrix is normalized by the sum of all elements (i.e. l1 normalization on the whole matrix). :param method (type: string). Regularization method of CoNMF. Currently support two ways: 'pair-wise': pair-wise NMF, details in paper [1] Section 4.3 'cluster-wise': cluster-wise NMF, details in paper [1] Section 4.4 V = W H V: #item * #feature; W: #item * #cluster H: #cluster * #feature """ # Update Hs[k] Ws, Hs = conmf_normalize(Ws, Hs, norm, basis="W") # Update Hs[k] first. NMF, CoNMF(mutual, cluster) are same for this updates for k in range(0, len(weights)): V, W, H = Vs[k], Ws[k], Hs[k] up = dot(W.T, V) down = dot(dot(W.T, W), H) elop_div = elop(up, down, div) Hs[k] = multiply(H, elop_div) # Update Ws[k] for k in range(0, len(weights)): V, W, H = Vs[k], Ws[k], Hs[k] up = dot(V, H.T) * weights[k] down = dot(W, dot(H, H.T)) * weights[k] if method == "pair-wise": for t in range(0, len(weights)): if k == t: continue if k < t: lambda_kt = regu_weights[k][t] if k > t: lambda_kt = regu_weights[t][k] up = up + Ws[t] * lambda_kt down = down + W * lambda_kt if method == "cluster-wise": for t in range(0, len(weights)): if k == t: continue if k < t: lambda_kt = regu_weights[k][t] if k > t: lambda_kt = regu_weights[t][k] up = up + 2 * lambda_kt * dot(Ws[k], dot(Ws[t].T, Ws[t])) down = down + 2 * lambda_kt * dot(Ws[k], dot(Ws[k].T, Ws[k])) elop_div = elop(up, down, div) Ws[k] = multiply(W, elop_div) return Ws, Hs
def euclidean_update(V, W, H, norm): """Update basis and mixture matrix based on Euclidean distance multiplicative update rules.""" up = dot(W.T, V) down = dot(dot(W.T, W), H) elop_div = elop(up, down, div) H = multiply(H, elop_div) W = multiply(W, elop(dot(V, H.T), dot(W, dot(H, H.T)), div)) return W, H
def conmf_normalize(Ws, Hs, norm="l2", basis="H"): """ Normalization strategy of CoNMF, details in [1] Section 4.3.2. :param basis (type: string). Indicate which matrix to use for calculating the norm factors. Values can be 'H' and 'W': 'H':First calculating norm factors from H (rows), then 1. Normalize W; 2. Normalize H (row) 'W':First calculating norm factors from W (cols), then 1. Normalize H; 2. Normalize W (col) """ if norm == "none": return Ws, Hs if basis not in ["W", "H"]: print "Error! Input basis is not 'W' or 'H'!" if basis == "H": for k in range(len(Hs)): W, H = Ws[k], Hs[k] if norm == "l1" or norm == "l0": S = np.squeeze(np.asarray(H.sum(axis=1))) #Type: np.array if norm == "l2": S = np.squeeze(np.asarray(multiply(H, H).sum(axis=1))) S = np.sqrt(S) D, D_inv = sparse.lil_matrix((len(S), len(S))), sparse.lil_matrix( (len(S), len(S))) D.setdiag(S) D_inv.setdiag(1.0 / S) Ws[k] = dot(W, D) Hs[k] = dot(D_inv, H) if basis == "W": for k in range(len(Hs)): W, H = Ws[k], Hs[k] if norm == "l1" or norm == "l0": S = np.squeeze(np.asarray(W.sum(axis=0))) #Type: np.array if norm == "l2": S = np.squeeze(np.asarray(multiply(W, W).sum(axis=0))) S = np.sqrt(S) D, D_inv = sparse.lil_matrix((len(S), len(S))), sparse.lil_matrix( (len(S), len(S))) D.setdiag(S) D_inv.setdiag(1.0 / S) Hs[k] = dot(D, H) Ws[k] = dot(W, D_inv) return Ws, Hs
def champernowne_constant(exponent: int = 6) -> int: digits_count = 0 length = 0 while length < 10**exponent: digits_count += 1 length += digits_count * 9 * 10**(digits_count - 1) stop = max_number(digits_count) fractional_part = ''.join(map(str, range(1, stop))) return multiply( int(fractional_part[10**exponent - 1]) for exponent in range(exponent + 1))
def recognize(self, figure): self.X = [figure] iters = 0 while iters<MAX_ITERS: new = apply(multiply(self.X, self.w), sign) if self.X == new: break self.X = new iters+=1 if iters==MAX_ITERS: return (False, self.X, iters) return (True, self.X, iters)
def __mixColumns(self,inv = False): ''' Performs mix column on current state. ''' newState = [['00000000' for j in range(len(self.__state))]for i in range(len(self.__state))] mCols = self.__mCols if inv == False else self.__invMCols for i in range(len(self.__state)): for j in range(len(self.__state)): for k in range(len(self.__state)): x = convertHexToBinary(mCols[i][k]).zfill(8) y = convertHexToBinary(self.__state[k][j]).zfill(8) product = multiply(x,y).zfill(8) newState[i][j] = binaryXOR(newState[i][j],product) newState = np.array(newState) hexify = np.vectorize(lambda x:convertBinaryToHex(x)[2:]) pad = np.vectorize(lambda x : '0' + x if len(x) == 1 else x) self.__state = pad(hexify(newState))
def skfunc(U, n): if n == 0: M = U.full() v = np.array([[np.real(M[0, 0]), np.imag(M[0, 0]), np.real(M[1, 0]), np.imag(M[1, 0])]]) dist, index = tree['tree'].query(v, k=1) name = tree['names'][index[0, 0]] if name == '': return gate.I else: basis = tree['basis'] return multiply([basis[int(x)] for x in name]) else: U_next = skfunc(U, n - 1) V, W = gcd(U * U_next.dag()) V_next = skfunc(V, n - 1) W_next = skfunc(W, n - 1) return V_next * W_next * V_next.dag() * W_next.dag() * U_next
def life(canvas, init_file): if 'random' not in init_file: init_file = '/home/pi/pixelcanvas/conway/' + init_file with open(init_file, "r") as file: result = [[int(x) for x in line.split()] for line in file] array = np.array(result) array = array.T else: array = [[random.choice([0, 1]) for pixel in col] for col in canvas._array] t_end = time.time() + 60 # Loop for 60 seconds while time.time() < t_end: colored_array = multiply(array, 0xFFFFFF) canvas._array = colored_array canvas.display() time.sleep(0.3) new_array = step(array) if (new_array == array).all(): break else: array = new_array
def displayClock(canvas): if canvas._height is not 32 or canvas._width is not 20: print 'The canvas is not 20x32!' return else: t_end = time.time() + 90 # Loop for 90 seconds while time.time() < t_end: hour = time.localtime().tm_hour minute = time.localtime().tm_min sec = time.localtime().tm_sec hour_tens = int(str(hour).zfill(2)[0]) hour_ones = int(str(hour).zfill(2)[1]) minute_tens = int(str(minute).zfill(2)[0]) minute_ones = int(str(minute).zfill(2)[1]) second_tens = int(str(sec).zfill(2)[0]) second_ones = int(str(sec).zfill(2)[1]) num = multiply(digits[hour_tens], 0xFF0000) embed(canvas._array, num, hour_tens_loc) num = multiply(digits[hour_ones], 0xFF0000) embed(canvas._array, num, hour_ones_loc) num = multiply(digits[minute_tens], 0x00FF00) embed(canvas._array, num, minute_tens_loc) num = multiply(digits[minute_ones], 0x00FF00) embed(canvas._array, num, minute_ones_loc) num = multiply(digits[second_tens], 0x0000FF) embed(canvas._array, num, second_tens_loc) num = multiply(digits[second_ones], 0x0000FF) embed(canvas._array, num, second_ones_loc) canvas.display() time.sleep(0.1)
def get_diag2(x, y): try: return multiply(data[x + i][y - i] for i in range(4)) except: return 0
def get_diag(x, y): try: return multiply(data[x + i][y + i] for i in range(4)) except: return 0
def get_right(x, y): try: return multiply(data[x + i][y] for i in range(4)) except: return 0
def test_multiply(): assert multiply(3, 3) == 9
c_pos = (pos[0] + c_rel[0], pos[1] + c_rel[1]) grid_dict[c_pos] = c_id lookup[c_id] = c_pos size = int(math.sqrt(len(matches))) grid = [size * [0] for _ in range(size)] w_off = min([e[0] for e in grid_dict]) h_off = min([e[1] for e in grid_dict]) for g_pos, g_id in grid_dict.items(): x, y = g_pos[0] - w_off, g_pos[1] - h_off grid[x][y] = g_id corners = [grid[0][0], grid[0][size-1], grid[size-1][0], grid[size-1][size-1]] print("1:", utils.multiply(corners)) ### BUILD THE IMAGE p_size = len(tiles[first].content) - 2 image = [] for x in range(size): image += [list() for _ in range(p_size)] for y in range(size): p = tiles[grid[x][y]].peel() for i, row in enumerate(p): image[i - p_size] += p[i] ### SEARCH THE MONSTER monster = """ #
from utils import multiply a = 3 b = 2 c = multiply(a, b) print(c)
def get_right(x, y): try: return multiply(data[x + i][y] for i in range(4)) except: return 0
from typing import Tuple from utils import (multiply, pythagorean_triplets) numbers_sum = 1_000 def special_condition(numbers: Tuple[int, ...]) -> bool: return sum(numbers) == numbers_sum special_pythagorean_triplet, = filter(special_condition, pythagorean_triplets(numbers_sum)) assert multiply(special_pythagorean_triplet) == 31_875_000
def test_multiply(): from utils import multiply ans = multiply(2, 2) assert ans == 4
import utils print(utils.add(7, 9)) print(utils.multiply(7, 9))
def convert(celsius): fahrenheit = multiply(celsius, 1.8) return add(fahrenheit, 32)
import utils m = utils.opener.lines("input/03.txt") x, y, t = 0, 0, 0 while y < len(m): if m[y][x] == "#": t += 1 x = (x + 3) % len(m[0]) y += 1 print("1:", t) c = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] t = [0 for _ in range(len(c))] for i, (xi, yi) in enumerate(c): x, y = 0, 0 while y < len(m): if m[y][x] == "#": t[i] += 1 x = (x + xi) % len(m[0]) y += yi print("2:", utils.multiply(t))
def test_multiply_3_4(): assert multiply(3,4) == 12
def get_down(x, y): try: return multiply(data[x][y + i] for i in range(4)) except: return 0
numerator_digits = list(number_to_digits(numerator)) denominator_digits = list(number_to_digits(denominator)) try: common_digit, = set(numerator_digits) & set(denominator_digits) except ValueError: continue else: cancelled_numerator_digits = numerator_digits[:] cancelled_numerator_digits.remove(common_digit) cancelled_denominator_digits = denominator_digits[:] cancelled_denominator_digits.remove(common_digit) cancelled_numerator = digits_to_number(cancelled_numerator_digits) cancelled_denominator = digits_to_number( cancelled_denominator_digits) fraction = Fraction(numerator, denominator) cancelled_fraction = Fraction(cancelled_numerator, cancelled_denominator) fraction_is_curious = fraction == cancelled_fraction if fraction_is_curious: yield fraction def non_trivial_fraction(numerator: int, denominator: int) -> bool: return bool(numerator % 10 and denominator % 10) assert multiply(curious_fractions(numbers=range(10, 100))).denominator == 100
import random import pyjokes from utils import multiply, divide if __name__ == '__main__': print(multiply(5, 2)) print(divide(10, 2)) print(random) print(random.random()) print(random.randint(1,20)) print(random.choice(['a', 'b','c','d'])) joke = pyjokes.get_joke('en', 'neutral') print(joke)
from utils import multiply, divide # module from shopping.shopping_cart import buy # package print(multiply(2, 3)) print(divide(2, 3)) print(buy('apple'))