def test_matrix_change_value(): array = np.zeros((10, 10), dtype=int) matrix = Matrix(array) matrix.change_element_value((2, 6), 3) matrix.change_element_value((3, 5), 2) assert matrix.get_matrix()[2, 6] == 3 assert matrix.get_matrix()[3, 5] == 2
def build_matrix(matrix: Matrix) -> None: matrix.build_empty_matrix() for entry_position in matrix.entry_positions: position = None start_pointer = -1 if entry_position.command_index == -1 else entry_position.command_index for index in range(start_pointer, input_index): if position is None: position = entry_position.position else: position = get_new_position(input_[index], position) if matrix.is_position_out_of_limits(position): break else: matrix.set_visited_position(position)
def generate_computer_matrix(list_of_sizes, dim): ''' Creates matrix and fleet for bot. ''' matrix = generate_empty_matrix(dim) list_of_infos = [] for size in list_of_sizes: list_of_cords = [] check = False while not check: cords = create_random_cords(dim) direction = choose_direction() check = check_if_making_is_possible(size, cords, matrix, dim, direction) if check: first, second = cords[0], cords[1] if direction == 'poziom': for number in range(size): matrix[first, second + number] = 1 list_of_cords.append((first, second+number)) if direction == 'pion': for number in range(size): matrix[first + number, second] = 1 list_of_cords.append((first + number, second)) list_of_infos.append((size, list_of_cords, direction)) Bot_Matrix = Matrix(matrix) Bot_Fleet = Fleet(make_list_of_ships(list_of_infos)) return Bot_Matrix, Bot_Fleet
def get_matrix_containing_position(position: Position) -> Matrix: query = { "x_start": { "$lte": position.x }, "x_end": { "$gte": position.x }, "y_start": { "$lte": position.y }, "y_end": { "$gte": position.y } } matrix = matrices.find_one(query) if matrix is None: return None return Matrix(matrix["id"], matrix["x_start"], matrix["x_end"], matrix["y_start"], matrix["y_end"], [ EntryPosition(Position(entry["x"], entry["y"]), entry["command_index"]) for entry in matrix["entry_positions"] ])
def translate_matrix_based_on_command(command: str, matrix: Matrix) -> None: if command == "O": matrix.translate_O() elif command == "E": matrix.translate_E() elif command == "N": matrix.translate_N() elif command == "S": matrix.translate_S()
def test_missed1(): dim = 8 matrix = np.zeros((dim, dim), dtype=int) obj = Matrix(matrix) matrix[2, 6] = 2 cords = (2, 6) new = missed(obj, cords).get_matrix() assert (new == matrix).all()
def error_correcting_parser(grammar, input_string): # pylint: disable=R0914 """Takes a grammar and an input string and returns a tuple of the closest string in the grammar for that input string and the distance of the input string to the grammar (number of errors). """ input_size = len(input_string) list_x = Lookup(grammar.productions, input_size) cyk_matrix = Matrix(input_size) for i in range(1, input_size + 1): input_char = input_string[i - 1:i] for A, productions in grammar.terminals.items(): if input_char in productions: errors = productions[input_char].errors cyk_matrix.insert(A, i, i + 1, errors, productions[input_char]) list_x.insert(A, i, i + 1, errors) for depth in range(2, input_size + 1): for lhs, rhs, production in grammar.get_all(grammar.nonterminals): l_3 = production.errors B, C = rhs.split() for i, k, l_1 in list_x.get_all(B, depth, input_size): j_offset = i + depth cyk_cell = cyk_matrix.get(k, j_offset) if C in cyk_cell: l_total = l_1 + cyk_cell[C][1] + l_3 cyk_matrix.insert(lhs, i, j_offset, l_total, production) list_x.insert(lhs, i, j_offset, l_total) least_err = None for (_, k, errors) in list_x.get(Grammar.TOP_SYMBOL, 1).values(): if (k == input_size + 1) and (not least_err or errors < least_err): least_err = errors if least_err is None: raise LookupError('Correction not found. Incomplete input grammar.') tree = parse_tree(cyk_matrix, Grammar.TOP_SYMBOL, 1, input_size + 1, least_err, grammar.nonterminals) return least_err, tree
def generate_matrix(command: str) -> Matrix: global matrix_count matrix = Matrix(matrix_count, current_matrix.x_start, current_matrix.x_end, current_matrix.y_start, current_matrix.y_end, [EntryPosition(current_position, input_index)]) translate_matrix_based_on_command(command, matrix) matrix_count += 1 add_matrix_to_cache(matrix) return matrix
def test_hit(): dim = 8 matrix = np.zeros((dim, dim), dtype=int) m_obj = Matrix(matrix) ship1 = Ship(4, [(3, 2), (3, 3), (3, 4), (3, 5)], 'poziom') size = ship1.get_size() ship2 = Ship(3, [(2, 6)], 'pion') fleet = Fleet([ship1, ship2]) cords = (3, 2) lifes, m_obj, fleet = hit(m_obj, cords, fleet, dim) assert lifes < size
def error_correcting_parser(grammar, input_string): # pylint: disable=R0914 """Takes a grammar and an input string and returns a tuple of the closest string in the grammar for that input string and the distance of the input string to the grammar (number of errors). """ input_size = len(input_string) list_x = Lookup(grammar.productions, input_size) cyk_matrix = Matrix(input_size) for i in range(1, input_size + 1): input_char = input_string[i-1:i] for A, productions in grammar.terminals.items(): if input_char in productions: errors = productions[input_char].errors cyk_matrix.insert(A, i, i+1, errors, productions[input_char]) list_x.insert(A, i, i+1, errors) for depth in range(2, input_size + 1): for lhs, rhs, production in grammar.get_all(grammar.nonterminals): l_3 = production.errors B, C = rhs.split() for i, k, l_1 in list_x.get_all(B, depth, input_size): j_offset = i + depth cyk_cell = cyk_matrix.get(k, j_offset) if C in cyk_cell: l_total = l_1 + cyk_cell[C][1] + l_3 cyk_matrix.insert(lhs, i, j_offset, l_total, production) list_x.insert(lhs, i, j_offset, l_total) least_err = None for (_, k, errors) in list_x.get(Grammar.TOP_SYMBOL, 1).values(): if (k == input_size + 1) and (not least_err or errors < least_err): least_err = errors if least_err is None: raise LookupError('Correction not found. Incomplete input grammar.') tree = parse_tree(cyk_matrix, Grammar.TOP_SYMBOL, 1, input_size + 1, least_err, grammar.nonterminals) return least_err, tree
def make_player_matrix(list_of_sizes, dim): ''' Conducts creating player's matrix and fleet ''' list_of_infos = [] matrix = np.zeros((dim, dim), dtype=int) print(make_empty_board(dim)) while list_of_sizes: size = list_of_sizes[0] direction, location = get_info_about_ship(size, matrix, dim) for cord in location: first, second = cord matrix[first, second] = 1 list_of_infos.append((size, location, direction)) list_of_sizes.pop(0) print(show_actual_board(matrix, dim)) Player_Matrix = Matrix(matrix) Player_Fleet = Fleet(make_list_of_ships(list_of_infos)) print('Twoja finalna tablica') return Player_Matrix, Player_Fleet
def main(self, path): filename = path[-path[::-1].index("/"):] try: with open(path[:-4] + ".pickle", "rb") as file: print("Cached file verison found!\n") a = pickle.load(file) except FileNotFoundError: print("No cache found.\n") a = Wave(filename) with open(path[:-4] + ".pickle", "wb") as file: pickle.dump(a, file, protocol=pickle.HIGHEST_PROTOCOL) FOURIER_INCREMENT = 512 FOURIER_SIZE = 4096 results_dict = {} #for offset in range(130): for offset in range( (int(a.get_data()[0].get_dim()[0]) - (FOURIER_SIZE - FOURIER_INCREMENT)) // FOURIER_INCREMENT): b = Fourier(a.get_data()[0].section( offset * FOURIER_INCREMENT, (offset * FOURIER_INCREMENT + FOURIER_SIZE) - 1, "h"), pad=True) #Shortest note appears to be 0.012 seconds long, bin number of 512 final = Fourier.FFT( b ) # Once transform is complete the values must be converted to hz conversion_vector = a.convert_hertz( final ) # HO BOI, use this to look up from a conversion table to get hz results = Matrix([[abs(final[i][0])] for i in range(final.get_dim()[0] // 2)]) peak_pos = [ i[0] for i in Fourier.find_peaks(results, 30, 6, 0.1)._contents ] raw_peak_values = [] for i in range(0, len(peak_pos)): if peak_pos[i]: raw_peak_values += [i] filtered_peaks = Fourier.filter_peaks(raw_peak_values) hz_values = [conversion_vector[i][0] for i in filtered_peaks] filtereds_hz_values = [ h for h in Fourier.filter_peaks(hz_values) if h not in [333, 4026] ] results_dict[offset * FOURIER_INCREMENT] = list(filtereds_hz_values) with open(path[:-4] + "_data.json", "w") as file: file.write(json.dumps(results_dict).replace("], ", "],\n")) with open(path[:-4] + "_data.json", "r") as file: results_dict = json.loads(file.read()) midi_file = Midi() v = 0 error = 0 start_t = 0 end_t = 0 for key, value in results_dict.items(): if len(value) > 3: if value[0] in list(range(int(v - error), int(v + error))): v = (v + value[0]) / 2 else: end_t = key if v != 0: midi_file.add_note(start_t, end_t, v, 40) v = value[0] start_t = key error = v / 30 count = 1 for i, num in enumerate(value): if (i + 1) * v in list( range(int(num - (i + 1) * error), int(num + (i + 1) * error))): count += 1 print(f"strength {count}") midi_file.write(path[:-4] + ".mid")
def main(self, path): filename = path[-path[::-1].index("/"):] FOURIER_SIZE = 2048 FOURIER_INCREMENT = 256 filename = "3_notes.wav" print( f"\nProcessing begun on file '{filename}', this will take a while.\n" ) loadStartTime = time.time() try: with open(filename[:-4] + ".pickle", "rb") as file: print("Cached file version found!\n") wave_file = pickle.load(file) except FileNotFoundError: print("No cache found.\n") wave_file = Wave(path) with open(filename[:-4] + ".pickle", "wb") as file: pickle.dump(wave_file, file, protocol=pickle.HIGHEST_PROTOCOL) loadEndTime = time.time() print( f"* Wave load complete. Elapsed time {loadEndTime - loadStartTime} seconds." ) wave_channel = wave_file.get_channel(0) results_lst = [] for offset in range( (int(wave_channel.get_dim()[0]) - (FOURIER_SIZE - FOURIER_INCREMENT)) // FOURIER_INCREMENT): signal = Fourier(wave_channel.section( offset * FOURIER_INCREMENT, (offset * FOURIER_INCREMENT + FOURIER_SIZE) - 1, "h"), pad=True) results_lst.append(Fourier.rms(signal)) v = Matrix([[i] for i in results_lst]) x = [i[0] for i in Fourier.find_peaks(v, 10, 3, 0.1)] dividers = [] prev = 0 for i in range(1, len(x)): if x[i] == 1 and x[i - 1] == 0: if i - prev > 25: prev = i dividers.append(i) dividers.append(len(x)) self.progress.setValue(5) noteEndTime = time.time() print( f"* Note partitioning complete. Elapsed time {noteEndTime - loadEndTime} seconds." ) midi_file = Midi() if len(dividers) > 0: start = 0 total = len(dividers) for j in dividers: current = dividers.index(j) self.progress.setValue(int((current * 95) / total) + 5) end = j * FOURIER_INCREMENT # print(f"length - {start}, {end}") if start != end: signal = Fourier(wave_channel.section( start, (end) - 1, "h"), pad=True) signal = Fourier.blackman_harris(signal) corr = abs(Fourier.FFT(signal)) post = Fourier.median_filter(corr, 15).section( 0, corr.get_dim()[0] // 2, "h") value = max([i[0] for i in post]) pos = post._contents.index([value]) hz_post = wave_file.convert_hertz(post) # print(hz_post[pos][0]) if hz_post[pos][0] > 0: midi_file.add_note(start, end, hz_post[pos][0], 40) start = end else: length = 2**int( math.log(wave_file.get_data()[0].get_dim()[0] - 1, 2)) # print(f"length - {length}") signal = Fourier(wave_channel.section(0, length - 1, "h"), pad=True) corr = abs(Fourier.autocorrelation(signal)) post = Fourier.median_filter(corr, 15).section(0, corr.get_dim()[0] // 2, "h") fourierEndTime = time.time() print( f"* Fourier transforms complete. Elapsed time {fourierEndTime - noteEndTime} seconds." ) self.progress.setValue(100) midi_file.write(filename[:-4] + ".mid") endEndTime = time.time() print( f"* Midi file write complete. Elapsed time {endEndTime - fourierEndTime} seconds." ) print(f"Total elapsed time {endEndTime - loadStartTime} seconds.")
def add_new_entry_position_to_matrix(matrix: Matrix) -> None: global current_position entry_position = EntryPosition(current_position, input_index) matrix.add_new_entry_position(entry_position)
def test_matrix_getter(): array = np.zeros(10, dtype=int) matrix = Matrix(array) assert (matrix.get_matrix() == array).all()
def test_matrix_setter(): array1 = np.zeros(10, dtype=int) matrix = Matrix(array1) array2 = np.ones(10, dtype=int) matrix.set_matrix(array2) assert (matrix.get_matrix() == array2).all()