Esempio n. 1
0
    def setPlaces(self, waypoints):
        i = 1
        while i <= len(self.order):
            pivot = str(i)
            neighbor = str(i+1)
            #check if there is a right neighbor and distance is calculable
            if i + 1 <= len(self.order) and self.order[pivot].score < len(waypoints) and self.order[neighbor].score < len(waypoints):
                #see if right neighbor surpassed i in the placement
                pivotDist = utils.getDistance(self.order[pivot].pos, waypoints[self.order[pivot].score].pos)
                neighborDist = utils.getDistance(self.order[neighbor].pos, waypoints[self.order[neighbor].score].pos)
                if (self.order[pivot].score < self.order[neighbor].score) or (self.order[pivot].score == self.order[neighbor].score and neighborDist < pivotDist):
                    #swap 
                    ent = self.order[pivot]
                    self.order[pivot] = self.order[neighbor]
                    self.order[pivot].place = i
                    self.order[neighbor] = ent
                    self.order[neighbor].place = i+1
                    #decrement i to see if the right neighbor surpassed anyone else -2
                    i -= 2
                    if i < 1:
                        i = 1
            i += 1

        # adjust ai max speed
        if self.ai[0].place > 1:
            self.ai[0].maxSpeed += 1
        else:
            self.ai[0].maxSpeed -= 1
        # cap off max speed
        if self.ai[0].maxSpeed > 250:
            self.ai[0].maxSpeed = 250
        elif self.ai[0].maxSpeed < 150:
            self.ai[0].maxSpeed = 150
Esempio n. 2
0
def isValidDetections(target_coordinates, pred_coordinates):
    bestDistance = 100000000
    for permutation in itertools.permutations(pred_coordinates.reshape(-1, 2)):
        distance = 0
        for i in range(len(permutation)):
            distance += getDistance(permutation[i][0], permutation[i][1],
                                    target_coordinates[i * 2],
                                    target_coordinates[i * 2 + 1])
        if distance < bestDistance:
            bestPermutation = permutation
            bestDistance = distance

    valid = []
    invalid = []
    limit = getDistance(0, 0, 256, 256) * 0.05
    for i in range(len(bestPermutation)):
        distance = getDistance(bestPermutation[i][0], bestPermutation[i][1],
                               target_coordinates[i * 2],
                               target_coordinates[i * 2 + 1])
        if distance < limit:
            valid.append(bestPermutation[i][0])
            valid.append(bestPermutation[i][1])
        else:
            invalid.append(bestPermutation[i][0])
            invalid.append(bestPermutation[i][1])
    return np.reshape(np.array(valid),
                      (-1, 2)), np.reshape(np.array(invalid), (-1, 2))
Esempio n. 3
0
def gridToBalls(grid, nballs, otherHand=None):
    gridSurface = grid[:, :, 0]
    gridWidth = grid.shape[0]
    gridHeight = grid.shape[1]
    minDistance = getDistance(0, 0, 256, 256) * 0.04
    boxWidth = 256 // gridWidth
    boxHeight = 256 // gridHeight
    ballList = []
    for i in range(nballs):
        while True:  # While ball candidate not accepted
            x, y = np.unravel_index(np.argmax(gridSurface),
                                    (gridWidth, gridHeight))
            ballX = int(boxWidth * x + boxWidth * grid[x, y, 1])
            ballY = int(boxHeight * y + boxHeight * grid[x, y, 2])
            gridSurface[x, y] = -1
            acceptable = True
            for j in range(0, len(ballList), 2):
                if getDistance(ballX, ballY, ballList[j],
                               ballList[j + 1]) < minDistance:
                    acceptable = False
            if otherHand is not None:
                if getDistance(ballX, ballY, otherHand[0],
                               otherHand[1]) < minDistance:
                    acceptable = False
            if acceptable:
                ballList.append(ballX)
                ballList.append(ballY)
                break
    return np.array(ballList)
Esempio n. 4
0
def tiebian():
    global sidePoints
    sidePoints = np.array(sidePoints)
    yawAim = getYawAim(sidePoints)
    log.info('已加载导航点,共有%d个点' % len(sidePoints))
    index = 0
    pos = Point(g.getValue('ship').lat, g.getValue('ship').lng)
    # 判断刚开始时,是否需要原地转
    state = State.TURN if utils.getDistance(
        pos, Point(sidePoints[0, 0], sidePoints[0, 1])) > 3 else State.GO
    try:
        while index < len(sidePoints):
            yaw = g.getValue('ship').yaw
            lat = g.getValue('ship').lat
            lng = g.getValue('ship').lng
            gz = g.getValue('ship').gz
            speed = g.getValue('ship').speed
            pShip = Point(lat, lng)
            pAim = Point(sidePoints[index, 0], sidePoints[index, 1])
            isFirst = True if index == 0 else False
            if state == State.TURN:
                thrust = 0
                dire = PID_Turn(pShip, pAim, yaw, -gz, yawAim[index], isFirst)
                if dire == 0:
                    # 转弯完毕,进入直行阶段
                    state = State.GO
            elif state == State.GO:
                # 判断直线段或是曲线段,之后五个点期望角度最大误差
                slowSpeed = True if angleArray_ptp(
                    yawAim[index:index + 5]) > 15 or index == 0 else False
                log.info('Go:当前期望方向角 %.1f 度,slowSpeed是 %s' % yawAim[index],
                         slowSpeed)
                dire, thrust = PID_Go(pShip, pAim, yaw, -gz, yawAim[index],
                                      slowSpeed, isFirst)

            dist = utils.getDistance(pShip, pAim)
            if state == State.GO and index > 0:
                # 将最近点序号作为当前序号
                index = index_cal(pShip, index,
                                  SearchLength=10)  #函数中使用了global量sidePoints
                log.info('当前处于第 %d 个点' % index)
            if dist < 1 and index == 0:
                state = State.TURN
                index += 1
            if index == len(sidePoints):
                # 跑完
                thrust = 0
                dire = 0
            data = struct.pack("hhb", int(thrust), int(dire), 0)
            g.getValue("can").send(0x544, data)
            log.info("%s\t%d\t%.1f\t%.1f\t%d" %
                     (state, index, thrust, dire, dist))
            time.sleep(1)
    except Exception:
        log.error('贴边Error', exc_info=True)

    log.info('导航结束')
