Python math.inf() Examples

The following are code examples for showing how to use math.inf(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: s2g   Author: caesar0301   File: bonus.py    MIT License 6 votes vote down vote up
def point_projects_to_line(point, line):
    """Get the nearest point index on line
    """
    p = Point(point)

    # compute
    min_distance = math.inf
    closer_point = 0

    for i, vertex_coords in enumerate(line.coords[1:]):
        vertex = Point(vertex_coords)

        distance = p.distance(vertex)
        if distance < min_distance:
            min_distance = distance
            # in this convention, first point is number 1
            closer_point = i + 1

    if closer_point != 0:
        return closer_point
    else:
        # exiting here should not happen
        raise ValueError(
            "Error: cannot get closer vertex in {} with respect to {}"\
            .format(line, point)) 
Example 2
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 6 votes vote down vote up
def boostHungry(agent):
    closestBoost = agent.me
    bestDistance = math.inf
    bestAngle = 0

    for boost in agent.boosts:
        if boost.spawned:
            distance = distance2D(boost.location, agent.me)
            localCoords = toLocal(closestBoost.location, agent.me)
            angle = abs(math.degrees(math.atan2(localCoords[1], localCoords[0])))
            distance +=  angle*5
            distance += distance2D(agent.me.location,agent.ball.location)
            if boost.bigBoost:
                distance *= .5
            if distance < bestDistance:
                bestDistance = distance
                closestBoost = boost
                bestAngle = angle

    agent.renderCalls.append(renderCall(agent.renderer.draw_line_3d, agent.me.location.data, closestBoost.location.data,
                                        agent.renderer.yellow))
    return efficientMover(agent, closestBoost.location, agent.maxSpd,boostHunt=False) 
Example 3
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 6 votes vote down vote up
def boostSwipe(agent):
    enemyBackBoostLocations = [Vector([3072,-sign(agent.team)*4096,73]),Vector([-3072,-sign(agent.team)*4096,73])]

    backBoosts = []
    minDist = math.inf
    bestBoost = None
    for b in agent.boosts:
        if b.bigBoost:
            if b.spawned:
                for eb in enemyBackBoostLocations:
                    if distance2D(eb,b.location) < 300:
                        backBoosts.append(eb)
                        dist = distance2D(eb,agent.me.location)
                        if dist < minDist:
                            bestBoost = eb
                            minDist = dist
                        #return b.location

    return bestBoost,minDist 
Example 4
Project: COSC367-Artificial_Intelligence   Author: santochaoya   File: AStarSearch.py    GNU General Public License v3.0 6 votes vote down vote up
def getMap(self, map_str):
        """convert a map string to a form(row, column)"""
        
        #convert map string to a list with only useful information:
        #divide map string into a list with row of graph
        filter_map = (map_str.strip()).split('\n')
        
        #divide each string in row's element as column of graph
        for element in filter_map:
            self.map_graph.append(list(element.strip()))
        
        for i in range(len(self.map_graph)):
            for j in range(len(self.map_graph[i])):
                r, c = i, j
                if self.map_graph[r][c] == 'S':
                    self.starting_list.append((r, c, math.inf))
                elif self.map_graph[r][c].isdigit():
                    self.starting_list.append((r, c, int(self.map_graph[r][c])))
                elif self.map_graph[r][c] == 'G':
                    self.goal_nodes.append((r, c))
                
        #print("starting nodes : {}\ngoal node : {}\n".
              #format(self.starting_list, self.goal_nodes)) 
Example 5
Project: COSC367-Artificial_Intelligence   Author: santochaoya   File: print_map.py    GNU General Public License v3.0 6 votes vote down vote up
def getMap(self, map_str):
        """convert a map string to a form(row, column)"""
        
        #convert map string to a list with only useful information:
        #divide map string into a list with row of graph
        filter_map = (map_str.strip()).split('\n')
        
        #divide each string in row's element as column of graph
        for element in filter_map:
            self.map_graph.append(list(element.strip()))
        
        for i in range(len(self.map_graph)):
            for j in range(len(self.map_graph[i])):
                r, c = i, j
                if self.map_graph[r][c] == 'S':
                    self.starting_list.append((r, c, math.inf))
                elif self.map_graph[r][c].isdigit():
                    self.starting_list.append((r, c, int(self.map_graph[r][c])))
                elif self.map_graph[r][c] == 'G':
                    self.goal_nodes.append((r, c))
                
        #print("starting nodes : {}\ngoal node : {}\n".
              #format(self.starting_list, self.goal_nodes)) 
Example 6
Project: COSC367-Artificial_Intelligence   Author: santochaoya   File: RoutingGraph.py    GNU General Public License v3.0 6 votes vote down vote up
def getMap(self, map_str):
        """convert a map string to a form(row, column)"""
        
        #convert map string to a list with only useful information:
        #divide map string into a list with row of graph
        filter_map = (map_str.strip()).split('\n')
        
        #divide each string in row's element as column of graph
        for element in filter_map:
            self.map_graph.append(list(element.strip()))
        
        for i in range(len(self.map_graph)):
            for j in range(len(self.map_graph[i])):
                r, c = i, j
                if self.map_graph[r][c] == 'S':
                    self.starting_list.append((r, c, math.inf))
                elif self.map_graph[r][c].isdigit():
                    self.starting_list.append((r, c, int(self.map_graph[r][c])))
                elif self.map_graph[r][c] == 'G':
                    self.goal_nodes.append((r, c)) 
Example 7
Project: StatNLP-PyTorch   Author: allanj   File: FeatureArray.py    GNU General Public License v3.0 6 votes vote down vote up
def get_score(self, param, version = None):
        if (self == FeatureArray.NEGATIVE_INFINITY):
            return self._total_score

        if (not self._is_local) != param.is_global_mode():
            eprint(self._next)
            raise Exception('This FeatureArray is local? ', self._is_local, '; The param is ', param.is_global_mode())

        # print('self._total_score:', self._total_score, '\t', type(self._total_score))
        # if self._total_score == -math.inf:
        #     return self._total_score

        self._total_score = 0.0
        #if self._fb._version != version:
        self._fb._curr_score =   sum(self.fw) #self.compute_score(param, self.get_current()) #
        self._fb._version = version

        self._total_score += self._fb._curr_score

        if self._next != None:
            self._total_score += self._next.get_score(param, version)

        return self._total_score 
Example 8
Project: Lyra   Author: caterinaurban   File: runner.py    Mozilla Public License 2.0 6 votes vote down vote up
def _actual_result(self, result, line):
        actual = None
        distance = inf
        if line == -inf:    # precondition
            actual = result.get_node_result(self.cfg.in_node)[0]
            return actual
        elif line == inf:   # postcondition
            actual = result.get_node_result(self.cfg.out_node)[0]
            return actual
        elif line < 0:
            for edge in self.cfg.edges.values():
                if isinstance(edge, Conditional) and edge.kind == Edge.Kind.LOOP_IN:
                    current = edge.condition.pp.line + line
                    if current < distance:
                        states = result.get_node_result(edge.source)
                        actual = states[0]
                        distance = current
        for node in self.cfg.nodes.values():
            states = result.get_node_result(node)
            for i, stmt in enumerate(node.stmts):
                current = stmt.pp.line - line
                if abs(current) < distance:
                    actual = states[i + 1] if current < 0 else states[i]
                    distance = abs(current)
        return actual 
Example 9
Project: Lyra   Author: caterinaurban   File: interval_domain.py    Mozilla Public License 2.0 6 votes vote down vote up
def __repr__(self):
        def var(dim):
            return self.environment.environment.contents.var_of_dim[dim].decode('utf-8')
        def itv(dim):
            bound = self.bound_variable(PyVar(var(dim)))
            interval = bound.interval.contents
            inf = '{}'.format(interval.inf.contents)
            lower = inf if inf != '-1/0' else '-inf'
            sup = '{}'.format(interval.sup.contents)
            upper = sup if sup != '1/0' else 'inf'
            return '[{}, {}]'.format(lower, upper)
        if self.is_bottom():
            return "⊥"
        env = self.environment.environment.contents
        result = ', '.join('{}: {}'.format(var(i), itv(i)) for i in range(env.intdim))
        result += ', '.join(
            '{} -> {}'.format(var(env.intdim + i), itv(env.intdim + i)) for i in range(env.realdim)
        )
        return result.replace('.0', '') 
Example 10
Project: Gemini   Author: anfederico   File: exchange.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, no, entry_price, shares, exit_price=math.inf, stop_loss=0):
        """Open the position.

        :param no: A unique position id number
        :type no: float
        :param entry_price: Entry price at which shares are longed
        :type entry_price: float
        :param shares: Number of shares to long
        :type shares: float
        :param exit_price: Price at which to take profit
        :type exit_price: float
        :param stop_loss: Price at which to cut losses
        :type stop_loss: float

        :return: A long position
        :rtype: long_position
        """

        if exit_price is False: exit_price = math.inf
        if stop_loss is False: stop_loss = 0
        super().__init__(no, entry_price, shares, exit_price, stop_loss)
        self.type = 'long' 
Example 11
Project: Gemini   Author: anfederico   File: exchange.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, no, entry_price, shares, exit_price=0, stop_loss=math.inf):
        """Open the position.

        :param no: A unique position id number
        :type no: int
        :param entry_price: Entry price at which shares are shorted
        :type entry_price: float
        :param shares: Number of shares to short
        :type shares: float
        :param exit_price: Price at which to take profit
        :type exit_price: float
        :param stop_loss: Price at which to cut losses
        :type stop_loss: float

        :return: A short position
        :rtype: short_position
        """       
        if exit_price is False: exit_price = 0
        if stop_loss is False: stop_loss = math.inf
        super().__init__(no, entry_price, shares, exit_price, stop_loss)
        self.type = 'short' 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 6 votes vote down vote up
