def integrated_scheme(metric,
                      N=8,
                      k=4,
                      nb_pkts=100,
                      graph='BER',
                      channel='BSC'):
    print(
        '-------------------Integrated Scheme Code-----------------------------'
    )
    for key in [0.5]:
        G, infoBits = polar.polar_generator_matrix(64, k, channel, 0.1)
        k = len(G)
        Nt = len(G[1])
        t = int(Nt / N)

        U_k = utils.symbols_generator(k)  # all possible messages
        C = utils.integrated_function(infoBits, U_k, k, Nt, -1)

        X_m = utils.symbols_generator(t)  # all possible symbol sequences
        nx = 2**t * key
        # print('nx', nx, 't', t)
        x = utils.mapping(C, X_m, t, nx)
        N = len(x[1])
        if graph == 'BLER':
            metric[f"Int_P({key})"] = utils.block_error_probability(
                N, k, C, e0, e1)
        else:
            metric[f"Int_P({key})"] = utils.bit_error_rate(
                k, x, nb_pkts, e0, e1)
示例#2
0
def insertNodesPOIsNonPOIs():
    cnt = 0
    nodesError = open('Nodes_error.txt', 'w')
    poisError = open('POIs_error.txt', 'w')
    nonpoisError = open('NonPOIs_error.txt', 'w')
    for node in root.findall('node'):
        ver = node.attrib['version']
        lon = node.attrib['lon']
        lat = node.attrib['lat']
        point = "POINT(%s %s)" % (lon, lat)
        (ply, plx) = ut.mapping(float(lat), float(lon))
        planaxy = "POINT(%f %f)" % (plx, ply)
        nodeID = node.attrib['id']
        cnt += 1
        if(cnt % 1000 == 0):
            print('%s nodes inserted...' % cnt)
        try:
            cur.execute("insert into nodes(nodeID, version) values(%s, %s)", (nodeID, ver))
        except:
            print('Nodes Insert Error:', nodeID)
            nodesError.write(nodeID)
            nodesError.write('\n')
        if(ver == '1'):
            name = ''
            poitype = ''
            otherInfo = []
            for tag in node.findall('tag'):
                if(tag.attrib['k'] == 'name'):
                    name = tag.attrib['v']
                elif(tag.attrib['k'] == 'poitype'):
                    poitype = tag.attrib['v']
                else:
                    otherInfo.append(tag.attrib)
            # print("insert into pois(nodeID, position, name, poitype, otherInfo) values(%s, GeomFromText('%s'), %s, %s, %s)"% (nodeID, point, name, poitype, str(otherInfo)))
            try:
                cur.execute("insert into pois(nodeID, position, planaxy, name, poitype, otherInfo) values(%s, GeomFromText(%s), GeomFromText(%s), %s, %s, %s)", (nodeID, point, planaxy, name, poitype, str(otherInfo)))
            except:
                print('POIs Insert Error:', nodeID)
                poisError.write(nodeID)
                poisError.write('\n')
        else:
            otherInfo = []
            for tag in node.findall('tag'):
                otherInfo.append(tag.attrib)
            try:
                cur.execute("insert into nonpois(nodeID, position, planaxy, otherInfo) values(%s, GeomFromText(%s), GeomFromText(%s), %s)", (nodeID, point, planaxy, str(otherInfo)))
            except:
                print('NonPOIs Insert Error:', nodeID)
                nonpoisError.write(nodeID)
                nonpoisError.write('\n')
        db.commit()
    nodesError.close()
    poisError.close()
    nonpoisError.close()
示例#3
0
 def set_angle(self, angle):
     try:
         angle = int(angle)
     except:
         raise ValueError("Angle value should be int value, not %s" % angle)
     if angle < -90:
         angle = -90
     if angle > 90:
         angle = 90
     angle = angle + self.offset
     High_level_time = mapping(angle, -90, 90, self.MIN_PW, self.MAX_PW)
     pwr = High_level_time / 20000
     value = int(pwr * self.PERIOD)
     self.pin.pulse_width(value)
示例#4
0
def Query4ByLLR(lat, lon, rad):
    (y, x) = ut.mapping(lat, lon)
    cur.execute("set @poly='Polygon((%f %f,%f %f,%f %f,%f %f,%f %f))'" %
                (x - rad, y + rad, x + rad, y + rad, x + rad, y - rad, x - rad,
                 y - rad, x - rad, y + rad))
    cur.execute(
        'select nodeID,ST_AsText(position),name,poitype from POIs where MBRContains(ST_GeomFromText(@poly),planaxy)'
    )
    queryResult = cur.fetchall()
    ans = []
    for row in queryResult:
        coordinate = row[1].strip().split(' ')
        lons = float(coordinate[0][6:])
        lats = float(coordinate[1][:-1])
        d = ut.calc_dist(lat, lon, lats, lons)
        if d <= rad:
            ans.append((row[0], (lons, lats), row[2], row[3], d))
    return (sorted(ans, key=operator.itemgetter(4)))