Esempio n. 5
0
    def updateHover(self):
        self.invalid = False
        self.hover_edge = None
        self.hover_node = None
        self.hover_pos = None

        if self.last_node:
            # Lock the hover position to an angle from last node
            locked_x, locked_y = utils.getAngleLockedPosition(8, mouse.x - self.last_node.x, mouse.y - self.last_node.y)
            angle_x, angle_y = self.last_node.x + locked_x, self.last_node.y + locked_y
            self.hover_pos = angle_x, angle_y
        else:
            angle_x, angle_y = mouse.x, mouse.y

        # Snap to node
        snap_node = None
        for node in loop.graph.nodes:
            dist = utils.getDistance((angle_x, angle_y), (node.x, node.y))
            if node.type is Signal.type:
                continue

            if dist == 0:
                if snap_node is None:
                    snap_node = (dist, node)
                elif dist < snap_node[0]:
                    snap_node = (dist, node)

        if snap_node:
            self.hover_pos = snap_node[1].x, snap_node[1].y
            self.hover_edge = None
            if self.last_node and snap_node in self.last_node.nbors:  # No back-tracking
                self.invalid = True
            else:
                self.hover_node = snap_node[1]
                if self.hover_node.isBusy():
                    self.invalid = True
                return
        else:
            # Snap to edge
            snap_edge = utils.getPointClosestToEdge(loop.graph.edges.keys(), angle_x, angle_y)
            if snap_edge:
                distance, n_edge, point = snap_edge
                if distance == 0:
                    self.hover_pos = angle_x, angle_y
                    self.hover_edge = n_edge
                    # If too close to a signal or edge is busy, it's invalid
                    if any(utils.getDistance(point, (node.x, node.y)) < self.signal_spacing
                           for node in n_edge if node.type is Signal.type) or loop.graph.getEdge(*n_edge).isBusy():
                        self.invalid = True
                    return
            self.hover_pos = angle_x, angle_y
Esempio n. 6
0
def PID_Go(pShip, pAim, yawShip, gz):  # 直行段PID
    global thrust_last  # 上一时刻油门值
    PID_P = 0.5
    # PID_D = 0 在下面if结构中定义
    yawAim = utils.getAimYaw(pShip, pAim)  # 期望方向角
    error = utils.angleDiff(yawAim, yawShip)  # 方向角误差
    dist = utils.getDistance(pShip, pAim)  # 距离误差
    if error * gz > 0:
        PID_D = -0.8
    else:
        PID_D = 0.8
    dire = PID_P * error + gz * PID_D
    dire = max(dire, -100)
    dire = min(dire, 100)

    thrust = 100 - abs(error) * 3
    if dist < 10:  # 接近段
        tar_speed = dist / 8 - abs(error) / 20  # 目标速度
        tar_speed = max(tar_speed, 0.2)  # 目标速度限幅在0.2到1之间
        tar_speed = min(tar_speed, 1)
        err_speed = tar_speed - speed
        thrust = thrust_last + err_speed * 50
    thrust = abs(thrust)
    thrust = max(thrust, 10)  # 下限是10
    thrust = min(thrust, 100)  # 上限100
    thrust_last = thrust
    return int(dire), thrust
Esempio n. 7
0
 def exploreGetData(self):
     print("CURRENT STATE: EXPLORE")
     print("CURRENT SUBSTATE: DATA ACQUISITION")
     self.distance = utils.getDistance()
     self.lastIMU = self.currentIMU
     self.currentIMU = self.imu.getImuRawData()
     self.exploreState = mbl_bots.PROCESSDATA
Esempio n. 8
0
def min_distance(mc):
    """

    :param mingcheng: 用户输入的景区名称
    :return: 返回距离从近到远排序的字典
    """
    #先得到用户输入景点的经纬度
    NODE_des = N_selector.match("名称", name=mc).first()
    R_lng1 = R_selector.match((NODE_des,), "经度").first()
    R_lat1 = R_selector.match((NODE_des,), "纬度").first()
    lng1 = R_lng1.end_node['name']
    lat1 = R_lat1.end_node['name']
    R_province = R_selector.match((NODE_des,), "省份").first()
    province = R_province.end_node
    R_same_province_des=R_selector.match((province,), "省2名")

    des={ }
    for i in R_same_province_des: #i是省份和景点的关系
        #print(i)
        d=i.end_node
        R_lng2 = R_selector.match((d,), "经度").first()
        R_lat2 = R_selector.match((d,), "纬度").first()
        lng2 = R_lng2.end_node['name']
        lat2 = R_lat2.end_node['name']
        dis=utils.getDistance(lat1, lng1, lat2, lng2)
        des[d['name']]=dis

     print(sorted(des.items(), key=lambda kv: (kv[1], kv[0])))
Esempio n. 9
0
    def updateHover(self):
        self.invalid = False
        self.hover_edge = None
        self.hover_node = None
        self.hover_pos = None

        # Snap to node
        snap_node = None
        for node in loop.graph.nodes:
            if not node.type is Signal.type:
                continue
            dist = utils.getNodeDistance(mouse, node)
            if dist < self.snap_distance:
                if snap_node is None:
                    snap_node = (dist, node)
                elif dist < snap_node[0]:
                    snap_node = (dist, node)

        if snap_node is not None:
            self.hover_node = snap_node[1]
            self.hover_pos = snap_node[1].x, snap_node[1].y
        else:
            # Snap to edge
            snap_edge = utils.getPointClosestToEdge(loop.graph.edges.keys(), mouse.x, mouse.y)
            if snap_edge:
                distance, n_edge, point = snap_edge
                if distance < self.snap_distance:
                    self.hover_edge = n_edge
                    self.hover_pos = point
                    # If too close to a signal or edge is busy, it's invalid
                    if any(utils.getDistance(point, (node.x, node.y)) < self.signal_spacing
                           for node in n_edge if node.type is Signal.type) or loop.graph.getEdge(*n_edge).isBusy():
                        self.invalid = True
                    return
Esempio n. 10
0
def evaluate(agent_net):

    n = config.Map.Height
    m = config.Map.Width

    mazemap = []
    for i in range(n):
        mazemap.append([])
        for j in range(m):
            mazemap[i].append(np.zeros(4))
            utils.setCellValue(mazemap, i, j, np.random.binomial(1, config.Map.WallDense))

    cell_value_memory = {}
    open(config.StrongMazeEnv.EvaluateFile, 'w')

    for distance in range(1, n + m):
        sum_score = 0
        for sx in range(n):
            for sy in range(m):
                if utils.equalCellValue(mazemap, sx, sy, utils.Cell.Wall):
                    continue
                utils.setCellValue(mazemap, sx, sy, utils.Cell.Source)
                score = 0
                count = 0
                output = ''
                for tx in range(n):
                    for ty in range(m):
                        if utils.equalCellValue(mazemap, tx, ty, utils.Cell.Empty) and utils.getDistance(sx, sy, tx, ty) <= distance:
                            count += 1
                            utils.setCellValue(mazemap, tx, ty, utils.Cell.Target)
                            memory_id = str(sx) + '_' + str(sy) + '_' + str(tx) + '_' + str(ty)
                            if memory_id in cell_value_memory:
                                dir_id = cell_value_memory[memory_id]
                            else:
                                dir_id = np.array(agent_net.predict(np.array([[mazemap]]))).argmax()
                                cell_value_memory[memory_id] = dir_id
                            output += utils.dir_symbols[dir_id]
                            utils.setCellValue(mazemap, tx, ty, utils.Cell.Empty)
                            if utils.getDistance(sx, sy, tx, ty) > utils.getDistance(sx + utils.dirs[dir_id][0], sy + utils.dirs[dir_id][1], tx, ty):
                                score += 1
                sum_score += float(score) / count
                utils.setCellValue(mazemap, sx, sy, utils.Cell.Empty)
        sum_score /= n * m
        print [distance, sum_score]
        f = open(config.StrongMazeEnv.EvaluateFile, 'a')
        f.write(str(distance) + '\t' + str(sum_score) + '\n')
        f.close()