def test_infinity_and_nan_constants(self):
        self.assertEqual(cmath.inf.real, math.inf)
        self.assertEqual(cmath.inf.imag, 0.0)
        self.assertEqual(cmath.infj.real, 0.0)
        self.assertEqual(cmath.infj.imag, math.inf)

        self.assertTrue(math.isnan(cmath.nan.real))
        self.assertEqual(cmath.nan.imag, 0.0)
        self.assertEqual(cmath.nanj.real, 0.0)
        self.assertTrue(math.isnan(cmath.nanj.imag))

        # Check consistency with reprs.
        self.assertEqual(repr(cmath.inf), "inf")
        self.assertEqual(repr(cmath.infj), "infj")
        self.assertEqual(repr(cmath.nan), "nan")
        self.assertEqual(repr(cmath.nanj), "nanj") 
Example 13
Project: Autoenv   Author: intelligent-control-lab   File: collision_detection.py    MIT License 6 votes vote down vote up
def ensure_pts_sorted_by_min_polar_angle(poly: ConvexPolygon):
    npts = poly.npts
    assert npts >= 3
    assert get_signed_area(poly.pts) > 0 # must be counter-clockwise

    # ensure that edges are sorted by minimum polar angle in [0,2π]

    angle_start = math.inf
    index_start = -1

    for i in range(npts):
        seg = get_edge(poly.pts, i, npts)
        theta = math.atan2(seg.B.y - seg.A.y, seg.B.x - seg.A.x)

        if theta < 0:
            theta += 2*math.pi
        if theta < angle_start:
            angle_start = theta
            index_start = i
    if index_start != 0:
        poly.pts = cyclic_shift_left(poly.pts, index_start, npts)
    return poly 
Example 14
Project: Autoenv   Author: intelligent-control-lab   File: roadway.py    MIT License 6 votes vote down vote up
def proj_2(posG: VecSE2.VecSE2, roadway: Roadway):

    best_dist2 = math.inf
    best_proj = RoadProjection(CurvePt.CurveProjection(CurvePt.CurveIndex(-1, -1), None, None), NULL_LANETAG)

    for seg in roadway.segments:
        for lane in seg.lanes:
            roadproj = proj_1(posG, lane, roadway, move_along_curves=False)  # return RoadProjection
            targetlane = roadway.get_by_tag(roadproj.tag)  # return Lane
            footpoint = targetlane.get_by_ind_roadway(roadproj.curveproj.ind, roadway)
            vec = posG - footpoint.pos
            dist2 = VecE2.normsquared(VecE2.VecE2(vec.x, vec.y))
            # print(best_dist2, dist2, roadproj.curveproj.ind.i)
            if dist2 < best_dist2:
                best_dist2 = dist2
                best_proj = roadproj
    return best_proj 
Example 15
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 6 votes vote down vote up
def boostHungry(agent):
    closestBoost = agent.me
    bestDistance = math.inf
    bestAngle = 0

    for boost in agent.boosts:
        if boost.spawned:
            distance = distance2D(boost.location, agent.me)
            localCoords = toLocal(closestBoost.location, agent.me)
            angle = abs(math.degrees(math.atan2(localCoords[1], localCoords[0])))
            distance +=  angle*5
            distance += distance2D(agent.me.location,agent.ball.location)
            if boost.bigBoost:
                distance *= .5
            if distance < bestDistance:
                bestDistance = distance
                closestBoost = boost
                bestAngle = angle

    agent.renderCalls.append(renderCall(agent.renderer.draw_line_3d, agent.me.location.data, closestBoost.location.data,
                                        agent.renderer.yellow))
    return efficientMover(agent, closestBoost.location, agent.maxSpd,boostHunt=False) 
Example 16
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 6 votes vote down vote up
def flipDecider(agent,targetVec,enemyInfluenced=False):
    if not enemyInfluenced:
        targetVec = agent.ball.location
        if distance2D(agent.me.location, agent.ball.location) <= 200:
            if targetVec[2] <= 160:
                agent.setJumping(0)

    else:
        if distance2D(agent.me.location,targetVec) <= 200:
            if targetVec[2] <= 160:
                if len(agent.enemies) > 0:
                    closest = agent.enemies[0]
                    cDist = math.inf
                    for e in agent.enemies:
                        x = findDistance(e.location,agent.ball.location)
                        if x < cDist:
                            cDist = x
                            closest = e
                    if cDist < 350:
                        agent.setJumping(0) 
Example 17
Project: linnea   Author: HPAC   File: matrix_chain_solver.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, expr, explicit_inversion=False):
        self.expr = expr
        self.n = len(self.expr.operands) # TODO remove?
        self.explicit_inversion = explicit_inversion

        n = len(self.expr.operands)

        self.costs = [[math.inf for _ in range(n)] for _ in range(n)]
        self.sol = [[None for _ in range(n)] for _ in range(n)]
        self.tmps = [[None for _ in range(n)] for _ in range(n)]
        self.kernels = [[None for _ in range(n)] for _ in range(n)]

        for i in range(n):
            self.costs[i][i] = 0
            self.tmps[i][i] = self.expr.operands[i]

        self._solve()
        self.matched_kernels = list(itertools.chain.from_iterable(self._constuct_solution(0, n-1)))
        self.tmp = self.tmps[0][n-1] 
Example 18
Project: pose_recovery_evaluation   Author: rbregier   File: evaluation_tools.py    GNU General Public License v3.0 6 votes vote down vote up
def compute_precision_recall_curve(max_distance, max_occlusion_rate, min_occlusion_rate, max_nb_results, scene_data):
    """ returns a tuple of precision/sensitivity lists, for every score, for the given scene """    
    pre = []
    sen = []
    
    scores = [math.inf] + list(get_scores({"toto" : scene_data}))
    scores = sorted(scores, reverse = True)
    for min_score in scores:
        c = classify_based_on_thresholds(scene_data, min_score, max_distance, max_occlusion_rate, min_occlusion_rate, max_nb_results)
        p = compute_precision(c)
        if max_nb_results <= 0:
            s = compute_recall(c)
        else:
            s = compute_recall_with_a_limited_number_of_retrieval(c, max_nb_results)
        pre.append(p)
        sen.append(s)
    return (pre, sen, scores) 
Example 19
Project: resolwe   Author: genialis   File: listener.py    Apache License 2.0 6 votes vote down vote up
def check_critical_load(self):
        """Check for critical load and log an error if necessary."""
        if self.load_avg.intervals['1m'].value > 1:
            if self.last_load_level == 1 and time.time() - self.last_load_log < 30:
                return
            self.last_load_log = time.time()
            self.last_load_level = 1
            logger.error(
                "Listener load limit exceeded, the system can't handle this!",
                extra=self._make_stats()
            )

        elif self.load_avg.intervals['1m'].value > 0.8:
            if self.last_load_level == 0.8 and time.time() - self.last_load_log < 30:
                return
            self.last_load_log = time.time()
            self.last_load_level = 0.8
            logger.warning(
                "Listener load approaching critical!",
                extra=self._make_stats()
            )

        else:
            self.last_load_log = -math.inf
            self.last_load_level = 0 
Example 20
Project: MusicDownloader   Author: wwwpf   File: download_model.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, song=None, row=0):
        super().__init__()

        self.song = song
        self.file_size = math.inf   # 文件大小,单位: KB
        self.progress = 0.0         # 下载进度
        self.speed = 0.0            # 下载速度
        self.current_size = 0       # 已下载大小,单位: KB
        self.row = row 
Example 21
Project: MusicDownloader   Author: wwwpf   File: download_model.py    GNU General Public License v3.0 5 votes vote down vote up
def get_file_size(self):
        if self.file_size is math.inf:
            return "未知"
        return get_human_read(self.file_size) 
Example 22
Project: MusicDownloader   Author: wwwpf   File: download_model.py    GNU General Public License v3.0 5 votes vote down vote up
def get_remain_time(self):
        if self.speed < 1e-6 or self.file_size is math.inf:
            return "--:--"
        if not self.finished():
            t = (self.file_size - self.current_size) / self.speed
            return time.strftime("%M:%S", time.gmtime(t))
        return "已完成" 
Example 23
Project: RLBotPack   Author: RLBot   File: util.py    MIT License 5 votes vote down vote up
def get_closest_small_pad(agent):
    pads = agent.info.small_boost_pads
    pad = None
    distance = math.inf
    for i in range(len(pads)):
        if distance_2d(agent.info.my_car.pos, pads[i].pos) < distance:
            distance = distance_2d(agent.info.my_car.pos, pads[i].pos)
            pad = pads[i]
    return pad 
Example 24
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 5 votes vote down vote up
def demoMagic(agent):
    currentSpd = agent.getCurrentSpd()
    if currentSpd <1900:
        if agent.me.boostLevel <=0:
            agent.activeState.active = False
    e_goal = Vector([0, 5100 * -sign(agent.team), 200])
    best = None
    distance = math.inf
    for e in agent.enemies:
        if e.location[2] <= 120:
            _distance = distance2D(e_goal,e.location)
            if _distance < distance:
                distance = _distance
                best = e

    if best != None:
        if currentSpd <=100:
            currentSpd = 100

        currentTimeToTarget = distance / currentSpd
        lead = clamp(agent.deltaTime*60,agent.deltaTime*5,agent.deltaTime*distance/500)
        difference = best.velocity.scale(lead)
        targetPos = e.location + difference
        agent.renderCalls.append(
            renderCall(agent.renderer.draw_line_3d, agent.me.location.data, targetPos.data, agent.renderer.purple))

        if currentTimeToTarget <= agent.deltaTime*30:
            targetLocal = toLocal(targetPos,agent.me)
            angle = math.degrees(math.atan2(targetLocal[1],targetLocal[0]))
            if abs(angle) <= 40:
                agent.setJumping(0)

        return testMover(agent,targetPos,2300)



    else:
        return None 
