Exemplo n.º 1
0
 def generate_puzzle(self, words_clues=None):
     if not words_clues:
         print(
             "generate puzzle needs a list of words and clues in"
             "the following format [{'answer': 'வணக்கம்', 'clue': 'hello in tamil'}]"
         )
         return None
     result = []
     across = 1
     down = 1
     num_puzzle = len(words_clues) - 1
     while num_puzzle >= 0:
         rand_num = random.randint(0, num_puzzle)
         p = words_clues.pop(rand_num)
         num_puzzle -= 1
         if len(p['answer']) >= self.width:
             continue
         x = self._find_best_fit(p)
         x['startx'], x['starty'] = x['starty'], x['startx']
         if x['orientation'] == 'across':
             x['position'] = across
             across += 1
         else:
             x['position'] = down
             down += 1
         result.append(x)
         print_matrix(self.puzzle_matrix, self.width)
     print(result)
Exemplo n.º 2
0
def nice_print(result):
    if type(result) is list and type(result[0]) is list and type(result[0][0]) is not dict and type(result[0][0]) is not list:
        print_matrix(result)
    elif type(result) is list and type(result[0]) is not dict:
        for line in result: 
            print(line)
    else:
        print(json.dumps(result, indent=2))
Exemplo n.º 3
0
 def print(self):
     # Print the current state of all state (memory) elements of the CPU
     print_val(self.PC, "PC")
     print_mem(self.imem, "IMEM", val_width=16)
     print_mem(self.regfile, "Regfile", label_all=True)
     print_mem(self.dmem, "DMEM")
     print_input(self.buttons, "Input")
     print_matrix(self.matrix, "Output")
Exemplo n.º 4
0
 def pprint(self, show_labels=False):
     if show_labels:
         vertex_list = self.vertex_list or [
             Vertex(i) for i in range(self.shape[0])
         ]
         row_labels = [v.label for v in vertex_list]
         print_matrix(self, row_labels)
     else:
         print_matrix(self)
Exemplo n.º 5
0
def print_best(iteration, simulated_annealing, n_rows, n_columns):
    if simulated_annealing.get_best_point() != -1:
        print(f"\n---{iteration} iteration best working_point:")
        utils.print_matrix(simulated_annealing.get_best_point())
        print(f"---{iteration} iteration best score: {simulated_annealing.get_best_score()}")
        print(f"--{iteration} iteration best iteration: {simulated_annealing.best_score_iteration}")
        print(f"\n---{iteration} iteration best working point in original form:")
        utils.print_matrix(generate_accepted_output(simulated_annealing.entry_matrix, simulated_annealing.get_best_point(), n_rows, n_columns))
    else:
        print("\n---No best working_point!!! No feasible solution found!!!")
Exemplo n.º 6
0
def compute_cosine_matrices(speaker_files):
    speakers = []

    for s in speaker_files:
        print(s)
        vocab_file = s.replace("embeddings_",
                               "wordids_").replace(".npz", ".json")
        indices = get_common_word_indices(vocab_file, common_words)
        m = np.load(s)['arr_0']
        m = slice_matrix_in_order(m, indices)
        print_matrix(
            m, common_words,
            s.replace("embeddings_", "common_vocab_").replace(".npz", ".dm"))
        m_cos = compute_cosines(m)
        speakers.append(m_cos)
        print_matrix(
            m_cos, common_words,
            s.replace("embeddings_", "cosines_").replace(".npz", ".dm"))
    return speakers