Esempio n. 11
0
    def findEndPos(self, city, agent_id):
        start_pos = self.agent_pos[agent_id]
        min_distance = -1
        if city == -1:
            for i in range(len(self.source_pos)):
                distance = utils.getDistance(self.source_pos[i], start_pos)
                if min_distance == -1 or distance < min_distance:
                    min_distance = distance
                    end_pos = self.source_pos[i]
        else:
            for i in range(len(self.hole_pos)):
                if self.hole_city[i] != city:
                    continue
                distance = utils.getDistance(self.hole_pos[i], start_pos)
                if min_distance == -1 or distance < min_distance:
                    min_distance = distance
                    end_pos = self.hole_pos[i]

        return end_pos
Esempio n. 12
0
    def computeFittingError(self, data, model):

        totalDist = 0

        for data in data:
            dist = getDistance(data, model[0], model[1], model[2], model[3],
                               model[4])
            totalDist = totalDist + dist

        return totalDist
Esempio n. 13
0
def filterIndexes(data, indexes, threshold, model) :

    filteredIndexes = [] 

    for index in indexes : 
        temp = data[index]
        dist = getDistance(temp, model[0], model[1], model[2], model[3], model[4])
        if (dist < threshold) : 
            filteredIndexes.append(index)

    return filteredIndexes
def calc(center, cluster):
    ''' 
    'center' is a candidate for the cluster center
    'cluster' has all the points in the cluster
    The return value indicates how far all the points are from the candidate center
    '''
    distList = []
    for c in range(len(cluster)):
        dist = utils.getDistance(center, cluster[c])
        distList.append(dist)
    return np.sqrt(sum(i * i for i in distList))
Esempio n. 15
0
 def exploreGetData(self):
     print("CURRENT STATE: EXPLORE")
     print("CURRENT SUBSTATE: DATA ACQUISITION")
     self.distance = utils.getDistance()
     self.lastIMU = self.currentIMU
     self.currentIMU = self.imu.getImuRawData()
     start_time = time.time()
     self.frame = self.camera.getFrame()
     self.camera.truncateFrame()
     end_time = time.time()
     print('It took me {} s to get the frame'.format(start_time - end_time))
     self.exploreState = mbl_bots.PROCESSDATA
Esempio n. 16
0
def assign(data, clusterCtrs):
    # Assign each point to one of the clusters
    clusterAssignments={}
    for idx in range(len(data)):
        shortestDist=np.inf
        bestCluster=None
        for n in range(len(clusterCtrs)):
            dist=utils.getDistance(clusterCtrs[n], data[idx])
            if dist<shortestDist:
                bestCluster=n
                shortestDist=dist
        clusterAssignments[idx]=bestCluster
    return clusterAssignments
Esempio n. 17
0
def index_cal(pos, index, SearchLength=10):
    # 计算当前点之后的SearchLength个点中距离当前最近的点的序号
    # 输入参数
    # pos为当前位置
    # index为当前点序号
    # SearchLength为搜索序列长度
    # 输出:距离最近的点序号
    global sidePoints
    if index + SearchLength > len(sidePoints):
        SearchLength = len(sidePoints) - index
    dist_list = list()
    for ii in range(SearchLength):
        dist_list.append(utils.getDistance(pos, sidePoints[ii + index]))
    index_max = dist_list.index(max(dist_list))
    return index_max + index
Esempio n. 18
0
def getNearestNeighbor(data, cfg):
    ''' Return a dictionary with the closest neighbor of each time series '''
    d = {}
    for a in range(len(data)):
        shortest = np.inf
        neighbor = None
        for b in range(len(data)):
            if a == b:
                pass
            else:
                dist = utils.getDistance(data[a], data[b])
                if dist < shortest:
                    shortest = dist
                    d[a] = b
    return d
Esempio n. 19
0
def filter(data, center):
    ''' Remove two sets of points:
       - most distant from the center
       - closest to the center
    Neither one will make good cluster centers '''
    distances = []
    for idx in range(len(data)):
        d = utils.getDistance(center, data[idx])
        distances.append((idx, d))
    distances.sort(key=lambda n: n[1])
    # remove closest 10%
    closest = int(len(data) * .1)
    distances = distances[closest:]
    # remove furthest 10%
    furthest = int(len(distances) * .9)
    distances = distances[:furthest]
    return distances
Esempio n. 20
0
    def process(self, position):
        if self.previousPosition is not None:
            if getDistance(position[0], position[1], self.previousPosition[0],
                           self.previousPosition[1]) < self.maxDistance:
                self.streak += 1
                if self.streak >= 1:
                    self.streakPosition = position
                    self.timeSinceStreak = 0
            else:
                self.streak = 0
                self.timeSinceStreak += 1

        self.previousPosition = position
        if self.streakPosition is not None and self.timeSinceStreak < 2:
            return self.streakPosition
        else:
            return position
Esempio n. 21
0
    def getPath(self, train):
        if not train.end and train.destination is train.start:
            return []
        if train.end is train.destination:
            return [train.end]
        node_data = {train.end: self.DataItem(None, 0, 0)}
        open_list = [train.end]
        closed_list = []
        current_node = train.end
        last_node = train.start  # For one-way rule
        while True:
            for nbor in current_node.nbors:
                if nbor is train.destination:
                    path = [nbor]
                    node = current_node
                    while node is not train.end:
                        path.append(node)
                        node = node_data[node].parent
                    return list(reversed(path))

                if nbor is last_node or nbor in closed_list:  # Enforce one-way rule (nbor is last_node)
                    continue

                edge = self.graph.getEdge(current_node, nbor)
                if nbor in open_list:
                    g = node_data[current_node].g + edge.length
                    if g < node_data[nbor].g:
                        node_data[nbor].g = g
                        node_data[nbor].parent = current_node
                else:
                    node_data[nbor] = self.DataItem(current_node,
                                                    node_data[current_node].g + edge.length,
                                                    utils.getDistance((train.destination.x, train.destination.y),
                                                                      (nbor.x, nbor.y)))
                open_list.append(nbor)

            open_list.remove(current_node)
            closed_list.append(current_node)
            last_node = current_node

            if not open_list:
                return []

            current_node = sorted([(node_data[node].g + node_data[node].h, node) for node in open_list],
                                  key=lambda x: x[0], reverse=True)[-1][1]