Example 25
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 5 votes vote down vote up
def saferBoostGrabber(agent):
    minDistance = distance2D(Vector([0, 5100 * sign(agent.team), 200]),agent.ball.location)
    closestBoost = physicsObject()
    closestBoost.location = Vector([0, 5100 * sign(agent.team), 200])
    bestDistance = math.inf
    bestAngle = 0

    for boost in agent.boosts:
        if boost.spawned:
            goalDistance = distance2D(boost.location, Vector([0, 5100 * sign(agent.team), 200]))
            if goalDistance < minDistance*.7:
                distance = distance2D(agent.me.location,boost.location)
                localCoords = toLocal(boost.location, agent.me)
                angle = abs(math.degrees(math.atan2(localCoords[1], localCoords[0])))
                if boost.bigBoost:
                    distance = distance*.5
                distance += angle * 5
                if distance < bestDistance:
                    bestDistance = distance
                    closestBoost = boost
                    bestAngle = angle

    agent.renderCalls.append(renderCall(agent.renderer.draw_line_3d, agent.me.location.data, closestBoost.location.data,
                                        agent.renderer.yellow))

    return efficientMover(agent, closestBoost.location, agent.maxSpd,boostHunt=False) 
Example 26
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 5 votes vote down vote up
def findEnemyClosestToLocation(agent,location):
    if len(agent.enemies) > 0:
        closest = agent.enemies[0]
        cDist = math.inf
        for e in agent.enemies:
            x = findDistance(e.location, location)
            if x < cDist:
                cDist = x
                closest = e
        return closest,cDist
    else:
        return None,None 
Example 27
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 5 votes vote down vote up
def inaccurateArrivalEstimator(agent,destination):
    distance = clamp(math.inf,0.00001,distance2D(agent.me.location,destination)-(91+agent.carLength/2))
    moreAccurateEstimation = calcTimeWithAcceleration(agent,distance)

    #print(f"estimate for reaching distance {distance}: {moreAccurateEstimation}")
    return moreAccurateEstimation 
Example 28
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 5 votes vote down vote up
def findSuitableBallPosition2(agent, heightMax, speed, origin):
    applicableStructs = []
    spd = clamp(2300,300,speed)
    ballInGoal = None
    goalTimer = math.inf
    if agent.ballPred is not None:
        for i in range(0, agent.ballPred.num_slices):
            if isBallHittable(agent.ballPred.slices[i],agent,heightMax):
                applicableStructs.append(agent.ballPred.slices[i])
                if agent.team == 0:
                    if agent.ballPred.slices[i].physics.location.y <= -5050:
                        ballInGoal = agent.ballPred.slices[i]
                        goalTimer = agent.ballPred.slices[i].game_seconds - agent.gameInfo.seconds_elapsed
                        break
                else:
                    if agent.ballPred.slices[i].physics.location.y >= 5050:
                        ballInGoal = agent.ballPred.slices[i]
                        goalTimer = agent.ballPred.slices[i].game_seconds - agent.gameInfo.seconds_elapsed
                        break
                applicableStructs.append(agent.ballPred.slices[i])

    for pred in applicableStructs:
        distance = distance2D(Vector([pred.physics.location.x,pred.physics.location.y]),origin)
        adjustSpd = clamp(2300,1000,speed+distance*.7)
        if distance/adjustSpd < (pred.game_seconds - agent.gameInfo.seconds_elapsed):
            if goalTimer < pred.game_seconds - agent.gameInfo.seconds_elapsed:
                agent.goalPred = ballInGoal
            return pred

    if goalTimer < math.inf:
        agent.goalPred = ballInGoal
    return agent.ballPred.slices[-1] 
Example 29
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 5 votes vote down vote up
def CB_Reworked(agent,targetVec):
    dist = clamp(25000, 1, distance2D(agent.me.location, targetVec))
    ballDist = clamp(25000, 1, distance2D(agent.me.location, agent.ball.location))
    destinationEstimate = inaccurateArrivalEstimator(agent,targetVec)
    locTarget = toLocal(targetVec, agent.me)
    targetAngle = correctAngle(math.degrees(math.atan2(locTarget[1], locTarget[0])))

    bestBoost = None
    bestAngle = 0
    angleDisparity = 1000
    bestDist = math.inf
    bestEstimate = math.inf
    goodBoosts = []
    for b in agent.boosts:
        _dist = distance2D(b.location, agent.me.location)
        if _dist < dist*.6:
            localCoords = toLocal(b.location, agent.me)
            angle = correctAngle(math.degrees(math.atan2(localCoords[1], localCoords[0])))
            _angleDisparity = targetAngle - angle

            if _angleDisparity > targetAngle-30 and _angleDisparity < targetAngle+30:
                goodBoosts.append(b)

    for b in goodBoosts:
        pathEstimate = inaccurateArrivalEstimator(agent,b.location) + inaccurateArrivalEstimatorRemote(agent,b.location,targetVec)
        if agent.me.boostLevel < 50:
            if b.bigBoost:
                pathEstimate*=.8
        if pathEstimate < bestEstimate:
            bestBoost = b
            bestEstimate = pathEstimate

    if bestEstimate < destinationEstimate*1.15 or bestEstimate < agent.ballDelay:
        return bestBoost.location
    else:
        return None 
Example 30
Project: matchpy   Author: HPAC   File: many_to_one.py    MIT License 5 votes vote down vote up
def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]:
        """Replace all occurrences of the patterns according to the replacement rules.

        Args:
            expression:
                The expression to which the replacement rules are applied.
            max_count:
                If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
                are applied until there is no more match. If the set of replacement rules is not confluent,
                the replacement might not terminate without a *max_count* set.

        Returns:
            The resulting expression after the application of the replacement rules. This can also be a sequence of
            expressions, if the root expression is replaced with a sequence of expressions by a rule.
        """
        replaced = True
        replace_count = 0
        while replaced and replace_count < max_count:
            replaced = False
            for subexpr, pos in preorder_iter_with_position(expression):
                try:
                    replacement, subst = next(iter(self.matcher.match(subexpr)))
                    result = replacement(**subst)
                    expression = functions.replace(expression, pos, result)
                    replaced = True
                    break
                except StopIteration:
                    pass
            replace_count += 1
        return expression 
Example 31
Project: MCS_DTW   Author: CGuichardMasterDL   File: dtw.py    MIT License 5 votes vote down vote up
def dtw(sequence_i, sequence_j, distance=entre_fenetres_audio, # pylint: disable=R0913
        w_0=1, w_1=1, w_2=1, d_max_diagonale=math.inf):
    """
        Comparaison dynamique entre deux séquence sequence_i et sequence_j
    """
    g_mat = np.zeros(shape=(len(sequence_i)+1, len(sequence_j)+1))
    g_mat[0][0] = 0

    for j in range(1, len(sequence_j)+1):
        g_mat[0][j] = math.inf

    for i in range(1, len(sequence_i)+1):
        g_mat[i][0] = math.inf
        for j in range(1, len(sequence_j)+1):
            if distance_de_case_a_diagonale(i, j, len(sequence_i)+1,
                                            len(sequence_j)+1) <= d_max_diagonale:
                g_mat[i][j] = min([
                    g_mat[i-1][j] + w_0*distance(sequence_i[i-1], sequence_j[j-1]),
                    g_mat[i-1][j-1] + w_1 *
                    distance(sequence_i[i-1], sequence_j[j-1]),
                    g_mat[i][j-1] + w_2*distance(sequence_i[i-1], sequence_j[j-1])
                ])
            else:
                g_mat[i][j] = math.inf

    return (g_mat, get_distance(g_mat), get_path(g_mat)) 
Example 32
Project: MCS_DTW   Author: CGuichardMasterDL   File: dtw.py    MIT License 5 votes vote down vote up
def find_dtw_match(unknown_sound, base, params=None): # pylint: disable=W0613
    """
        Trouve le son le plus proche de unknown_sound dans le tableau de sons passé en paramètre
    """
    match = ""
    d_diagonale = 7
    distance_min = math.inf
    for sound in base:
        distance = dtw(unknown_sound.get_mfcc(),
                       sound.get_mfcc(), d_max_diagonale=d_diagonale)[1]
        if distance < distance_min:
            match = sound
            distance_min = distance
    return match 
Example 33
Project: Lyra   Author: caterinaurban   File: test_IntervalLattice.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_init(self):
        self.assertFalse(IntervalLattice().is_bottom())
        self.assertTrue(IntervalLattice().is_top())

        self.assertFalse(IntervalLattice(0, 1).is_bottom())
        self.assertFalse(IntervalLattice(0, 1).is_top())

        self.assertEqual(IntervalLattice(upper=2), IntervalLattice(-inf, 2))
        self.assertEqual(IntervalLattice(lower=3), IntervalLattice(3, inf))

        self.assertTrue(IntervalLattice(1, 0).is_bottom())
        self.assertFalse(IntervalLattice(1, 0).is_top()) 