Exemplo n.º 7
0
def main(use_penalty, input_field, number_of_iterations=100000, starting_temperature=90, init_generation_mode=0, author_penalty=150, university_penalty=200):

    if input_field == 'f':
        used_input = filozofia_input
    elif input_field == 'm':
        used_input = matematyka_input
    elif input_field == 'i':
        used_input = informatyka_techniczna_telekomunikacja_input
    else:
        print("---Unknown input field")
        return

    lp_matrix, score_matrix, contribution_matrix, author_limits, n_rows, n_columns = generate_accepted_input(used_input)
    if use_penalty:
        simulated_annealing = SimulatedAnnealingPenalty(lp_matrix, score_matrix, contribution_matrix, author_limits, number_of_iterations, starting_temperature, init_generation_mode, author_penalty, university_penalty)
    else:
        simulated_annealing = SimulatedAnnealingRepair(lp_matrix, score_matrix, contribution_matrix, author_limits, number_of_iterations, starting_temperature, init_generation_mode)
    
    pair_count = get_author_article_pairs_count(simulated_annealing.working_point)
    print(f"---Pair author/article count: {pair_count}")

    if number_of_iterations < 1000*pair_count:
        print("Too small number of iterations")
        print(f"Should be greater or equal: {1000*pair_count}")
        return
    
    print("---Entry matrix (score, contribution, unit gain): ")
    utils.print_matrix(simulated_annealing.entry_matrix)
    print("---Init working point: ")
    utils.print_matrix(simulated_annealing.working_point)
    print("\n---Init working point in original form:")
    utils.print_matrix(generate_accepted_output(simulated_annealing.entry_matrix, simulated_annealing.working_point, n_rows, n_columns))

    stop_list = [1, 10*pair_count, 100*pair_count, 1000*pair_count]

    print("\n---Running Simulated Annealing...")
    prev_iteration = 0
    for stop in stop_list:
        iterations = stop - prev_iteration

        working_point, score = simulated_annealing.simulated_annealing(iterations)
        prev_iteration = stop

        print(f"---After {stop} iterations:")
        print(f"---{simulated_annealing.best_score_iteration} best iteration score: {simulated_annealing.get_best_score()}")

    print_best(prev_iteration, simulated_annealing, n_rows, n_columns)

    working_point, score = simulated_annealing.simulated_annealing()
    print_best(number_of_iterations, simulated_annealing, n_rows, n_columns)
    elif args.exercise == 2:
        from tests import test_exercise_2
        test_exercise_2()
    elif args.exercise == 3:
        from tests import test_exercise_3
        test_exercise_3()
    elif args.exercise == 4:
        from tests import test_exercise_4
        test_exercise_4()
else:
    from utils import print_matrix
    #  print_heading(f'Solution to exercise {args.exercise}')

    if args.exercise == 1:
        from markov import exercise_1
        _, trans_table = exercise_1()
        print_matrix(trans_table)

    elif args.exercise == 2:
        from markov import exercise_2
        _, trans_table = exercise_2()
        print_matrix(trans_table)

    elif args.exercise == 3 or args.exercise == 4:
        from markov import exercise_3, exercise_4
        ((p1, std1), (p3, std3),
         (p9, std9)) = exercise_3() if args.exercise == 3 else exercise_4()

        for s, p, std in [(1, p1, std1), (3, p3, std3), (9, p9, std9)]:
            print(f'p(state = {s}) = {p}+-{std}')
def read_file(filename="input.mat"):
    '''
       Method - 1 . All params in the same file.
       Legacy code!
       File format:
       TRANSA TRANSB ALPHA BETA LDA LDB LDC M N K
       A
       B
       C
    '''
    A = None
    B = None
    C = None
    lines = []
    params = {}
    try:
        f = open(filename, "r")
        lines = f.readlines()
    except:
        print "Failed to open/read from file: " + filename
        raise
    line = lines[0].split(' ')
    try:
        params['TRANSA'] = line[0]
        params['TRANSB'] = line[1]
        params['ALPHA'] = float(line[2])
        params['BETA'] = float(line[3])
        params['LDA'] = int(line[4])
        params['LDB'] = int(line[5])
        params['LDC'] = int(line[6])
        params['M'] = int(line[7])
        params['N'] = int(line[8])
        params['K'] = int(line[9])
        if params['LDA'] < 0 or\
           params['LDB'] < 0 or\
           params['LDC'] < 0 or\
           params['M'] < 0 or\
           params['N'] < 0 or\
           params['K'] < 0:
            raise WrongParameterError(
                "One of the matrix dimensions is negative")
        # read matrix A[M][K]
        A = parse_matrix(lines[1:params['M'] + 1], params['M'], params['K'])
        # read matrix B[K][N]
        B = parse_matrix(
            lines[(params['M'] + 1):(params['M'] + params['K'] + 1)],
            params['K'], params['N'])
        # read matrix C
        C = parse_matrix(lines[(params['M'] + params['K'] + 1):], params['M'],
                         params['N'])
        print_matrix(A, "----Matrix A----", "----End of Matrix A----")
        print_matrix(B, "----Matrix B----", "----End of Matrix B----")
        print_matrix(C, "----Matrix C----", "----End of Matrix C----")
    except ValueError:
        print "Error when converting one of the parameters"
        raise
    except Exception as ex:
        raise
    if A == None or\
       B == None or\
       C == None:
        return None

    params['A'] = A
    params['B'] = B
    params['C'] = C
    f.close()
    return params