Esempio n. 22
0
def PID_Go(pShip,
           pAim,
           yawShip,
           gz,
           yawOpt,
           slowSpeed=True,
           isFirst=True):  # 直行段PID
    global thrust_last  # 上一时刻油门值
    PID_P = 0.5
    # PID_D = 0 在下面if结构中定义
    if isFirst == True:
        yawAim = utils.getAimYaw(pShip, pAim)  # 期望方向角
    else:
        yawAim = yawOpt
        # *********************补偿项***************注意,距离小的时候不准
        # if utils.getAimYaw(pShip, pAim)>5:
        #     weight=np.array([0.7,0.3])
        #     yawAim=angleWeightSum(np.array(yawOpt,utils.getAimYaw(pShip, pAim)),weight)
        # else:
        #     yawAim=yawOpt
    error = utils.angleDiff(yawAim, yawShip)  # 方向角误差
    dist = utils.getDistance(pShip, pAim)  # 距离误差
    if error * gz > 0:
        PID_D = -0.8
    else:
        PID_D = 0.8
    dire = PID_P * error + gz * PID_D
    dire = max(dire, -100)
    dire = min(dire, 100)

    thrust = (100 - abs(error) * 3) * 0.8
    tar_speed = 0
    if dist < 0.8 and slowSpeed == True:
        tar_speed = dist / 1.5 - abs(error) / 20  # 目标速度
        tar_speed = max(tar_speed, 0.2)  # 目标速度限幅在0.2到1之间
        tar_speed = min(tar_speed, 1)
        err_speed = tar_speed - speed
        thrust = thrust_last + err_speed * 50
    thrust = abs(thrust)
    thrust = max(thrust, 10)  # 下限是10
    thrust = min(thrust, 100)  # 上限100
    thrust_last = thrust
    log.debug("PID_Go 目标速度:{}\t实际速度: {}\tthrust: {}\tdist: {}".format(
        tar_speed, speed, thrust, dist))
    return int(dire), thrust
Esempio n. 23
0
 def process(self, balls):
     if self.previousBalls is None:
         self.previousBalls = balls
         return balls
     else:
         bestDistance = 100000000
         bestPermutation = None
         for permutation in itertools.permutations(balls):
             distance = 0
             for i in range(len(permutation)):
                 distance += getDistance(permutation[i][0],
                                         permutation[i][1],
                                         self.previousBalls[i][0],
                                         self.previousBalls[i][1])
             if distance < bestDistance:
                 bestPermutation = permutation
                 bestDistance = distance
         self.previousBalls = bestPermutation
         return np.array(self.previousBalls)
Esempio n. 24
0
 def tick(self, dtime):
     self.ent.AI_UP = False
     self.ent.AI_DOWN = False
     self.ent.AI_LEFT = False
     self.ent.AI_RIGHT = False
     self.ent.AI_FORWARD = False
     self.ent.AI_REVERSE = False
     if self.ent.goals:
         self.currentGoal = self.ent.goals[0].pos
     if self.finished == False:
         dist = self.range
         if self.currentGoal != None:
             #get distane from goal
             dist = utils.getDistance(self.ent.pos, self.currentGoal)
             self.setControls(self.currentGoal)
         #if distance is within range, complete goal and move onto the next one
         if dist < self.range:
             self.ent.score += 1 #increment score counter for ai to keep track of the winner and losers
             self.nextGoal()
Esempio n. 25
0
    def calc_mark(self, state):  #a ameliorer pour la gestion des ennemis
        if self.assignedGroup.eff == 0:
            print(
                "Warning : calc_mark tente d'evaluer les actions d'un groupe vide"
            )
            return 0
        if self.action_type == ActionType.attackHuman:
            distance = utils.getDistance(self.assignedGroup, self.target_group)
            groupe_max = Group(0, 0, 0, self.assignedGroup.species.inverse()
                               )  #on initialise un groupe max de base, a 0
            for group in state.groupes:
                if group.species == self.assignedGroup.species.inverse() \
                        and utils.getDistance(group,self.target_group) < distance \
                        and group.eff >= self.target_group.eff \
                        and group.eff>groupe_max.eff: #on cherche les groupes ennemis plus proches que nous de la cible, plus nombreux que la cible, et on garde le plus gros d'entre eux
                    groupe_max = group

            enemyWinner = utils.simulateBattle(
                groupe_max, self.target_group
            )  # on simule une bataille entre ce groupe_max (cad le groupe d'enemis plus proche que nous, ou, à défaut, un groupe fictif vide, qui perdra forcément la bataille)
            winnerFinal = utils.simulateBattle(
                self.assignedGroup, enemyWinner
            )  # et on simule une bataille entre nous et le gagnant de la première bataille
            #et ensuite on traite les differents cas

            if winnerFinal.species == self.assignedGroup.species:  #soit on gagne avec certitude la derniere bataille
                self.possibleEnemyGain = -groupe_max.eff
                self.possibleGain = (winnerFinal.eff) - self.assignedGroup.eff

            elif winnerFinal.species == Species.human:  # soit les humains remportent et nos deux groupes se sont faits bouffer (on a été cons)
                self.possibleEnemyGain = -groupe_max.eff
                self.possibleGain = -self.assignedGroup.eff

            else:  # soit les enemis gagnent et on perd
                self.possibleEnemyGain = (winnerFinal.eff) - groupe_max.eff
                self.possibleGain = -self.assignedGroup.eff

        elif self.action_type == ActionType.attackEnemy:
            distance = utils.getDistance(self.assignedGroup, self.target_group)
            groupe_max = Group(
                0, 0, 0,
                Species.human)  #on initialise un groupe max de base, a 0
            for group in state.groupes:
                if group.species == Species.human \
                        and utils.getDistance(group,self.target_group) < distance \
                        and group.eff <= self.target_group.eff \
                        and group.eff>groupe_max.eff: #on cherche les groupes d'humains plus proches que nous de la cible ennemie, moins nombreuse que la cible, et on garde le plus gros d'entre eux
                    groupe_max = group

            enemyWinner = utils.simulateBattle(
                self.target_group, groupe_max
            )  # on simule une bataille entre ce groupe_max (cad le groupe d'humains plus proche que nous, ou, à défaut, un groupe fictif vide, qui perdra forcément la bataille)
            winnerFinal = utils.simulateBattle(
                self.assignedGroup, enemyWinner
            )  # et on simule une bataille entre nous et le gagnant de la première bataille

            if winnerFinal.species == self.assignedGroup.species:
                self.possibleGain = (winnerFinal.eff) - self.assignedGroup.eff
                self.possibleEnemyGain = -self.target_group.eff
            else:
                self.possibleGain = -self.assignedGroup.eff
                self.possibleEnemyGain = (winnerFinal.eff -
                                          self.target_group.eff)

        elif self.action_type == ActionType.run:  #todo a implementer en cas de plateau vide à la fin si on est plus nombreux que les ennemis
            self.possibleGain = 0
        else:
            print("type d'action non reconnu par calc_mark", self.action_type)
        intuitive_mark = (self.possibleGain - self.possibleEnemyGain)
        #enfin, on divise les notes intuitives par la distance pour prendre en compte des incertitudes
        if intuitive_mark >= 0:
            self.mark = intuitive_mark / float(
                utils.getDistance(
                    self.assignedGroup,
                    self.target_group))  #todo diviser par distance au carre ?
        else:  #mais on garde les notes négatives telles quelles pour leur donner plus de poids negatif
            self.mark = intuitive_mark
Esempio n. 26
0
def test_cityDistance():
    london = [-0.118092, 51.509865]
    paris = [2.352222, 48.856614]

    assert (utils.getDistance(paris[0], paris[1], london[0], london[1]) == 340)
Esempio n. 27
0
def getNearestVehicles(latitude, longitude, route=None):
    vehicles = getVehiclesByRoute(route)
    vehicles.sort(key=lambda v: utils.getDistance(v.latitude, v.longitude, latitude, longitude))
    return vehicles