Example 34
Project: Lyra   Author: caterinaurban   File: runner.py    Mozilla Public License 2.0 5 votes vote down vote up
def _expected_result(self):
        initial = re.compile('INITIAL:?\s*(?P<state>.*)')
        state = re.compile('STATE:?\s*(?P<state>.*)')
        loop = re.compile('LOOP:?\s*(?P<state>.*)')
        final = re.compile('FINAL:?\s*(?P<state>.*)')
        for token in tokenize.tokenize(io.BytesIO(self.source.encode('utf-8')).readline):
            if token.type == tokenize.COMMENT:
                comment = token.string.strip("# ")
                initial_match = initial.match(comment)
                state_match = state.match(comment)
                loop_match = loop.match(comment)
                final_match = final.match(comment)
                if initial_match:
                    result = initial_match.group('state')
                    line = -inf                 # -inf for a precondition
                    yield line, result
                if state_match:
                    result = state_match.group('state')
                    line = token.start[0]
                    yield line, result
                if loop_match:
                    result = loop_match.group('state')
                    line = -token.start[0]      # negative line number for a loop invariant
                    yield line, result
                if final_match:
                    result = final_match.group('state')
                    line = inf                  # inf for a postcondition
                    yield line, result 
Example 35
Project: Lyra   Author: caterinaurban   File: range_domain.py    Mozilla Public License 2.0 5 votes vote down vote up
def from_json(json: str) -> 'JSONMixin':
        if json == '⊥':
            return RangeLattice().bottom()
        lower, upper = json[1:-1].split(',')
        lower = int(lower) if lower != '-inf' else -inf
        upper = int(upper) if upper != 'inf' else inf
        return RangeLattice(lower, upper) 
Example 36
Project: Lyra   Author: caterinaurban   File: interval_domain.py    Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, lower=-inf, upper=inf):
        super().__init__()
        if lower <= upper and lower != inf and upper != -inf:      # the interval is not empty
            self._lower = lower
            self._upper = upper
        else:                   # the interval is empty
            self.bottom() 
Example 37
Project: Lyra   Author: caterinaurban   File: interval_domain.py    Mozilla Public License 2.0 5 votes vote down vote up
def _widening(self, other: 'IntervalLattice') -> 'IntervalLattice':
        """``[a, b] ▽ [c, d] = [(c < a ? -oo : a), (b < d ? +oo : b)]``."""
        lower = self.lower
        upper = self.upper
        if other.lower < self.lower:
            lower = -inf
        if self.upper < other.upper:
            upper = inf
        return self._replace(type(self)(lower, upper))

    # arithmetic operations 
Example 38
Project: Advanced-Data-Structures-with-Python   Author: bhavinjawade   File: segment_Tree.py    MIT License 5 votes vote down vote up
def query(st,ql,qh,low,high,pos):
  if(ql<=low and qh>=high):
    return st[pos]
  if(ql > high or qh < low):
    return math.inf
  mid = (low + high)/2
  return min(query(st,ql,qh,low,mid,2*pos + 1),
  query(st,ql,qh,mid+1,high,2*pos + 2)) 
Example 39
Project: ConvLab   Author: ConvLab   File: dataset_reader.py    MIT License 5 votes vote down vote up
def find_best_delex_act(self, action):
        def _score(a1, a2):
            score = 0
            for domain_act in a1:
                if domain_act not in a2:
                    score += len(a1[domain_act])
                else:
                    score += len(set(a1[domain_act]) - set(a2[domain_act]))
            return score

        best_p_action_index = -1
        best_p_score = math.inf
        best_pn_action_index = -1
        best_pn_score = math.inf
        for i, v_action in enumerate(self.action_list):
            if v_action == action:
                return i
            else:
                p_score = _score(action, v_action)
                n_score = _score(v_action, action)
                if p_score > 0 and n_score == 0 and p_score < best_p_score:
                    best_p_action_index = i
                    best_p_score = p_score
                else:
                    if p_score + n_score < best_pn_score:
                        best_pn_action_index = i
                        best_pn_score = p_score + n_score
        if best_p_action_index >= 0:
            return best_p_action_index
        return best_pn_action_index 
Example 40
Project: Jtyoui   Author: jtyoui   File: theorem.py    MIT License 5 votes vote down vote up
def theorem_Zero(function, x1: float, x2: float) -> float:
    """零点定理

    定义一个函数:x^3-2x-5=0,求x等于多少。x的值域:[1,1000]
    原理利用二分法不断的逼近,求出答案

    :param function: 定一个函数
    :param x1: 开始值
    :param x2: 结束值
    :return: 返回零点的值
    """
    if function(x1) == 0:
        return x1
    elif function(x2) == 0:
        return x2
    elif function(x1) * function(x2) > 0:
        warnings.warn('[a,b]区间的值应该满足:f(a)*f(b)<0', category=MathValueWarning)
        return math.inf
    else:
        mid = x1 + (x2 - x1) / 2.0
        while abs(x1 - mid) > math.pow(10, -9):  # x值小于10亿分之一
            if function(mid) == 0:
                return mid
            elif function(mid) * function(x1) < 0:
                x2 = mid
            else:
                x1 = mid
            mid = x1 + (x2 - x1) / 2.0
        return mid 
Example 41
Project: pytorch-a3c   Author: wuhuikai   File: eval_utils.py    MIT License 5 votes vote down vote up
def play_game(env, model, max_episode_length=math.inf, vis=None, render=False, rand=False, gpu_id=-1):
    if vis:
        vis, window_id, fps = vis
        frame_dur = 1.0 / fps
        last_time = time.time()

    reward_sum, episode_length = 0, 0
    state = torch.from_numpy(env.reset()).float()
    with torch.cuda.device(gpu_id):
        state = state.cuda() if gpu_id >= 0 else state

    while True:
        _, logit = model(Variable(state.unsqueeze(0), volatile=True))
        prob = F.softmax(logit)
        action = prob.multinomial(1) if rand else prob.max(1)[1]
        raw_state, reward, done, _ = env.step(action.data.cpu().numpy()[0, 0])
        reward_sum += reward

        episode_length += 1
        if vis and time.time() > last_time + frame_dur:
            vis.image(np.transpose(env.render(mode='rgb_array'), (2,0,1)), win=window_id)
            last_time = time.time()

        if render:
            env.render()

        if done:
            return reward_sum, False
        if episode_length > max_episode_length:
            return reward_sum, True

        state = state.copy_(torch.from_numpy(raw_state).float()) 
Example 42
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testAtan(self):
        self.assertRaises(TypeError, math.atan)
        self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
        self.ftest('atan(0)', math.atan(0), 0)
        self.ftest('atan(1)', math.atan(1), math.pi/4)
        self.ftest('atan(inf)', math.atan(INF), math.pi/2)
        self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
        self.assertTrue(math.isnan(math.atan(NAN))) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
                   abs_tol=ulp(1))
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN))) 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testIsfinite(self):
        self.assertTrue(math.isfinite(0.0))
        self.assertTrue(math.isfinite(-0.0))
        self.assertTrue(math.isfinite(1.0))
        self.assertTrue(math.isfinite(-1.0))
        self.assertFalse(math.isfinite(float("nan")))
        self.assertFalse(math.isfinite(float("inf")))
        self.assertFalse(math.isfinite(float("-inf"))) 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testIsnan(self):
        self.assertTrue(math.isnan(float("nan")))
        self.assertTrue(math.isnan(float("-nan")))
        self.assertTrue(math.isnan(float("inf") * 0.))
        self.assertFalse(math.isnan(float("inf")))
        self.assertFalse(math.isnan(0.))
        self.assertFalse(math.isnan(1.)) 
Example 46
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def test_inf_constant(self):
        self.assertTrue(math.isinf(math.inf))
        self.assertGreater(math.inf, 0.0)
        self.assertEqual(math.inf, float("inf"))
        self.assertEqual(-math.inf, float("-inf"))

    # RED_FLAG 16-Oct-2000 Tim
    # While 2.0 is more consistent about exceptions than previous releases, it
    # still fails this part of the test on some platforms.  For now, we only
    # *run* test_exceptions() in verbose mode, so that this isn't normally
    # tested. 
Example 47
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 5 votes vote down vote up
def check_polar(self, func):
        def check(arg, expected):
            got = func(arg)
            for e, g in zip(expected, got):
                self.rAssertAlmostEqual(e, g)
        check(0, (0., 0.))
        check(1, (1., 0.))
        check(-1, (1., pi))
        check(1j, (1., pi / 2))
        check(-3j, (3., -pi / 2))
        inf = float('inf')
        check(complex(inf, 0), (inf, 0.))
        check(complex(-inf, 0), (inf, pi))
        check(complex(3, inf), (inf, pi / 2))
        check(complex(5, -inf), (inf, -pi / 2))
        check(complex(inf, inf), (inf, pi / 4))
        check(complex(inf, -inf), (inf, -pi / 4))
        check(complex(-inf, inf), (inf, 3 * pi / 4))
        check(complex(-inf, -inf), (inf, -3 * pi / 4))
        nan = float('nan')
        check(complex(nan, 0), (nan, nan))
        check(complex(0, nan), (nan, nan))
        check(complex(nan, nan), (nan, nan))
        check(complex(inf, nan), (inf, nan))
        check(complex(-inf, nan), (inf, nan))
        check(complex(nan, inf), (inf, nan))
        check(complex(nan, -inf), (inf, nan)) 
Example 48
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_isfinite(self):
        real_vals = [float('-inf'), -2.3, -0.0,
                     0.0, 2.3, float('inf'), float('nan')]
        for x in real_vals:
            for y in real_vals:
                z = complex(x, y)
                self.assertEqual(cmath.isfinite(z),
                                  math.isfinite(x) and math.isfinite(y)) 