示例#5
0
def linear_codes_mapping(metric, N=8, k=4, nb_pkts = 100, graph = 'BER'):
  print('-------------------Linear Code + Mapping-----------------------------')
  G = mat_gen.matrix_codes(64,k,'linear')
  if G!= []:
    for key in [0.55]:
      k = len(G)
      Nt = len(G[1])
      t = int(Nt/N)
      U_k= utils.symbols_generator(k)  # all possible messages
      X_m = utils.symbols_generator(t)  # all possible symbol sequences
      C = utils.matrix_codes(U_k, k, G, Nt)
      nx = 2**t*key
      # print('nx', nx, 't', t)
      x = utils.mapping(C, X_m, t, nx) #codebook after mapping
      N = len(x[1])

      if graph == 'BLER':
        metric[f"L+M({key})"] = utils.block_error_probability(N,k,x,e0,e1)
      else:
        metric[f"L+M({key})"] = utils.bit_error_rate(k,x,nb_pkts,e0,e1)
def trainModels(trainingData):

    # get test data of 50 instances
    X_test_set, y_test_set = read_OnlyTestData(dropFileName=True, returnXy=True)

    # get pickle files
    LogRegression = getPicklefile('LogisticRegression')
    Svc = getPicklefile('SVC')
    RFClassifier = getPicklefile('RandomForestClassifier')

    classifiers = [LogRegression,Svc,RFClassifier]

    scores = {}
    for execNo in range(len(trainingData)):

        tdata = trainingData[execNo]
        tdata = mapping(tdata)
        X = tdata.drop(['label','audio_name'],axis=1).values
        y = tdata['label']

        clf = classifiers[execNo]
        clfname = type(clf).__name__

        # retrain the model
        clf.fit(X,y)
        y_pred = clf.predict(X_test_set)
        score = accuracy_score(y_pred, y_test_set)
        scores[clfname] = score
        # save models to pickle
        savePickle(clf, clfname)

        #get previous score and save it
        oldscores = getPicklefile(clfname+'_scores')

        oldscores.append(score)
        #print "OLD",oldscores
        # save scores to pickle
        savePickle(oldscores, clfname + '_scores')

    return scores
示例#7
0
def Query5ByLL(lat, lon):
    (y, x) = ut.mapping(lat, lon)
    rad_ori = 10
    rad = rad_ori * 1.33
    queryResult = []
    flag = 1
    ans = []
    while True:
        cur.execute("set @poly='Polygon((%f %f,%f %f,%f %f,%f %f,%f %f))'" %
                    (x - rad, y + rad, x + rad, y + rad, x + rad, y - rad,
                     x - rad, y - rad, x - rad, y + rad))
        cur.execute(
            'select nodeID,ST_AsText(position) from nonPOIs where MBRContains(ST_GeomFromText(@poly),planaxy)'
        )
        queryResult = cur.fetchall()
        ans = []
        for row in queryResult:
            coordinate = row['ST_AsText(position)'].strip().split(' ')
            lons = float(coordinate[0][6:])
            lats = float(coordinate[1][:-1])
            d = ut.vin_dist(lat, lon, lats, lons)
            if d <= rad_ori:
                ans.append((row['nodeID'], (lons, lats), d))
        ls = (sorted(ans, key=operator.itemgetter(2)))
        for each in ls:
            cur.execute(
                "select ways.wayid, ways.name, ways.isRoad, ways.otherinfo from waynode, ways where waynode.nodeid=%s and waynode.wayid=ways.wayid and ways.isroad <> '0'"
                % (each[0]))
            queryRes = cur.fetchall()
            if len(queryRes) > 0:
                ans = queryRes
                flag = 0
                break
        if flag == 0:
            break
        else:
            rad_ori = rad_ori * 2.7
            rad = rad_ori * 1.33
    return ans