Esempio n. 28
0
 def __init__(self):
     self.previousPosition = None
     self.streak = 0
     self.streakPosition = None
     self.timeSinceStreak = 0
     self.maxDistance = getDistance(0, 0, 256, 256) * 0.1
Esempio n. 29
0
    thread.start_new_thread(serial_recv_thread, ())
    # 开启RTK线程
    thread.start_new_thread(ntrip.fun, ())
    # 等待定位成功
    while g.getValue('lat') == None or g.getValue('lat') == 0:
        time.sleep(1)
        pass
    logging.info('已定位')
    # 获取导航点
    getPoints('gps.csv')
    if len(sidePoints) > 1:
        logging.info('已加载导航点,共有%d个点' % len(sidePoints))
        index = 0
        pos = Point(g.getValue('lat'), g.getValue('lng'))
        # 判断刚开始时,是否需要原地转
        state = State.TURN if utils.getDistance(
            pos, sidePoints[0]) > 3 else State.GO
        while index < len(sidePoints):
            pos = Point(g.getValue('lat'), g.getValue('lng'))
            if state == State.TURN:
                thrust = 0
                dire = PID_Turn(pos, sidePoints[index], yaw, -gz)
                if dire == 0:
                    # 转弯完毕,进入直行阶段
                    state = State.GO
            elif state == State.GO:
                dire, thrust = PID_Go(pos, sidePoints[index], yaw, -gz)

            # 已到达
            dist = utils.getDistance(pos, sidePoints[index])
            if dist < 1:
                if index == 0:
Esempio n. 30
0
def enumerate_possible_actions(state, group, specie, number_my_groups, max_split_rate):
    groups_human = state.getMembers(Species.human)
    groups_enemy = state.getMembers(specie.inverse())
    actions_total = []
    len_group_me = group.eff
    actions_simple_per_group = []
    actions_split_per_group = []
    doublets = []
    groups_targets = []

    #on elague les groupes d'humains
    humanDistances = []
    for humangroup in groups_human:
        humanDistances.append(utils.getDistance(group, humangroup))
    groups_human.sort(key=dict(zip(groups_human, humanDistances)).get, reverse=False)
    groups_human=groups_human[:len_group_me+1]

    #de même pour les ennemis
    enemyDistances = []
    for enemy in groups_enemy:
        enemyDistances.append(utils.getDistance(group, enemy))
    groups_enemy.sort(key=dict(zip(groups_enemy, enemyDistances)).get, reverse=False)
    groups_enemy=groups_human[:len_group_me+1]

    # actions sans split
    for group_human in groups_human:
        action = Action(ActionType.attackHuman, group_human, group)
        action.calc_mark(state)
        actions_simple_per_group.append(action)
        groups_targets.append(group_human)

    for group_enemy in groups_enemy:
        action = Action(ActionType.attackEnemy, group_enemy, group)
        action.calc_mark(state)
        actions_simple_per_group.append(action)
        groups_targets.append(group_enemy)

    # actions avec splits
    if number_my_groups <= max_split_rate: #on évite de trop se splitter
        for i in range(1, int(len_group_me/2)+1):
            doublets.append([i, len_group_me-i])

        for doublet in doublets:
            group1 = Group(group.x, group.y, doublet[0], specie)
            group2 = Group(group.x, group.y, doublet[1], specie)
            for target_group_1 in groups_targets:
                action_type_1 = specie.determine_action_type(target_group_1.species)
                for target_group_2 in groups_targets:
                    action_type_2 = specie.determine_action_type(target_group_2.species)
                    # si les deux targets sont différentes :
                    if (target_group_1.x != target_group_2.x) or (target_group_1.y != target_group_2.y):
                        action1 = Action(action_type_1, target_group_1, group1)
                        action2 = Action(action_type_2, target_group_2, group2)
                        action1.calc_mark(state)
                        action2.calc_mark(state)
                        action1.parent_group = group
                        action2.parent_group = group
                        actions_split_per_group.append([action1, action2])
    actions_total.append(actions_simple_per_group)
    actions_total.append(actions_split_per_group)

    return actions_total
Esempio n. 31
0
def serial_recv_thread():
    ser = serial.Serial("/dev/ttyAMA0", 115200)
    gz = 0
    flag_ang_control = 0
    flag_finish = False
    flag_back = False
    while True:
        if True or g.getValue('mode') != 1 and g.getValue('mode') != 0:
            try:
                msg = ser.readline().strip()
                if msg.startswith('$') and msg.endswith('#'):
                    datas = msg.replace('$', '').replace('#', '').split(';')
                    if len(datas) >= 10:
                        yaw = float(datas[3])
                        gps_speed = float(datas[7])

                        if flag_finish:
                            angle_error = 279 - yaw
                            if angle_error > 180:
                                angle_error -= 360
                            elif angle_error <= -180:
                                angle_error += 360

                            if flag_back:
                                dire = angle_control_5(angle_error, -gz)
                                dire = 0
                                ser.write(utils.parityGenerate(
                                    "$E;-25,%d#" % dire))
                                dist = utils.getDistance(Point(lat_rev1, lng_rev1), Point(
                                    g.getValue('lat'), g.getValue('lng')))
                                print(dist, angle_error)
                                if dist < 2:
                                    time.sleep(1)
                                    ser.write(utils.parityGenerate("$E;0,0#"))
                                    break
                                continue

                            if abs(angle_error) < 10:
                                ser.write(utils.parityGenerate("$E;-25,0#"))
                                flag_back = True
                            dire = angle_control_4(angle_error, -gz)
                            print("角度差、方向油门:%d\t%d" % (angle_error, dire))
                            ser.write(utils.parityGenerate(
                                "$E;%d,%d#" % (0, dire)))
                            continue

                        (thrust, dire, flag_ang_control) = control_reverse_point(
                            g.getValue('lat'), g.getValue('lng'), yaw, gps_speed, -gz, lat_rev, lng_rev, flag_ang_control)
                        # print(g.getValue('lat'), g.getValue(
                        #     'lng'), g.getValue('mode'), yaw, gps_speed, thrust, dire)
                        ser.write(utils.parityGenerate(
                            "$E;%d,%d#" % (thrust, dire)))
                        if thrust == 0 and dire == 0:
                            flag_finish = True
                elif msg.startswith('&') and msg.endswith('#'):
                    datas = msg.replace('&', '').replace('#', '').split(';')
                    gz = float(datas[0])
            except KeyboardInterrupt:
                break
            except Exception:
                continue
    ser.close()
    print('Finish')
Esempio n. 32
0
with open(tmp_input, 'w') as f:
    f.write('Host1\tHost2\tDistance\n')
    for i in xrange(len(species)):
        for j in xrange(len(species)):
            if i != j:
                host1 = species[i]
                host2 = species[j]
                sum = float(0)
                elms_compared = 0
                for elm in utils_graph.unionLists([host2elmFreqs[host1],
                                                   host2elmFreqs[host2]]):
                    for h in (host1, host2):
                        if elm not in host2elmFreqs[h]:
                            host2elmFreqs[h][elm] = {}
                    if len(host2elmFreqs[host1][elm].keys()) != 0 and len(host2elmFreqs[host2][elm].keys()) != 0:
                        sum += utils.getDistance(host2elmFreqs[host1][elm],
                                                 host2elmFreqs[host2][elm])
                        elms_compared += 1
                f.write('%s\t%s\t%.10f\n'
                        % (short_names[host1], 
                           short_names[host2], 
                           float(sum)/float(elms_compared)))
           