Example 49
Project: Autoenv   Author: intelligent-control-lab   File: collision_detection.py    MIT License 5 votes vote down vote up
def get_collision_time(ray: VecSE2.VecSE2, poly: ConvexPolygon, ray_speed: float):
    min_col_time = math.inf
    for i in range(len(poly)):
        seg = get_poly_edge(poly, i)
        col_time = get_intersection_time(Projectile(ray, ray_speed), seg)
        if col_time and col_time < min_col_time:
            min_col_time = col_time
    return min_col_time 
Example 50
Project: sequeval   Author: D2KLab   File: evaluator.py    MIT License 5 votes vote down vote up
def perplexity(self, recommender):
        cross_entropy = np.full(len(self.test_set), 0.0, dtype=float)
        count_ratings = 0

        for sequence_index, sequence in enumerate(self.test_set):

            for rating_index, rating in enumerate(sequence):
                try:
                    next_item = sequence[rating_index + 1][0]
                    probability = recommender.predict_item(rating, next_item)

                    if probability > 0:
                        # noinspection PyUnresolvedReferences
                        cross_entropy[sequence_index] -= np.log2(probability)
                    else:
                        cross_entropy[sequence_index] = math.inf

                    count_ratings += 1

                except IndexError:
                    # The sequence has ended
                    pass

            recommender.reset()

        perplexity = 2 ** (cross_entropy.sum() / count_ratings)

        return perplexity 
Example 51
Project: sequeval   Author: D2KLab   File: test_evaluator.py    MIT License 5 votes vote down vote up
def test_perplexity(self):
        evaluator = sequeval.Evaluator(training_set, test_set, items, 3)
        recommender = baseline.MostPopularRecommender(training_set, items)
        self.assertAlmostEqual(math.inf, evaluator.perplexity(recommender))
        recommender = baseline.RandomRecommender(training_set, items)
        self.assertAlmostEqual(3.0, evaluator.perplexity(recommender)) 
Example 52
Project: code_sorted   Author: jan25   File: skip_list.py    The Unlicense 5 votes vote down vote up
def __init__(self):
        a, b = Node(-math.inf), Node(math.inf) # left, right most infinite columns
        a.next = b
        b.prev = a
        self.l = a # top-left node
        # self._pretty_print('__init__') 
Example 53
Project: code_sorted   Author: jan25   File: skip_list.py    The Unlicense 5 votes vote down vote up
def _do_promote(self, node: Node, down_nodes: List[Node]) -> None:
        while self._must_promote():
            prev_node = None
            if len(down_nodes) > 0:
                prev_node = down_nodes.pop()
            else:
                new_minf_node = Node(-math.inf)
                new_inf_node = Node(math.inf)
                new_inf_node.prev = new_minf_node
                new_minf_node.next = new_inf_node
                new_minf_node.down = self.l # Note: we are not setting new_inf_node.down, not idea how to set quickly
                self.l.up = new_minf_node
                self.l = new_minf_node

                prev_node = new_minf_node
            
            new_node = Node(node.val)
            new_node.next = prev_node.next
            new_node.next.prev = new_node
            prev_node.next = new_node
            new_node.prev = prev_node

            new_node.down = node
            node.up = new_node
            node = node.up

    # coin flip to decide whether to promote a node to a upper level 
Example 54
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 5 votes vote down vote up
def demoMagic(agent):
    currentSpd = agent.getCurrentSpd()
    if currentSpd <1900:
        if agent.me.boostLevel <=0:
            agent.activeState.active = False
    e_goal = Vector([0, 5100 * -sign(agent.team), 200])
    best = None
    distance = math.inf
    for e in agent.enemies:
        if e.location[2] <= 120:
            _distance = distance2D(e_goal,e.location)
            if _distance < distance:
                distance = _distance
                best = e

    if best != None:
        if currentSpd <=100:
            currentSpd = 100

        currentTimeToTarget = distance / currentSpd
        lead = clamp(agent.deltaTime*60,agent.deltaTime*5,agent.deltaTime*distance/500)
        difference = best.velocity.scale(lead)
        targetPos = e.location + difference
        agent.renderCalls.append(
            renderCall(agent.renderer.draw_line_3d, agent.me.location.data, targetPos.data, agent.renderer.purple))

        if currentTimeToTarget <= agent.deltaTime*30:
            targetLocal = toLocal(targetPos,agent.me)
            angle = math.degrees(math.atan2(targetLocal[1],targetLocal[0]))
            if abs(angle) <= 40:
                agent.setJumping(0)

        return testMover(agent,targetPos,2300)



    else:
        return None 
Example 55
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 5 votes vote down vote up
def saferBoostGrabber(agent):
    minDistance = distance2D(Vector([0, 5100 * sign(agent.team), 200]),agent.ball.location)
    closestBoost = physicsObject()
    closestBoost.location = Vector([0, 5100 * sign(agent.team), 200])
    bestDistance = math.inf
    bestAngle = 0

    for boost in agent.boosts:
        if boost.spawned:
            goalDistance = distance2D(boost.location, Vector([0, 5100 * sign(agent.team), 200]))
            if goalDistance < minDistance*.7:
                distance = distance2D(agent.me.location,boost.location)
                localCoords = toLocal(boost.location, agent.me)
                angle = abs(math.degrees(math.atan2(localCoords[1], localCoords[0])))
                if boost.bigBoost:
                    distance = distance*.5
                distance += angle * 5
                if distance < bestDistance:
                    bestDistance = distance
                    closestBoost = boost
                    bestAngle = angle

    agent.renderCalls.append(renderCall(agent.renderer.draw_line_3d, agent.me.location.data, closestBoost.location.data,
                                        agent.renderer.yellow))

    return efficientMover(agent, closestBoost.location, agent.maxSpd,boostHunt=False) 
Example 56
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 5 votes vote down vote up
def findEnemyClosestToLocation(agent,location):
    if len(agent.enemies) > 0:
        closest = agent.enemies[0]
        cDist = math.inf
        for e in agent.enemies:
            x = findDistance(e.location, location)
            if x < cDist:
                cDist = x
                closest = e
        return closest,cDist
    else:
        return None,None 
Example 57
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 5 votes vote down vote up
def findSuitableBallPosition2(agent, heightMax, speed, origin):
    applicableStructs = []
    spd = clamp(2300,300,speed)
    ballInGoal = None
    goalTimer = math.inf
    if agent.ballPred is not None:
        for i in range(0, agent.ballPred.num_slices):
            if isBallHittable(agent.ballPred.slices[i],agent,heightMax):
                applicableStructs.append(agent.ballPred.slices[i])
                if agent.team == 0:
                    if agent.ballPred.slices[i].physics.location.y <= -5050:
                        ballInGoal = agent.ballPred.slices[i]
                        goalTimer = agent.ballPred.slices[i].game_seconds - agent.gameInfo.seconds_elapsed
                        break
                else:
                    if agent.ballPred.slices[i].physics.location.y >= 5050:
                        ballInGoal = agent.ballPred.slices[i]
                        goalTimer = agent.ballPred.slices[i].game_seconds - agent.gameInfo.seconds_elapsed
                        break
                applicableStructs.append(agent.ballPred.slices[i])

    for pred in applicableStructs:
        distance = distance2D(Vector([pred.physics.location.x,pred.physics.location.y]),origin)
        adjustSpd = clamp(2300,1000,speed+distance*.7)
        if distance/adjustSpd < (pred.game_seconds - agent.gameInfo.seconds_elapsed):
            if goalTimer < pred.game_seconds - agent.gameInfo.seconds_elapsed:
                agent.goalPred = ballInGoal
            return pred

    if goalTimer < math.inf:
        agent.goalPred = ballInGoal
    return agent.ballPred.slices[-1] 
Example 58
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 5 votes vote down vote up
def inaccurateArrivalEstimatorRemote(agent,start,destination):
    distance = clamp(math.inf,1,distance2D(start,destination))
    currentSpd = clamp(2300,1,agent.getCurrentSpd())

    if agent.me.boostLevel > 0:
        maxSpd = clamp(2300,currentSpd,currentSpd+ (distance*.3))
    else:
        maxSpd = clamp(2200, currentSpd, currentSpd + (distance*.15))

    return distance/maxSpd 
Example 59
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 5 votes vote down vote up
def CB_Reworked(agent,targetVec):
    dist = clamp(25000, 1, distance2D(agent.me.location, targetVec))
    ballDist = clamp(25000, 1, distance2D(agent.me.location, agent.ball.location))
    destinationEstimate = inaccurateArrivalEstimator(agent,targetVec)
    locTarget = toLocal(targetVec, agent.me)
    targetAngle = correctAngle(math.degrees(math.atan2(locTarget[1], locTarget[0])))

    bestBoost = None
    bestAngle = 0
    angleDisparity = 1000
    bestDist = math.inf
    bestEstimate = math.inf
    goodBoosts = []
    for b in agent.boosts:
        _dist = distance2D(b.location, agent.me.location)
        if _dist < dist*.6:
            localCoords = toLocal(b.location, agent.me)
            angle = correctAngle(math.degrees(math.atan2(localCoords[1], localCoords[0])))
            _angleDisparity = targetAngle - angle

            if _angleDisparity > targetAngle-30 and _angleDisparity < targetAngle+30:
                goodBoosts.append(b)

    for b in goodBoosts:
        pathEstimate = inaccurateArrivalEstimator(agent,b.location) + inaccurateArrivalEstimatorRemote(agent,b.location,targetVec)
        if agent.me.boostLevel < 50:
            if b.bigBoost:
                pathEstimate*=.8
        if pathEstimate < bestEstimate:
            bestBoost = b
            bestEstimate = pathEstimate

    if bestEstimate < destinationEstimate*1.15 or bestEstimate < agent.ballDelay:
        return bestBoost.location
    else:
        return None 