Exemplo n.º 10
0
import utils
from utils import print_matrix as my_print_matrix
from pprint import pprint as pp
import sys

print_matrix = True

utils.print_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

pp([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

pp(sys.path)

print("__name__:", __name__)
def play_pyano():
    n_folds = 5
    learning_rate = 0.1  # 1e-05
    n_epoch = 1500
    mu = 0.001
    filename = 'data-copy.csv'  # 'data.csv'

    dataset = utils.load_csv(filename)

    utils.ds_to_float(dataset)
    # print_dataset(dataset)

    # convert class column to integers
    last_column_index = len(dataset[0]) - 1
    utils.column_to_int(dataset, last_column_index)
    # print_dataset(dataset)

    # normalize input variables
    minmax = utils.min_max(dataset)
    # print(minmax)
    utils.normalize(dataset, minmax)

    folds = utils.cross_validation_split(dataset, n_folds)
    #for fold in folds:
    #print("Fold {} \n \n".format(fold))
    scores = list()

    predicted = []
    actual = []

    for fold in folds:
        train_set = list(folds)
        train_set.remove(fold)
        train_set = sum(train_set, [])
        test_set = list()
        for row in fold:
            row_copy = list(row)
            test_set.append(row_copy)
            row_copy[-1] = None
        predicted = train_and_predict(dataset, train_set, test_set, row,
                                      learning_rate, n_epoch, mu)
        actual = [row[-1] for row in fold]
        accuracy = utils.accuracy_met(actual, predicted)
        cm = confusion_matrix(actual, predicted)
        utils.print_matrix(cm)
        FP = cm.sum(axis=0) - np.diag(cm)
        FN = cm.sum(axis=1) - np.diag(cm)
        TP = np.diag(cm)
        TN = cm.sum() - (FP + FN + TP)
        print('False Positives\n{}'.format(FP))
        print('False Negatives\n{}'.format(FN))
        print('True Positives\n{}'.format(TP))
        print('True Negatives\n{}'.format(TN))
        TPR = TP / (TP + FN)
        print('Sensitivity \n{}'.format(TPR))
        TNR = TN / (TN + FP)
        print('Specificity \n{}'.format(TNR))
        Precision = TP / (TP + FP)
        print('Precision \n{}'.format(Precision))
        Recall = TP / (TP + FN)
        print('Recall \n{}'.format(Recall))
        Acc = (TP + TN) / (TP + TN + FP + FN)
        print('Áccuracy \n{}'.format(Acc))
        Fscore = 2 * (Precision * Recall) / (Precision + Recall)
        print('FScore \n{}'.format(Fscore))
        k = cohen_kappa_score(actual, predicted)
        print('Çohen Kappa \n{}'.format(k))
        scores.append(accuracy)
Exemplo n.º 12
0
import utils

matrix = [[0] * 5 for i in range(3)]

utils.print_matrix(matrix)
Exemplo n.º 13
0
def face_detect_main(options, cam_id=0):
    #装载训练好的模型
    model = Model()
    model.load_model(MODEL_PATH)
    #识别部分,分为使用图片进行识别,和利用摄像头中的实时图像进行识别
    if options == 'use_images':
        #如果选择使用现有图片来预测,则从62类的照片中每类任意抽出一张进行预测
        order_sheet, mini_id = generate_orderSheet(TEST_DATA)
        generate_testdata(TEST_DATA)
        image_visualization()
        predict = model.predict(images, image_num=len(labels))
        for i in range(len(labels)):
            predict[i] = order_sheet[predict[i]] + mini_id
            labels[i] = order_sheet[labels[i]] + mini_id
        print('[predict]')
        print_matrix(predict)
        print('[truth]')
        print_matrix(labels)
        print('accuracy: %d' % (cal_accuracy(predict, labels) * 100) + '%')
        image = Image.open('../test.png')
        image.show()

    elif options == 'use_camera':
        #默认使用电脑自带摄像头进行预测,修改camera_id可以选择使用外接摄像头
        camera_id = cam_id
        color = (255, 0, 255)
        cap = cv2.VideoCapture(camera_id)
        order_sheet, mini_id = generate_orderSheet(TEST_DATA)
        while True:
            #获取摄像头中实时图片并灰度化,减少分割出人脸时的计算量
            _, frame = cap.read()
            frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            #加载cascade分类器,并从图像中分割出人脸部分
            cascade = cv2.CascadeClassifier(cascade_path)
            faceRects = cascade.detectMultiScale(frame_gray,
                                                 scaleFactor=1.2,
                                                 minNeighbors=3,
                                                 minSize=(48, 48),
                                                 maxSize=(192, 192))

            if len(faceRects) > 0:
                for faceRect in faceRects:
                    x, y, w, h = faceRect
                    #send face image to network
                    image = frame[y - 30:y + h + 30, x - 30:x + w + 30]
                    image = cv2.cvtColor(resize_image(image, padding=True),
                                         cv2.COLOR_BGR2RGB).astype(
                                             np.float32) / 255
                    image = image.reshape(1, 64, 64, 3)
                    faceID = model.predict(image)
                    #using faceID to set the annotation
                    label = str(order_sheet[faceID] + mini_id)
                    cv2.rectangle(frame, (x - 10, y - 10),
                                  (x + w + 10, y + h + 10),
                                  color,
                                  thickness=2)

                    #文字提示是谁
                    cv2.putText(
                        frame,
                        label,
                        (x + 10, y - 40),  #坐标
                        cv2.FONT_HERSHEY_SIMPLEX,  #字体
                        1,  #字号
                        color,  #颜色
                        2)  #字的线宽
            cv2.imshow("face_detect", frame)

            #等待10毫秒看是否有按键输入
            k = cv2.waitKey(10)
            #如果输入q则退出循环
            if k & 0xFF == ord('q'):
                break
        #释放摄像头并销毁所有窗口
        cap.release()
        cv2.destroyAllWindows()
import os

from nussinov import Nussinov
from utils import FastaReader, pairs2parentheses, print_matrix

if __name__ == "__main__":
    nus = Nussinov()
    #seq = "ACCAGCU"
    seq = "GCGCUCUGAUGAGGCCGCAAGGCCGAAACUGCCGCAAGGCAGUCAGCGC"
    nus.seq = seq
    nus.fill_matrix()
    print_matrix(nus.V_matrix, seq=seq)
    pairs = nus.get_pairs()
    print(pairs)
    print(seq)
    parentheses = pairs2parentheses(pairs, len(seq))
    print(parentheses)
    print(parentheses.count("("))
Exemplo n.º 15
0
ex_path1 = sys.argv[1]  # Path de la première matrice
ex_path2 = sys.argv[2]  # Path de la deuxième matrice

# def looper(a, b, seuil):
#     start = time.time()
#     _ = strassen_seuil(a, b, seuil)
#     duration = (time.time() - start) * 1000
#     print(f'{seuil}\t{duration}')

if __name__ == "__main__":
    a = read_matrix(ex_path1)
    b = read_matrix(ex_path2)

    # seuil = 150

    seuil = len(a) // 2

    # for seuil in range(len(a)):
    #     looper(a, b, seuil)

    start = time.time()
    matrix = strassen_seuil(a, b, seuil)
    duration = (time.time() - start) * 1000

    options = sys.argv[3:]
    if '-p' in options:  # On imprime la matrice résultat
        # Données bidon, mais output du bon format demandé
        print_matrix(matrix)
    if '-t' in options:  # On imprime le temps d'exécution
        print(duration)  # Données bidon, mais output du bon format demandé ok
Exemplo n.º 16
0
    appendRecursively(fileTree, pathList)

setReachable(fileTree)
outputs = []
printRecursively(".", fileTree, True)



i = -1
def index():
    global i
    i +=1
    return "[%d]" % i

if not outputs:
    exit(1)
elif len(outputs) > 1:
    sys.stderr.write("Velg path:\n")
    print_matrix([["Index", "Path", "Antall filer"]] + map(lambda line: (index(), line[0], line[1]), outputs), sys.stderr)
    try:
        i = input()
    except:
        exit(1)
else:
    i = 0

git_root = Popen(["git", "root"], stdout=PIPE).communicate()[0]

print("%s/%s" % (git_root.rstrip(), outputs[i][0]))

Exemplo n.º 17
0
def begin_new_game(player1, player2):
    """
        This is the function that calls and makes all the necessary updates when the user enters a move
    """

    matrix = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]

    Global_variables.random_player_begin = Global_variables.next_player

    if Global_variables.random_player_begin == 0:

        Global_variables.random_player_begin = randint(1, 2)

    if Global_variables.random_player_begin == 1:

        Global_variables.next_player = 2

        current_player = player1

        print(current_player, end=" ")
        character = input("what character do you want to be? O or X: ")
        if character.upper() == "O":

            player1_character = "O"
            player2_character = "X"

        else:

            player1_character = "X"
            player2_character = "O"

    else:

        Global_variables.next_player = 1

        current_player = player2

        print(current_player, end=" ")
        character = input("what character do you want to be? O or X: ")
        if character.upper() == "O":

            player2_character = "O"
            player1_character = "X"

        else:

            player2_character = "X"
            player1_character = "O"

    while True:

        print_matrix(matrix)

        if current_player == player1:

            character = player1_character

        else:

            character = player2_character

        valid = True

        while valid:

            print(current_player,
                  "enter the position where you want to place",
                  character,
                  "?",
                  end=" ")
            move = int(input(""))

            if validate_move(move, matrix) == True:

                valid = False

            else:

                print(
                    "That move is not valid! You should consider entering a different position!"
                )

        make_move(move, matrix, character)

        if check_if_player_is_winner(character, matrix) == True:

            print("The winner of this match is ", current_player)

            if current_player == player1:

                Global_variables.player_one_score = Global_variables.player_one_score + 1

            else:

                Global_variables.player_two_score = Global_variables.player_two_score + 1

            return

        if current_player == player1:

            current_player = player2

        else:

            current_player = player1

        if can_continue(matrix) == True:

            print("It is a draw!")

            return
Exemplo n.º 18
0
from utils import print_matrix


def load_origins():
    return [Location(line.strip()) for line in open("origins.txt")]


def load_destinations():
    destinations = []
    with open("destinations.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            # Support empty lines and comments for easier readability of csv
            if not row or row[0].startswith("#"):
                continue
            destinations.append(
                Location(name=row[0],
                         address=row[1],
                         comment=row[2],
                         weight=float(row[3]),
                         mode=row[4]))
    return destinations


if __name__ == "__main__":
    force = len(sys.argv) == 2 and sys.argv[1] in {"--force", "-f"}
    streets_ahead = StreetsAheadService()
    origins, destinations = load_origins(), load_destinations()
    matrix = streets_ahead.summary(origins, destinations, force=force)
    print_matrix(matrix, sort_by='wa')
Exemplo n.º 19
0
    def Generate_OrderSheet(self):
        '''
        初始得到的标签列表元素为string类型
        首先将其转化为np.array
        然后根据得到的np.array中元素的大小,从小到大排序得到一张次序表
        然后遍历np.array,每一个元素在次序表中搜索对应,并用次序表中这个元素的下标
        来取代np.array中该元素的值
        这样就可以把一个string类型的列表转化为一个one-hot编码方式所需求得顺序np.array数组
        '''
        #using os operation to get the number of classes
        print(
            "============================================================================"
        )
        print(
            '||                 the original class labels is:                          ||'
        )
        print(
            "============================================================================"
        )
        #print labels
        folders = os.listdir(self.DATASET_ROOT_DIR)
        folders = np.asarray(folders, dtype=np.float32)
        print(folders)
        print(
            "============================================================================\n"
        )

        self.minimun_id = min(folders)
        print("=======================================")
        print('the minimum class label is: ' + str(self.minimun_id) + '||')
        print("=======================================\n")

        class_num = len(folders)
        self.predefined_class = class_num
        print("=================================================")
        print('the total number of predefined classes is: ' + str(class_num) +
              '||')
        print("=================================================\n")

        for folder in folders:
            temp = int(folder) - self.minimun_id
            self.relative_sheet = np.append(self.relative_sheet, temp)
        print(
            "============================================================================="
        )
        print(
            '||             the relative class label sheet is:                          ||'
        )
        print(
            "============================================================================="
        )
        print(self.relative_sheet)
        print(
            "=============================================================================\n"
        )

        self.order_sheet = Bubble_Sort(self.relative_sheet)
        print(
            "============================================================================="
        )
        print(
            '||                  generated order sheet:                                 ||'
        )
        print(
            "============================================================================="
        )
        print_matrix(self.order_sheet)
        print(
            "=============================================================================\n"
        )