out_file = 'plots/for_aydin_2/cos_dis_sum_host' + suffix + '.png'
tmp_r = 'tmp_r' + str(random.randint(0,100))
with open(tmp_r, 'w') as f:
    f.write('library(ggplot2)\n')
    f.write("d<-read.delim('"
            + tmp_input + "', header=T, sep='\\t')\n")
    f.write("png('" + out_file + "')\n")
    f.write("ggplot(d,aes(Host1,Host2)) + geom_tile(aes(fill=Distance),colour='white') + scale_fill_gradient(low='green',high='steelblue')\n")
    f.write('dev.off()\n')
Esempio n. 33
0
            (elm, fq) = line.strip().split('\t')
            freqs_single[elm] = float(fq)
    freqs[host] = freqs_single

tmp_input = 'tmp_i' + str(random.randint(0,100))
tmp_r = 'tmp_r' + str(random.randint(0,100))
out_file = 'plots/for_aydin_2/elm_count_dis_redo.png'
with open(tmp_input, 'w') as f:
    f.write('Host1\tHost2\tDistance\n')
    for i in xrange(len(species)):
        for j in xrange(len(species)):
            if i != j:
                host1 = species[i]
                host2 = species[j]
                f.write('%s\t%s\t%.10f\n'
                        % (short_names[host1], 
                           short_names[host2], 
                           utils.getDistance(freqs[host1], 
                                             freqs[host2])))
with open(tmp_r, 'w') as f:
        f.write('library(ggplot2)\n')
        f.write("d<-read.delim('"
                + tmp_input + "', header=T, sep='\\t')\n")
        f.write("png('" + out_file + "')\n")
        f.write("ggplot(d,aes(Host1,Host2)) + geom_tile(aes(fill=Distance),colour='white') + scale_fill_gradient(low='white',high='steelblue')\n")
        f.write('dev.off()\n')
os.system('R < ' + tmp_r + ' --no-save')
#os.system('rm ' + tmp_r + ' ' + tmp_input)

    
Esempio n. 34
0
def enumerate_possible_actions(state, group, specie, number_my_groups,
                               max_split_rate):
    groups_human = state.getMembers(Species.human)
    groups_enemy = state.getMembers(specie.inverse())
    actions_total = []
    len_group_me = group.eff
    actions_simple_per_group = []
    actions_split_per_group = []
    doublets = []
    groups_targets = []

    #on elague les groupes d'humains
    humanDistances = []
    for humangroup in groups_human:
        humanDistances.append(utils.getDistance(group, humangroup))
    groups_human.sort(key=dict(zip(groups_human, humanDistances)).get,
                      reverse=False)
    groups_human = groups_human[:len_group_me + 1]

    #de même pour les ennemis
    enemyDistances = []
    for enemy in groups_enemy:
        enemyDistances.append(utils.getDistance(group, enemy))
    groups_enemy.sort(key=dict(zip(groups_enemy, enemyDistances)).get,
                      reverse=False)
    groups_enemy = groups_human[:len_group_me + 1]

    # actions sans split
    for group_human in groups_human:
        action = Action(ActionType.attackHuman, group_human, group)
        action.calc_mark(state)
        actions_simple_per_group.append(action)
        groups_targets.append(group_human)

    for group_enemy in groups_enemy:
        action = Action(ActionType.attackEnemy, group_enemy, group)
        action.calc_mark(state)
        actions_simple_per_group.append(action)
        groups_targets.append(group_enemy)

    # actions avec splits
    if number_my_groups <= max_split_rate:  #on évite de trop se splitter
        for i in range(1, int(len_group_me / 2) + 1):
            doublets.append([i, len_group_me - i])

        for doublet in doublets:
            group1 = Group(group.x, group.y, doublet[0], specie)
            group2 = Group(group.x, group.y, doublet[1], specie)
            for target_group_1 in groups_targets:
                action_type_1 = specie.determine_action_type(
                    target_group_1.species)
                for target_group_2 in groups_targets:
                    action_type_2 = specie.determine_action_type(
                        target_group_2.species)
                    # si les deux targets sont différentes :
                    if (target_group_1.x != target_group_2.x) or (
                            target_group_1.y != target_group_2.y):
                        action1 = Action(action_type_1, target_group_1, group1)
                        action2 = Action(action_type_2, target_group_2, group2)
                        action1.calc_mark(state)
                        action2.calc_mark(state)
                        action1.parent_group = group
                        action2.parent_group = group
                        actions_split_per_group.append([action1, action2])
    actions_total.append(actions_simple_per_group)
    actions_total.append(actions_split_per_group)

    return actions_total
    def main(self,img):
        transform = transforms.Compose([transforms.ToTensor()])
        with torch.no_grad():
            height, width = img.shape[:2]
            img_det = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            det = self.mtcnn.detect_face(img_det)
            # '''
            # [{'box': (160, 48, 322, 270), 'cls': array([0.9666081], dtype=float32),
            #   'pts': {'leye': (214, 136), 'reye': (276, 121), 'nose': (257, 159), 'lmouse': (238, 208),
            #           'rmouse': (288, 197)}}]
            # '''
            for i in range(len(det)): #单张图片人脸数量
                box = det[i]['box']   #人脸框tuple
                #cls = result[i]['cls']  #置信度ndarry
                pts = det[i]['pts']   #五官坐标dict
                x1, y1, x2, y2 = box     #左上右下
                dis = y2 - y1
                #cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 25)) #天蓝色人脸框
                w = x2 - x1 + 1
                h = y2 - y1 + 1
                size_w = int(max([w, h])*0.9)
                size_h = int(max([w, h]) * 0.9)
                cx = x1 + w//2
                cy = y1 + h//2
                x1 = cx - size_w//2
                x2 = x1 + size_w
                y1 = cy - int(size_h * 0.4)
                y2 = y1 + size_h
                left = 0
                top = 0
                bottom = 0
                right = 0
                if x1 < 0:
                    left = -x1
                if y1 < 0:
                    top = -y1
                if x2 >= width:
                    right = x2 - width
                if y2 >= height:
                    bottom = y2 - height

                x1 = max(0, x1)
                y1 = max(0, y1)
                x2 = min(width, x2)
                y2 = min(height, y2)
                cropped = img[y1:y2, x1:x2]  #裁剪出的人脸
                # print(cropped.shape)
                # np_img = img[int(y1/1):y2+int(y1/1),int(x1/1):x2+int(x1/1)]
                # cv2.imshow(str(numa),np_img)
                cropped = cv2.copyMakeBorder(cropped, top, bottom, left, right, cv2.BORDER_CONSTANT, 0)
                input = cv2.resize(cropped, (112, 112))
                input = cv2.cvtColor(input, cv2.COLOR_BGR2RGB)
                input = transform(input).unsqueeze(0).cuda()
                pose, landmarks = self.pfldmodel(input)
                #poses = pose.cpu().detach().numpy()[0] * 180 / np.pi
                # 长度3 pitch是围绕X轴旋转,也叫做俯仰角。 yaw是围绕Y轴旋转,也叫偏航角。 roll是围绕Z轴旋转,也叫翻滚角
                pre_landmark = landmarks[0]
                pre_landmark = pre_landmark.cpu().detach().numpy().reshape(-1, 2) * [size_w, size_h]  # 长度98
                # cv2.rectangle(img,(x1, y1), (x2, y2),(255,0,0)) #蓝色正方形
                fatigue = []
                for num, (x, y) in enumerate(pre_landmark.astype(np.int32)):
                    #cv2.circle(img, (x1 - left + x, y1 - bottom + y), 1, (255, 255, 0), 1)
                    #if 59 < num < 76 or num in [96,97]: #眼眶坐标
                    #眼镜轮廓坐标
                    #             62                     70
                    #       60         64          68          72
                    #             66                     74

                    if num in [60, 62, 64, 66, 68, 70, 72, 74]:
                        cv2.circle(img, (x1 - left + x, y1 - bottom + y), 1, (255, 255, 0), 1)
                        fatigue.append((x, y))
                # print(fatigue)
                rightrow = getDistance(fatigue[0], fatigue[2])
                rightcol = getDistance(fatigue[1],fatigue[3])
                leftrow = getDistance(fatigue[4],fatigue[6])
                leftcol = getDistance(fatigue[5],fatigue[7])
                numerator = rightcol+leftcol
                denominator = rightrow+leftrow
                distance = numerator/denominator
                print('dis:'+str(distance))
                text ,color= 'eyes closed!' if distance < 0.17 else 'eyes opened',\
                             (0, 0, 255) if distance < 0.17 else (0, 255, 0)



                img = cv2.putText(img, text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, color, 2)
                # another way 计算
                # eye = rightcol + leftcol
                # if eye / dis < 0.03:
                # print('dis:' + str(distance))
                # print('eyes closed!')
                # else:
                #     print('ok')

                # plotPosecube(img, poses[0], poses[1], poses[2], tdx=pts['nose'][0], tdy=pts['nose'][1],
                #        size=(x2 - x1) // 2)
            cv2.imshow('example', img)
            cv2.waitKey(0)