Example 60
Project: BiLatticeRNN-data-processing   Author: alecokas   File: enrich_confusion_network.py    MIT License 5 votes vote down vote up
def find_match(cn_word_emb, cn_word, cn_edge_start_time, cn_edge_duration, lat_words, lat_edge_start_times, lat_edge_durations, lat_posteriors, max_time_diff):
    """ Iterate each arc in the lattice and find the arc which corresponds to the confusion network arc.
        Returning an arc index of -1 indicates that no matches were found.
    """
    candidate_list = []
    min_cost = math.inf
    for lat_arc_idx, lat_word in enumerate(lat_words):
        # Check that the words match
        if (cn_word_emb == lat_word).all():
            cost = cost_fn(cn_edge_start_time, cn_edge_duration, lat_edge_start_times[lat_arc_idx], lat_edge_durations[lat_arc_idx], max_time_diff)
            if cost >= 0 and cost <= min_cost:
                if cost == min_cost:
                    candidate_list.append((lat_arc_idx, cost, lat_posteriors[lat_arc_idx]))
                else:
                    # When cost < min_cost
                    candidate_list = [(lat_arc_idx, cost, lat_posteriors[lat_arc_idx])]
                    min_cost = cost
    if not candidate_list:
        print('No matches found for CN arc {} with start time: {} and duration: {}'.format(cn_word, cn_edge_start_time, cn_edge_duration))
        LOGGER.info('No matches found for CN arc {} with start time: {} and duration: {}'.format(cn_word, cn_edge_start_time, cn_edge_duration))
        return -1
    if len(candidate_list) > 1 and isinstance(candidate_list, list):
        # Need to sort by posterior and choose the one with the highest posterior
        match = sorted(candidate_list, key=lambda x: x[2], reverse=True)[0][0]
    elif len(candidate_list) == 1 and isinstance(candidate_list, list):
        match = candidate_list[0][0]
    else:
        # Must be just a tuple - only one candidate
        match = candidate_list[0]
    # Return the index of the matching arc in the lattice
    return match 
Example 61
Project: linnea   Author: HPAC   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def apply_kernel_with_context(expr, many_to_one_matcher):
    """Applies the optimal kernel to an expressions.

    This function applies the optimal matching kernel of the many_to_one_matcher
    to expr and returns the replacement, as well as the matched kernel.

    The functions only searches for matches at the root of expr, and it expects
    many_to_one_matcher to use the patterns with context variables
    (Kernel.pattern_with_context).

    Args:
        expr (Expression): The expression where the kernel should be applied.
        many_to_one_matcher (ManyToOneMatcher): Matcher for kernel patterns with
            context. The label has to be the kernel.

    Returns:
        A tuple containing
        - the replacement (Expression)
        - the matched kernel (MatchedKernel)
        If no match was found, the replacement is the input expression and
        instead of the matched kernel, None is returned.
    """

    optimal_match = (None, None)
    min_cost = math.inf

    for kernel, substitution in many_to_one_matcher.match(expr):
        cost = kernel.cost(substitution)
        if cost < min_cost:
            optimal_match = (kernel, substitution)

    kernel, substitution = optimal_match
    if kernel:
        matched_kernel = kernel.set_match(substitution, True)
        expr = matched_kernel.replacement
        return expr, matched_kernel
    return (expr, None) 
Example 62
Project: linnea   Author: HPAC   File: base.py    GNU General Public License v3.0 5 votes vote down vote up
def shortest_path(self):
        try:
            path, cost = next(self.k_shortest_paths(1))
        except StopIteration:
            return ([], math.inf)
        else:
            return (path, cost) 
Example 63
Project: linnea   Author: HPAC   File: base.py    GNU General Public License v3.0 5 votes vote down vote up
def optimal_algorithm(self):
        matched_kernels = []
        current_node = self.root
        path, cost = self.shortest_path()
        if path:
            for idx in path:

                matched_kernels.extend(current_node.edge_labels[idx].matched_kernels)
                if current_node.successors:
                    current_node = current_node.successors[idx]

            return matched_kernels, cost, current_node.get_payload()
        else:
            return [], math.inf, None 
Example 64
Project: linnea   Author: HPAC   File: matrix_chain_derivation.py    GNU General Public License v3.0 5 votes vote down vote up
def derivation(self):

        old_verbosity = config.verbosity
        config.set_verbosity(0)

        self.best_first_search(time_limit=math.inf)

        config.set_verbosity(old_verbosity) 
Example 65
Project: linnea   Author: HPAC   File: config.py    GNU General Public License v3.0 5 votes vote down vote up
def set_time_limit(limit):
    global time_limit
    if isinstance(limit, str):
        if limit == "inf":
            time_limit = math.inf
        else:
            time_limit = float(limit)
    else:    
        time_limit = limit 
Example 66
Project: workload-collocation-agent   Author: intel   File: allocations.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, value: Union[float, int],
                 common_labels: Dict[str, str] = None,
                 min_value: Optional[Union[int, float]] = 0,
                 max_value: Optional[Union[int, float]] = None,
                 value_change_sensitivity: float = VALUE_CHANGE_SENSITIVITY,
                 ):
        if not isinstance(value, (float, int)):
            assert isinstance(value, (float, int)), \
                    'should be of type (float, int) but was {}'.format(type(value))
        self.value = value
        self.value_change_sensitivity = value_change_sensitivity
        self.min_value = min_value if min_value is not None else -math.inf
        self.max_value = max_value if max_value is not None else math.inf
        self.labels_updater = LabelsUpdater(common_labels or {}) 