示例#8
0
        x, y = x / res + grid.shape[0] // 2, y / res + grid.shape[1] // 2
        cor = mapCorrelation(temp, x_im, y_im, np.vstack((x, y)),
                             (X[i][0] + xs) / res, (X[i][1] + ys) / res)
        cors.append(np.max(cor))

    cors = W * np.array(cors)
    W = softmax(cors)

    best = np.where(W == np.max(W))[0][0]
    now = X[best].copy()
    now[0] /= res
    now[1] /= res
    img_name = 'rgb%d_%d.png' % (dataset, cor_rgb[lidar_index])
    depth_name = 'disparity%d_%d.png' % (dataset, cor_depth[lidar_index])

    grid = mapping(grid, lidar, now, res, lidar_angles)
    now_texture = now.copy()

    texture_map = texture_mapping(texture_map, now_texture, res, img_name,
                                  depth_name)
    n_eff = 1 / (W**2).sum()
    if n_eff < 0.85 * N:
        idx = stratified_resample(W)
        X[:] = X[idx]
        W.fill(1 / N)

    slam_map[int(now[0]) + slam_map.shape[0] // 2,
             int(now[1]) + slam_map.shape[1] // 2] = 1
    walk_map[int(robot_pos[lidar_index, 0] / res) + walk_map.shape[0] // 2,
             int(robot_pos[lidar_index, 1] / res) + walk_map.shape[1] // 2] = 1
示例#9
0
def game_make():
    screen = pygame.display.set_mode(SCREEN_SHAPE)
    pygame.display.set_caption('Color Sokoban')  # 타이틀바의 텍스트를 설정
    tool = 0

    # 게임판을 저장, 불러오기할 수 있는 버튼과 게임판을 만드는데 필요한 도구를 선택할 수 있는 버튼을 생성합니다.
    save_button = Button((10, 10, 40, 30), WHITE, BLACK, 16, 'Save')
    load_button = Button((50, 10, 40, 30), WHITE, BLACK, 16, 'Load')
    red_button = Button((100, 10, 60, 30), WHITE, RED, 16, 'RedStone')
    blue_button = Button((170, 10, 60, 30), WHITE, BLUE, 16, 'BlueStone')
    yellow_button = Button((240, 10, 60, 30), WHITE, YELLOW, 16, 'YellowStone')
    brick_button = Button((310, 10, 60, 30), WHITE, BROWN, 16, 'Brick')
    player_button = Button((380, 10, 60, 30), WHITE, PINK, 16, 'Player')
    erase_button = Button((450, 10, 40, 30), WHITE, GRAY, 16, 'Erase')

    button_list = [
        red_button, blue_button, yellow_button, brick_button, player_button,
        erase_button
    ]
    tools = [RED_STONE, BLUE_STONE, YELLOW_STONE, BRICK, PLAYER,
             EMPTY]  # 각 버튼에 맞는 도구를 지정합니다.

    screen.fill(WHITE)
    for button in button_list:
        button.draw(screen)
    save_button.draw(screen)
    load_button.draw(screen)

    board = utils.make_2D_array(TABLE_SHAPE)

    board_rect = pygame.Rect(60, 60, 400, 400)  # 게임판의 위치를 설정합니다.
    board_painter = BoardPainter(
        board_rect, TABLE_SHAPE)  # 게임판을 그리기 위한 BoardPainter를 생성합니다.

    done = False
    while not done:
        for event in pygame.event.get():

            for i in range(len(button_list)):
                if button_list[i].is_clicked(event):
                    tool = tools[i]  # i번째 버튼이 눌렀을 경우 도구를 i번째 도구로 설정합니다.

            if save_button.is_clicked(event):  # save button을 눌렀을 경우
                filename = game_input()  # filename을 입력받습니다.
                filename = 'maps/' + filename
                try:
                    file_handle.save_board(filename,
                                           board)  # 게임판을 filename에 저장합니다.
                    done = True
                except:
                    pass

            elif load_button.is_clicked(event):  # load button을 눌렀을 경우
                filename = game_input()  # filename을 입력받습니다.
                filename = 'maps/' + filename
                try:
                    board = file_handle.load_board(
                        filename)  # file_handle 모듈의 load_board를 통해 게임판을 불러옵니다.
                    screen.fill(WHITE)  # 화면을 초기화 해줍니다.
                    for button in button_list:
                        button.draw(screen)
                    save_button.draw(screen)
                    load_button.draw(screen)
                except:
                    board = utils.make_2D_array(
                        TABLE_SHAPE
                    )  # 불러오기를 실패했을 경우 TABLE_SHAPE형태로 비어있는 2차원 배열을 만들어줍니다.

            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True

            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pos()
                if board_rect.collidepoint(mouse):  # mouse가 게임판을 클릭했을 경우
                    x, y = utils.mapping(
                        mouse, (board_rect[0], board_rect[1]),
                        (board_rect[2], board_rect[3]),
                        TABLE_SHAPE)  # 클릭한 부분을 TABLE_SHAPE크기에 맞도록 변환한다.
                    board[y][x] = tool  # board[y][x]에 tool값을 넣어준다.

                    if utils.is_stone(tool):  # tool이 stone일 경우 portal로 변환시킨다.
                        tool = utils.stone_to_portal(tool)
                    elif utils.is_portal(
                            tool):  # tool이 portal일 경우 stone으로 변환시킨다.
                        tool = utils.portal_to_stone(tool)

        board_painter.draw_board(screen, board)

        pygame.display.flip()