Esempio n. 36
0
def getNearestStops(latitude, longitude, route=None):
    stops = getStopsByRoute(route)
    stops.sort(key=lambda s: utils.getDistance(s.latitude, s.longitude, latitude, longitude))
    return stops
Esempio n. 37
0
def serial_recv_thread():
    global gps_speed
    ser = serial.Serial("/dev/ttyAMA0", 115200)
    gz = 0
    flag_ang_control = 0
    flag_finish = False
    flag_back = False
    while True:
        if True or g.getValue('mode') != 1 and g.getValue('mode') != 0:
            try:
                msg = ser.readline().strip()
                if msg.startswith('$') and msg.endswith('#'):
                    datas = msg.replace('$', '').replace('#', '').split(';')
                    if len(datas) >= 10:
                        yaw = float(datas[3])
                        gps_speed = float(datas[7])
                        if flag_finish:  # 到达倒库点
                            angle_error = 279 - yaw
                            if angle_error > 180:
                                angle_error -= 360
                            elif angle_error <= -180:
                                angle_error += 360

                            if flag_back:  # 在倒库点修完角,开始后退
                                # 边后退边修角,修角PID采用PID_Go中的
                                PID_P = 0.5
                                if angle_error * (-gz) > 0:
                                    PID_D = -0.8
                                else:
                                    PID_D = 0.8
                                dire = PID_P * angle_error + (-gz) * PID_D
                                dire = saturate(dire, -100, 100)
                                #考虑是否使用PID_Go然后thrust加负号

                                ser.write(
                                    utils.parityGenerate("$E;-15,%d#" % dire))
                                dist = utils.getDistance(
                                    Point(lat_rev1, lng_rev1),
                                    Point(g.getValue('lat'),
                                          g.getValue('lng')))  # 离最终点距离
                                print(dist, angle_error)
                                if dist < 2:  # 离最终点距离小于2m,停止
                                    time.sleep(1)
                                    ser.write(utils.parityGenerate("$E;0,0#"))
                                    break
                                continue

                            if abs(angle_error) < 10:
                                ser.write(utils.parityGenerate("$E;-15,0#"))
                                flag_back = True
                            dire = PID_Turn(angle_error, yaw_now,
                                            -gz)  # 在倒库点修角
                            # dire = angle_control_4(angle_error, -gz)
                            print("角度差、方向油门:%d\t%d" % (angle_error, dire))
                            ser.write(
                                utils.parityGenerate("$E;%d,%d#" % (0, dire)))
                            continue

                        (thrust, dire,
                         flag_ang_control) = control_reverse_point(
                             g.getValue('lat'), g.getValue('lng'), yaw,
                             gps_speed, -gz, lat_rev, lng_rev,
                             flag_ang_control)
                        # print(g.getValue('lat'), g.getValue(
                        #     'lng'), g.getValue('mode'), yaw, gps_speed, thrust, dire)
                        ser.write(
                            utils.parityGenerate("$E;%d,%d#" % (thrust, dire)))
                        if thrust == 0 and dire == 0:
                            flag_finish = True
                elif msg.startswith('&') and msg.endswith('#'):
                    datas = msg.replace('&', '').replace('#', '').split(';')
                    gz = float(datas[0])
            except KeyboardInterrupt:
                break
            except Exception:
                continue
    ser.close()
    print('Finish')
Esempio n. 38
0
def getNearestVehicles(latitude, longitude, route=None):
    vehicles = getVehiclesByRoute(route)
    vehicles.sort(key=lambda v: utils.getDistance(v.latitude, v.longitude,
                                                  latitude, longitude))
    return vehicles
Esempio n. 39
0
    def AStar(self, agent_id, start_pos, end_pos, agent_pos):
        open_set = []
        close_set = []
        h = [{} for i in range(self.window + 2)]
        g = [{} for i in range(self.window + 2)]
        path = [{} for i in range(self.window + 2)]
        open_set.append([start_pos, 0])
        pos = start_pos
        g[0][encode(pos)] = 0
        h[0][encode(pos)] = utils.getDistance(start_pos, end_pos)
        path[0][encode(pos)] = [[-1, -1], -1, -1]
        schedule = []
        while len(open_set) > 0:
            min_f = -1
            idx = -1
            for i in range(len(open_set)):
                [pos, t] = open_set[i]
                f = g[t][encode(pos)] + h[t][encode(pos)]
                if min_f == -1 or f < min_f:
                    min_f = f
                    idx = i
            [pos, t] = open_set[idx]
            open_set.pop(idx)
            close_set.append([pos, t])

            #dirs = utils.dirs + [[0, 0]]
            dirs = utils.dirs
            for i in range(len(dirs)):
                a = dirs[i]
                new_pos = [pos[0] + a[0], pos[1] + a[1]]
                #print new_pos
                if not self.isValidPath(agent_id, new_pos, t + 1, agent_pos,
                                        end_pos):
                    continue
                if [new_pos, t + 1] in close_set:
                    continue
                new_g = g[t][encode(pos)] + 1
                if [new_pos, t + 1] not in open_set:
                    open_set.append([new_pos, t + 1])
                    g[t + 1][encode(new_pos)] = new_g
                    h[t + 1][encode(new_pos)] = utils.getDistance(
                        new_pos, end_pos)
                    path[t + 1][encode(new_pos)] = [pos, t, a]
                elif new_g < g[t + 1][encode(new_pos)]:
                    g[t + 1][encode(new_pos)] = new_g
                    path[t + 1][encode(new_pos)] = [pos, t, a]

            if pos == end_pos or g[t][encode(pos)] == self.window or len(
                    open_set) == 0:
                while (path[t][encode(pos)] != [[-1, -1], -1, -1]):
                    [pos, t, a] = path[t][encode(pos)]
                    schedule.insert(0, [pos, a])
                break

        if len(schedule) == 0:
            #print 'fail to schedule, stay'
            #print path
            schedule.append([start_pos, [0, 0]])
        [pos, a] = schedule[-1]
        new_pos = [pos[0] + a[0], pos[1] + a[1]]
        schedule.append([new_pos, None])
        #print 'self.AStar'
        #print ['start_pos', start_pos, 'end_pos', end_pos]
        #print ['schedule', schedule]
        #print 'End self.AStar'
        return schedule