Example 67
Project: resolwe   Author: genialis   File: listener.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize attributes.

        :param host: Optional. The hostname where redis is running.
        :param port: Optional. The port where redis is running.
        """
        super().__init__()

        # The Redis connection object.
        self._redis = None
        self._redis_params = kwargs.get('redis_params', {})

        # Running coordination.
        self._should_stop = False
        self._runner_coro = None

        # The verbosity level to pass around to Resolwe utilities
        # such as location_purge.
        self._verbosity = kwargs.get('verbosity', 1)

        # Statistics about how much time each event needed for handling.
        self.service_time = stats.NumberSeriesShape()

        # Statistics about the number of events handled per time interval.
        self.load_avg = stats.SimpleLoadAvg([60, 5 * 60, 15 * 60])

        # Timestamp of last critical load error and level, for throttling.
        self.last_load_log = -math.inf
        self.last_load_level = 0 
Example 68
Project: resolwe   Author: genialis   File: stats.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        """Construct an instance of the class."""
        self.high = -math.inf
        self.low = math.inf
        self.mean = 0
        self.deviation = 0
        self.count = 0
        self._rolling_variance = 0 
Example 69
Project: resolwe   Author: genialis   File: stats.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, intervals):
        """Construct an instance of the class.

        :param interval: A list of interval lengths, in seconds.
        """
        self.last_data = -math.inf
        self.intervals = {i: SimpleLoadAvg._Interval(i) for i in intervals}
        for meta in list(self.intervals.values()):
            self.intervals[meta.display] = meta 
Example 70
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 4 votes vote down vote up
def calcTimeWithAcceleration(agent,distance,boostless = False):
    estimatedSpd = agent.currentSpd
    estimatedTime = 0
    distanceTally = 0
    if boostless:
        boostAmount = 0
    else:
        boostAmount = agent.me.boostLevel
    boostingCost = 33.3*agent.deltaTime
    linearChunk = 1600/1410
    while distanceTally < distance and estimatedTime < 6:
        if estimatedSpd < maxPossibleSpeed:
            acceleration = 1600 - (estimatedSpd*linearChunk)
            if boostAmount > 0:
                acceleration+=991
                boostAmount -= boostingCost
            if acceleration > 0:
                estimatedSpd += acceleration * agent.deltaTime
            distanceTally+= estimatedSpd*agent.deltaTime
            estimatedTime += agent.deltaTime
        else:
            #estimatedSpd += acceleration * agent.deltaTime
            distanceTally += estimatedSpd * agent.deltaTime
            estimatedTime += agent.deltaTime

    #print("friendly ended")
    return estimatedTime

# def inaccurateArrivalEstimator(agent,destination):
#     distance = clamp(math.inf,1,distance2D(agent.me.location,destination))
#     currentSpd = clamp(2300,1,agent.getCurrentSpd())
#     localTarg = toLocal(destination,agent.me)
#     if agent.forward:
#         angle = math.degrees(math.atan2(localTarg[1],localTarg[0]))
#     else:
#         angle = correctAngle(math.degrees(math.atan2(localTarg[1],localTarg[0]))-180)
#     if distance < 2000:
#         if abs(angle) > 40:
#             distance+= abs(angle)
#
#     if agent.me.boostLevel > 0:
#         maxSpd = clamp(2300,currentSpd,currentSpd+ (distance*.3))
#     else:
#         maxSpd = clamp(2200, currentSpd, currentSpd + (distance*.15))
#
#     return distance/maxSpd 
Example 71
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 4 votes vote down vote up
def findSuitableBallPosition(agent, heightMax, speed, origin):
    applicableStructs = []
    spd = clamp(2300,300,speed)
    ballInGoal = None
    goalTimer = math.inf
    if agent.ballPred is not None:
        for i in range(0, agent.ballPred.num_slices):
            if isBallHittable(agent.ballPred.slices[i],agent,heightMax):
                applicableStructs.append(agent.ballPred.slices[i])
                if agent.team == 0:
                    if agent.ballPred.slices[i].physics.location.y <= -5250:
                        ballInGoal = agent.ballPred.slices[i]
                        goalTimer = agent.ballPred.slices[i].game_seconds - agent.gameInfo.seconds_elapsed
                        break
                else:
                    if agent.ballPred.slices[i].physics.location.y >= 5250:
                        ballInGoal = agent.ballPred.slices[i]
                        goalTimer = agent.ballPred.slices[i].game_seconds - agent.gameInfo.seconds_elapsed
                        break
    agent.wallShot = False
    for pred in applicableStructs:
        distance = distance2D(Vector([pred.physics.location.x,pred.physics.location.y]),origin)
        timeToTarget = inaccurateArrivalEstimator(agent,Vector([pred.physics.location.x,pred.physics.location.y,pred.physics.location.z]))
        #adjustSpd = clamp(2300,1000,speed+distance*.7)
        if timeToTarget < (pred.game_seconds - agent.gameInfo.seconds_elapsed):
            if goalTimer < pred.game_seconds - agent.gameInfo.seconds_elapsed:
                agent.goalPred = ballInGoal
            agent.wallShot = isBallNearWall(pred)
            if timeToTarget < goalTimer:
                return pred


    if ballInGoal:
        agent.wallShot = isBallNearWall(ballInGoal)
        return ballInGoal

    if len(applicableStructs) > 0:
        agent.wallShot = isBallNearWall(applicableStructs[0])
        return applicableStructs[0]

    agent.wallShot = isBallNearWall(agent.ballPred.slices[-1])
    return agent.ballPred.slices[-1] 
Example 72
Project: RLBotPack   Author: RLBot   File: Utilities.py    MIT License 4 votes vote down vote up
def convenientBoost(agent,targetVec):
    dist = clamp(25000,1,distance2D(agent.me.location,targetVec))
    ballDist = clamp(25000,1,distance2D(agent.me.location,agent.ball.location))
    spd = agent.getCurrentSpd()
    spd = clamp(2200,1500,spd + spd/(dist/1000))

    locTarget = toLocal(targetVec,agent.me)
    targetAngle = correctAngle(math.degrees(math.atan2(locTarget[1],locTarget[0])))


    bestBoost = None
    bestAngle = 0
    angleDisparity = 1000
    bestDist = math.inf
    goodBoosts = []
    for b in agent.boosts:
        _dist = distance2D(b.location,agent.me.location)
        if _dist < dist-500:
            localCoords = toLocal(b.location,agent.me)
            angle = correctAngle(math.degrees(math.atan2(localCoords[1],localCoords[0])))
            _angleDisparity = targetAngle - angle
            _angleDisparity = (_angleDisparity + 180) % 360 - 180
            if b.bigBoost:
                if _angleDisparity > 5:
                    _angleDisparity-=5
                elif _angleDisparity < -5:
                    _angleDisparity +=5

            if abs(_angleDisparity) < clamp(35,0,30*_dist/2000):
                goodBoosts.append(b)


    for each in goodBoosts:
        d = distance2D(each.location,agent.me.location)
        if each.bigBoost:
            d *=.7
        if d < bestDist:
            bestBoost = each
            bestDist = d


    if bestBoost != None and abs(angleDisparity) and (bestDist/spd + distance2D(bestBoost.location,targetVec)/spd < agent.ballDelay):
        if (bestDist/spd) + (distance2D(bestBoost.location,targetVec)/spd) <= agent.ballDelay or ballDist >= 3000:
            return bestBoost.location

    return None 
Example 73
Project: StatNLP-PyTorch   Author: allanj   File: Network.py    GNU General Public License v3.0 4 votes vote down vote up
def get_inside(self, k):
        if self.is_removed(k):
            self.inside_scores[k] = -math.inf
            return

        inside_score = -math.inf
        children_list_k = self.get_children(k)
        ## If this node has no child edge, assume there is one edge with no child node
        ## This is done so that every node is visited in the feature extraction step below
        if len(children_list_k) == 0:
            children_list_k = np.zeros((1, 0))


        # print('children_list_k:', children_list_k, ' k:', k, 'len(children_list_k):', len(children_list_k))

        scores = autograd.Variable(torch.Tensor(len(children_list_k)).cuda() if NetworkConfig.GPU_ID >= 0 else torch.Tensor(len(children_list_k)))
        for children_k_index in range(len(children_list_k)):
            children_k = children_list_k[children_k_index]
            ignore_flag = False
            for child_k in children_k:
                if child_k < 0:
                    continue
                if self.is_removed(child_k):
                    ignore_flag = True
            if ignore_flag:
                continue
            fa = self.param.extract(self, k, children_k, children_k_index)
            #global_param_version = self.param.fm.get_param_g().get_version()
            score = fa.get_score(self.param)
            #print('score after get_score:', score)
            # print("hyper edge child: ", children_k, " curr node arr: ", self.get_node_array(k))
            for child_k in children_k:
                if child_k < 0:
                    continue
                score += self.inside_scores[child_k]

            scores[children_k_index] = score

        # print(" curr node arr: ", self.get_node_array(k))
        # print('scores:', scores, " len : ", len(scores))
        # for score in scores:
        #     print('score type:', type(score))
        #print(len(scores))
        self.inside_scores[k] = scores[0]  if len(scores) == 1 else log_sum_exp(scores) 
Example 74
Project: matchpy   Author: HPAC   File: functions.py    MIT License 4 votes vote down vote up
def replace_all(expression: Expression, rules: Iterable[ReplacementRule], max_count: int=math.inf) \
        -> Union[Expression, Sequence[Expression]]:
    """Replace all occurrences of the patterns according to the replacement rules.

    A replacement rule consists of a *pattern*, that is matched against any subexpression
    of the expression. If a match is found, the *replacement* callback of the rule is called with
    the variables from the match substitution. Whatever the callback returns is used as a replacement for the
    matched subexpression. This can either be a single expression or a sequence of expressions, which is then
    integrated into the surrounding operation in place of the subexpression.

    Note that the pattern can therefore not be a single sequence variable/wildcard, because only single expressions
    will be matched.

    Args:
        expression:
            The expression to which the replacement rules are applied.
        rules:
            A collection of replacement rules that are applied to the expression.
        max_count:
            If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
            are applied until there is no more match. If the set of replacement rules is not confluent,
            the replacement might not terminate without a *max_count* set.

    Returns:
        The resulting expression after the application of the replacement rules. This can also be a sequence of
        expressions, if the root expression is replaced with a sequence of expressions by a rule.
    """
    rules = [ReplacementRule(pattern, replacement) for pattern, replacement in rules]
    expression = expression
    replaced = True
    replace_count = 0
    while replaced and replace_count < max_count:
        replaced = False
        for subexpr, pos in preorder_iter_with_position(expression):
            for pattern, replacement in rules:
                try:
                    subst = next(match(subexpr, pattern))
                    result = replacement(**subst)
                    expression = replace(expression, pos, result)
                    replaced = True
                    break
                except StopIteration:
                    pass
            if replaced:
                break
        replace_count += 1

    return expression 
Example 75
Project: ConvLab   Author: ConvLab   File: multiwoz.py    MIT License 4 votes vote down vote up
def rule_policy(self, state, algorithm, body):
        def find_best_delex_act(action):
            def _score(a1, a2):
                score = 0
                for domain_act in a1:
                    if domain_act not in a2:
                        score += len(a1[domain_act])
                    else:
                        score += len(set(a1[domain_act]) - set(a2[domain_act]))
                return score

            best_p_action_index = -1 
            best_p_score = math.inf 
            best_pn_action_index = -1 
            best_pn_score = math.inf 
            for i, v_action in enumerate(self.action_vocab.vocab):
                if v_action == action:
                    return i
                else:
                    p_score = _score(action, v_action)
                    n_score = _score(v_action, action)
                    if p_score > 0 and n_score == 0 and p_score < best_p_score:
                        best_p_action_index = i
                        best_p_score = p_score
                    else:
                        if p_score + n_score < best_pn_score:
                            best_pn_action_index = i
                            best_pn_score = p_score + n_score
            if best_p_action_index >= 0:
                return best_p_action_index
            return best_pn_action_index

        rule_act = self.sys_policy.predict(state)
        delex_act = {}
        for domain_act in rule_act:
            domain, act_type = domain_act.split('-', 1)
            if act_type in ['NoOffer', 'OfferBook']:
                delex_act[domain_act] = ['none'] 
            elif act_type in ['Select']:
                for sv in rule_act[domain_act]:
                    if sv[0] != "none":
                        delex_act[domain_act] = [sv[0]] 
                        break
            else:
                delex_act[domain_act] = [sv[0] for sv in rule_act[domain_act]] 
        action = find_best_delex_act(delex_act)

        return action 
Example 76
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 4 votes vote down vote up
def testAtan2(self):
        self.assertRaises(TypeError, math.atan2)
        self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
        self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
        self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
        self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
        self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)

        # math.atan2(0, x)
        self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
        self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
        self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
        self.assertEqual(math.atan2(0., 0.), 0.)
        self.assertEqual(math.atan2(0., 2.3), 0.)
        self.assertEqual(math.atan2(0., INF), 0.)
        self.assertTrue(math.isnan(math.atan2(0., NAN)))
        # math.atan2(-0, x)
        self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
        self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
        self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
        self.assertEqual(math.atan2(-0., 0.), -0.)
        self.assertEqual(math.atan2(-0., 2.3), -0.)
        self.assertEqual(math.atan2(-0., INF), -0.)
        self.assertTrue(math.isnan(math.atan2(-0., NAN)))
        # math.atan2(INF, x)
        self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
        self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
        self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
        self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
        self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
        self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
        self.assertTrue(math.isnan(math.atan2(INF, NAN)))
        # math.atan2(NINF, x)
        self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
        self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
        self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
        self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
        self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
        self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
        self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
        # math.atan2(+finite, x)
        self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
        self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
        self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
        self.assertEqual(math.atan2(2.3, INF), 0.)
        self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
        # math.atan2(-finite, x)
        self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
        self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
        self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
        self.assertEqual(math.atan2(-2.3, INF), -0.)
        self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
        # math.atan2(NAN, x)
        self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
        self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
        self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
        self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
        self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
        self.assertTrue(math.isnan(math.atan2(NAN, INF)))
        self.assertTrue(math.isnan(math.atan2(NAN, NAN))) 
Example 77
Project: Autoenv   Author: intelligent-control-lab   File: collision_detection.py    MIT License 4 votes vote down vote up
def minkowksi_sum(retval: ConvexPolygon, P: ConvexPolygon, Q: ConvexPolygon):
    '''

    For two convex polygons P and Q in the plane with m and n vertices, their Minkowski sum is a
    convex polygon with at most m + n vertices and may be computed in time O (m + n) by a very simple procedure,
    which may be informally described as follows.
    Assume that the edges of a polygon are given and the direction, say, counterclockwise, along the polygon boundary.
    Then it is easily seen that these edges of the convex polygon are ordered by polar angle.
    Let us merge the ordered sequences of the directed edges from P and Q into a single ordered sequence S.
    Imagine that these edges are solid arrows which can be moved freely while keeping them parallel to their original direction.
    Assemble these arrows in the order of the sequence S by attaching the tail of the next arrow to the head of the previous arrow.
    It turns out that the resulting polygonal chain will in fact be a convex polygon which is the Minkowski sum of P and Q.

    '''

    retval.set(empty(retval))

    index_P = 0
    index_Q = 0

    theta_p = get_polar_angle(get_edge(P.pts, index_P, P.npts))
    theta_q = get_polar_angle(get_edge(Q.pts, index_Q, Q.npts))

    while index_P < len(P) or index_Q < len(Q):
        # select next edge with minimum polar angle

        if theta_p == theta_q:
            seg_p = get_edge(P.pts, index_P, P.npts)
            seg_q = get_edge(Q.pts, index_Q, Q.npts)

            O = (P.pts[0] + Q.pts[0]) if isempty(retval) else retval.pts[retval.npts - 1]
            retval.set(push(retval, O + seg_p.B - seg_p.A + seg_q.B - seg_q.A))
            index_P += 1
            theta_p = get_polar_angle(get_edge(P.pts, index_P, P.npts)) if index_P < len(P) else math.inf
            index_Q += 1
            theta_q = get_polar_angle(get_edge(Q.pts, index_Q, Q.npts)) if index_Q < len(Q) else math.inf
        elif theta_p <= theta_q:
            seg = get_edge(P.pts, index_P, P.npts)
            O = (P.pts[0] + Q.pts[0]) if isempty(retval) else retval.pts[retval.npts - 1]
            retval.set(push(retval, O + seg.B - seg.A))
            index_P += 1
            theta_p = get_polar_angle(get_edge(P.pts, index_P, P.npts)) if index_P < len(P) else math.inf
        else:
            seg = get_edge(Q.pts, index_Q, Q.npts)
            O = (P.pts[0] + Q.pts[0]) if isempty(retval) else retval.pts[retval.npts - 1]
            retval.set(push(retval, O + seg.B - seg.A))
            index_Q += 1
            theta_q = get_polar_angle(get_edge(Q.pts, index_Q, Q.npts)) if index_Q < len(Q) else math.inf

    retval.set(ensure_pts_sorted_by_min_polar_angle(retval))

    return retval 
Example 78
Project: Diablo   Author: oxrock   File: Utilities.py    MIT License 4 votes vote down vote up
def convenientBoost(agent,targetVec):
    dist = clamp(25000,1,distance2D(agent.me.location,targetVec))
    ballDist = clamp(25000,1,distance2D(agent.me.location,agent.ball.location))
    spd = agent.getCurrentSpd()
    spd = clamp(2200,1500,spd + spd/(dist/1000))

    locTarget = toLocal(targetVec,agent.me)
    targetAngle = correctAngle(math.degrees(math.atan2(locTarget[1],locTarget[0])))


    bestBoost = None
    bestAngle = 0
    angleDisparity = 1000
    bestDist = math.inf
    goodBoosts = []
    for b in agent.boosts:
        _dist = distance2D(b.location,agent.me.location)
        if _dist < dist-500:
            localCoords = toLocal(b.location,agent.me)
            angle = correctAngle(math.degrees(math.atan2(localCoords[1],localCoords[0])))
            _angleDisparity = targetAngle - angle
            _angleDisparity = (_angleDisparity + 180) % 360 - 180
            if b.bigBoost:
                if _angleDisparity > 5:
                    _angleDisparity-=5
                elif _angleDisparity < -5:
                    _angleDisparity +=5

            if abs(_angleDisparity) < clamp(35,0,30*_dist/2000):
                goodBoosts.append(b)


    for each in goodBoosts:
        d = distance2D(each.location,agent.me.location)
        if each.bigBoost:
            d *=.7
        if d < bestDist:
            bestBoost = each
            bestDist = d


    if bestBoost != None and abs(angleDisparity) and (bestDist/spd + distance2D(bestBoost.location,targetVec)/spd < agent.ballDelay):
        if (bestDist/spd) + (distance2D(bestBoost.location,targetVec)/spd) <= agent.ballDelay or ballDist >= 3000:
            return bestBoost.location

    return None 
Example 79
Project: linnea   Author: HPAC   File: utils.py    GNU General Public License v3.0 4 votes vote down vote up
def select_optimal_match(matches):
    """Selects the best match according to the cost function of the kernels.

    Selects the best match from matches according to the cost function. The
    matching kernels have to be equivalent in the sense that the patterns
    (excluding constraints) have to be the same (modulo renaming of variables).
    Lists of matches that fulfill those requirements can be obtained from
    ManyToOneMatcher.match(expr).grouped() (all matches in one group are
    equivalent) or with list(DiscriminationNet.match(expr)) (since
    discrimination nets only work for syntactic patterns, if there are multiple
    matches, all matching patterns have the same structure).

    Furthermore, the constraints of those patterns have to be lists of
    PropertyConstraint objects.

    The best matching kernel is selected in two steps. In the first step,
    the partial ordering on PropertyTuple objects is used to exclude all matches
    that are not minimal in the sense that there is another kernel that requires
    operands to have more specific properties. The underlying assumption is that
    more specialized kernels are expected to be cheaper. After this step, more
    than one kernel might be left because some kernels are not comparable.

    In the next step, the cost function is used to select the cheapest kernel
    among the remaining kernels.

    Args:
        matches (iterable): Iterable of tuples (Kernel, Substitution).

    Returns:
        Kernel: The cheapest matching kernel. If no match was found, it is None.
        Substitution: The corresponding substitution for the kernel. If no match
            was found, it is None.
    """

    matches = list(matches)

    if len(matches) == 1:
        return matches[0]

    optimal_match = (None, None)
    min_cost = math.inf

    # TODO: possible "optimization" if cost function is very expensive:
    # Construct list of candidates first. If there is only one, don't compute
    # cost and return it directly.

    for match in matches:
        if not any(match2[0].property_tuple < match[0].property_tuple for match2 in matches):
            cost = match[0].cost(match[1])
            if cost < min_cost:
                optimal_match = match
                min_cost = cost

    return optimal_match 
Example 80
Project: pose_recovery_evaluation   Author: rbregier   File: evaluation_tools.py    GNU General Public License v3.0 4 votes vote down vote up
def average_precision_recall_curves(pr_curves, return_variance=False):
    """ Estimate macro averaged precision/recall curve based on a list of PR tuples for each score value.
    Assumption: PR curves are indexed by decreasing scores
    Returns a tuple containing the mean precision/recall/score data."""
    n_curves = len(pr_curves)
            
    # Lists indexed over the curves, of list indexed over scores
    precisions = []
    sensitivities = []
    for i in range(n_curves):
        precisions.append([])
        sensitivities.append([])
    scores = []
    current_score = math.inf
    ids = [0] * n_curves    
    while True:
        scores.append(current_score)
        # Greater score among the next ones after the results considered for each scene: it will be the next threshold value
        greatest_score = -math.inf
        for i, (p, r, s) in enumerate(pr_curves):
            # We look for the performances obtained with the last result having a score greater than the current score threshold
            while ids[i] < len(s) and  s[ids[i]] >= current_score:
                ids[i] += 1
            ids[i] -= 1
            cid = ids[i]
            assert(cid >= 0)
            assert(s[cid] >= current_score)                
            precisions[i].append(p[cid])
            sensitivities[i].append(r[cid])
            if not (len(precisions[i]) == len(scores)):
                print("bug")
            if cid + 1 < len(s):
                greatest_score = max(greatest_score, s[cid + 1])
        if greatest_score == -math.inf:
            break
        current_score = greatest_score
    
    # Compute statistical values, for each score
    mean_precisions = np.mean(precisions, axis = 0)
    mean_sensitivities = np.mean(sensitivities, axis = 0)
    if not return_variance:
        return (list(mean_precisions), list(mean_sensitivities))
    else:    
        var_precisions = np.var(precisions, axis = 0)
        var_sensitivities = np.var(sensitivities, axis = 0)
    
        return (list(mean_precisions), 
                list(mean_sensitivities),
                list(scores),
                list(var_precisions),
                list(var_sensitivities))