Esempio n. 40
0
    def calc_mark(self, state): #a ameliorer pour la gestion des ennemis
        if self.assignedGroup.eff==0:
            print("Warning : calc_mark tente d'evaluer les actions d'un groupe vide")
            return 0
        if self.action_type == ActionType.attackHuman:
            distance = utils.getDistance(self.assignedGroup,self.target_group)
            groupe_max = Group(0,0,0,self.assignedGroup.species.inverse()) #on initialise un groupe max de base, a 0
            for group in state.groupes:
                if group.species == self.assignedGroup.species.inverse() \
                        and utils.getDistance(group,self.target_group) < distance \
                        and group.eff >= self.target_group.eff \
                        and group.eff>groupe_max.eff: #on cherche les groupes ennemis plus proches que nous de la cible, plus nombreux que la cible, et on garde le plus gros d'entre eux
                    groupe_max=group

            enemyWinner = utils.simulateBattle(groupe_max,self.target_group) # on simule une bataille entre ce groupe_max (cad le groupe d'enemis plus proche que nous, ou, à défaut, un groupe fictif vide, qui perdra forcément la bataille)
            winnerFinal = utils.simulateBattle(self.assignedGroup,enemyWinner) # et on simule une bataille entre nous et le gagnant de la première bataille
            #et ensuite on traite les differents cas

            if winnerFinal.species==self.assignedGroup.species: #soit on gagne avec certitude la derniere bataille
                self.possibleEnemyGain = -groupe_max.eff
                self.possibleGain = (winnerFinal.eff)-self.assignedGroup.eff

            elif winnerFinal.species == Species.human: # soit les humains remportent et nos deux groupes se sont faits bouffer (on a été cons)
                self.possibleEnemyGain = -groupe_max.eff
                self.possibleGain = -self.assignedGroup.eff

            else:                                       # soit les enemis gagnent et on perd
                self.possibleEnemyGain = (winnerFinal.eff)-groupe_max.eff
                self.possibleGain = -self.assignedGroup.eff


        elif self.action_type == ActionType.attackEnemy:
            distance = utils.getDistance(self.assignedGroup,self.target_group)
            groupe_max = Group(0,0,0,Species.human) #on initialise un groupe max de base, a 0
            for group in state.groupes:
                if group.species == Species.human \
                        and utils.getDistance(group,self.target_group) < distance \
                        and group.eff <= self.target_group.eff \
                        and group.eff>groupe_max.eff: #on cherche les groupes d'humains plus proches que nous de la cible ennemie, moins nombreuse que la cible, et on garde le plus gros d'entre eux
                    groupe_max=group

            enemyWinner = utils.simulateBattle(self.target_group,groupe_max) # on simule une bataille entre ce groupe_max (cad le groupe d'humains plus proche que nous, ou, à défaut, un groupe fictif vide, qui perdra forcément la bataille)
            winnerFinal = utils.simulateBattle(self.assignedGroup,enemyWinner) # et on simule une bataille entre nous et le gagnant de la première bataille

            if winnerFinal.species==self.assignedGroup.species:
                self.possibleGain = (winnerFinal.eff)-self.assignedGroup.eff
                self.possibleEnemyGain = -self.target_group.eff
            else :
                self.possibleGain = -self.assignedGroup.eff
                self.possibleEnemyGain = (winnerFinal.eff-self.target_group.eff)

        elif self.action_type == ActionType.run:  #todo a implementer en cas de plateau vide à la fin si on est plus nombreux que les ennemis
            self.possibleGain = 0
        else :
            print("type d'action non reconnu par calc_mark", self.action_type)
        intuitive_mark = (self.possibleGain-self.possibleEnemyGain)
        #enfin, on divise les notes intuitives par la distance pour prendre en compte des incertitudes
        if intuitive_mark >= 0:
            self.mark = intuitive_mark/float(utils.getDistance(self.assignedGroup,self.target_group)) #todo diviser par distance au carre ?
        else : #mais on garde les notes négatives telles quelles pour leur donner plus de poids negatif
            self.mark = intuitive_mark
Esempio n. 41
0
                            ('H_sapiens', 'Gallus_gallus'),
                            ('H_sapiens', 'Taeniopygia_guttata'),
                            ('H_sapiens', 'D_rerio')
                            ):#itertools.combinations(hosts.keys(),2):
            use_dict_1 = {}
            use_dict_2 = {}
            if elm in host2elmFreqs[host1]:
                use_dict_1 = host2elmFreqs[host1][elm]
            if elm in host2elmFreqs[host2]:
                use_dict_2 = host2elmFreqs[host2][elm]
            if len(use_dict_1.keys()) == 0 and len(use_dict_2.keys()) == 0:
                pass
            #    f.write('%s\t%s\t%.10f\n'
            #            % (str(10), elm, float(0)))
            else:
                dis = utils.getDistance(use_dict_2, 
                                        use_dict_1)
                f.write('%s\t%s\t%.10f\n'
                        % (str(counter), elm, dis))
            counter += 1

out_file = 'plots/for_aydin_2/cos_dis_host' + suffix + '.png'
tmp_r = 'tmp_r' + str(random.randint(0,100))
with open(tmp_r, 'w') as f:
    f.write('library(ggplot2)\n')
    f.write("d<-read.delim('"
            + tmp_input + "', header=T, sep='\\t')\n")
    f.write("png('" + out_file + "')\n")
    f.write("ggplot(d,aes(Host_Host,ELM)) + opts(axis.text.x = theme_blank()) + opts(axis.text.y = theme_blank()) + geom_tile(aes(fill=Distance),colour='white') + scale_fill_gradient(low='green',high='steelblue')\n")
    f.write('dev.off()\n')
os.system('R < ' + tmp_r + ' --no-save')
Esempio n. 42
0
def getNearestStops(latitude, longitude, route=None):
    stops = getStopsByRoute(route)
    stops.sort(key=lambda s: utils.getDistance(s.latitude, s.longitude,
                                               latitude, longitude))
    return stops