Python numpy.PINF Examples

The following are 13 code examples for showing how to use numpy.PINF(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: prpy   Author: personalrobotics   File: util.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ComputeEnabledAABB(kinbody):
    """
    Returns the AABB of the enabled links of a KinBody.

    @param kinbody: an OpenRAVE KinBody
    @returns: AABB of the enabled links of the KinBody
    """
    from numpy import NINF, PINF
    from openravepy import AABB

    min_corner = numpy.array([PINF] * 3)
    max_corner = numpy.array([NINF] * 3)

    for link in kinbody.GetLinks():
        if link.IsEnabled():
            link_aabb = link.ComputeAABB()
            center = link_aabb.pos()
            half_extents = link_aabb.extents()
            min_corner = numpy.minimum(center - half_extents, min_corner)
            max_corner = numpy.maximum(center + half_extents, max_corner)

    center = (min_corner + max_corner) / 2.
    half_extents = (max_corner - min_corner) / 2.
    return AABB(center, half_extents) 
Example 2
Project: chainer   Author: chainer   File: test_constants.py    License: MIT License 6 votes vote down vote up
def test_constants():
    assert chainerx.Inf is numpy.Inf
    assert chainerx.Infinity is numpy.Infinity
    assert chainerx.NAN is numpy.NAN
    assert chainerx.NINF is numpy.NINF
    assert chainerx.NZERO is numpy.NZERO
    assert chainerx.NaN is numpy.NaN
    assert chainerx.PINF is numpy.PINF
    assert chainerx.PZERO is numpy.PZERO
    assert chainerx.e is numpy.e
    assert chainerx.euler_gamma is numpy.euler_gamma
    assert chainerx.inf is numpy.inf
    assert chainerx.infty is numpy.infty
    assert chainerx.nan is numpy.nan
    assert chainerx.newaxis is numpy.newaxis
    assert chainerx.pi is numpy.pi 
Example 3
Project: revscoring   Author: wikimedia   File: util.py    License: MIT License 6 votes vote down vote up
def normalize(v):
    if isinstance(v, numpy.bool_):
        return bool(v)
    elif isinstance(v, numpy.ndarray):
        return [normalize(item) for item in v]
    elif v == numpy.NaN:
        return "NaN"
    elif v == numpy.NINF:
        return "-Infinity"
    elif v == numpy.PINF:
        return "Infinity"
    elif isinstance(v, numpy.float):
        return float(v)
    elif isinstance(v, tuple):
        return list(v)
    else:
        return v 
Example 4
Project: emukit   Author: amzn   File: continuous_fidelity_entropy_search.py    License: Apache License 2.0 6 votes vote down vote up
def _get_proposal_function(self, model, space):

        # Define proposal function for multi-fidelity
        ei = ExpectedImprovement(model)

        def proposal_func(x):
            x_ = x[None, :]
            # Map to highest fidelity
            idx = np.ones((x_.shape[0], 1)) * self.high_fidelity

            x_ = np.insert(x_, self.target_fidelity_index, idx, axis=1)

            if space.check_points_in_domain(x_):
                val = np.log(np.clip(ei.evaluate(x_)[0], 0., np.PINF))
                if np.any(np.isnan(val)):
                    return np.array([np.NINF])
                else:
                    return val
            else:
                return np.array([np.NINF])

        return proposal_func 
Example 5
Project: emukit   Author: amzn   File: entropy_search.py    License: Apache License 2.0 6 votes vote down vote up
def _get_proposal_function(self, model, space):

        # Define proposal function for multi-fidelity
        ei = ExpectedImprovement(model)

        def proposal_func(x):
            x_ = x[None, :]

            # Add information source parameter into array
            idx = np.ones((x_.shape[0], 1)) * self.target_information_source_index
            x_ = np.insert(x_, self.source_idx, idx, axis=1)

            if space.check_points_in_domain(x_):
                val = np.log(np.clip(ei.evaluate(x_)[0], 0., np.PINF))
                if np.any(np.isnan(val)):
                    return np.array([np.NINF])
                else:
                    return val
            else:
                return np.array([np.NINF])

        return proposal_func 
Example 6
Project: sharpy   Author: ImperialCollegeLondon   File: optimiser.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_ground_clearance(data):
    """
    Extracts the minimum value of for_pos[2] and returns that value and the
    timestep it happened at.
    """
    structure = data.structure
    min_clear = np.PINF
    ts_min_clear = None
    for ts, tstep in enumerate(structure.timestep_info):
        try:
            tstep.mb_dict['constraint_00']
            continue
        except KeyError:
            pass
        if tstep.for_pos[2] < min_clear:
            min_clear = tstep.for_pos[2]
            ts_min_clear = ts
    return min_clear, ts_min_clear 
Example 7
Project: Computable   Author: ktraunmueller   File: anneal.py    License: MIT License 5 votes vote down vote up
def init(self, **options):
        self.__dict__.update(options)
        self.lower = asarray(self.lower)
        self.lower = where(self.lower == numpy.NINF, -_double_max, self.lower)
        self.upper = asarray(self.upper)
        self.upper = where(self.upper == numpy.PINF, _double_max, self.upper)
        self.k = 0
        self.accepted = 0
        self.feval = 0
        self.tests = 0 
Example 8
Project: hover_net   Author: vqdang   File: augs.py    License: MIT License 5 votes vote down vote up
def _get_weight_map(self, ann, inst_list):
        if len(inst_list) <= 1: # 1 instance only
            return np.zeros(ann.shape[:2])
        stacked_inst_bgd_dst = np.zeros(ann.shape[:2] +(len(inst_list),))

        for idx, inst_id in enumerate(inst_list):
            inst_bgd_map = np.array(ann != inst_id , np.uint8)
            inst_bgd_dst = distance_transform_edt(inst_bgd_map)
            stacked_inst_bgd_dst[...,idx] = inst_bgd_dst

        near1_dst = np.amin(stacked_inst_bgd_dst, axis=2)
        near2_dst = np.expand_dims(near1_dst ,axis=2)
        near2_dst = stacked_inst_bgd_dst - near2_dst
        near2_dst[near2_dst == 0] = np.PINF # very large
        near2_dst = np.amin(near2_dst, axis=2)
        near2_dst[ann > 0] = 0 # the instances
        near2_dst = near2_dst + near1_dst
        # to fix pixel where near1 == near2
        near2_eve = np.expand_dims(near1_dst ,axis=2)
        # to avoide the warning of a / 0
        near2_eve = (1.0 + stacked_inst_bgd_dst) / (1.0 + near2_eve)
        near2_eve[near2_eve != 1] = 0
        near2_eve = np.sum(near2_eve, axis=2)
        near2_dst[near2_eve > 1] = near1_dst[near2_eve > 1]
        #
        pix_dst = near1_dst + near2_dst
        pen_map = pix_dst / self.sigma
        pen_map = self.w0 * np.exp(- pen_map**2 / 2)
        pen_map[ann > 0] = 0 # inner instances zero
        return pen_map 
Example 9
Project: revscoring   Author: wikimedia   File: test_util.py    License: MIT License 5 votes vote down vote up
def test_normalize_json():
    doc = {"foo": {numpy.bool_(True): "value"},
           "what": numpy.bool_(False),
           "this": numpy.PINF}
    normalized_doc = normalize_json(doc)
    assert isinstance(normalized_doc['what'], bool)
    assert isinstance(list(normalized_doc['foo'].keys())[0], bool)
    assert normalized_doc['this'] == "Infinity" 
Example 10
Project: fairlearn   Author: fairlearn   File: _lagrangian.py    License: MIT License 5 votes vote down vote up
def best_h(self, lambda_vec):
        """Solve the best-response problem.

        Returns the classifier that solves the best-response problem for
        the vector of Lagrange multipliers `lambda_vec`.
        """
        classifier = self._call_oracle(lambda_vec)
        def h(X): return classifier.predict(X)
        h_error = self.obj.gamma(h)[0]
        h_gamma = self.constraints.gamma(h)
        h_value = h_error + h_gamma.dot(lambda_vec)

        if not self.hs.empty:
            values = self.errors + self.gammas.transpose().dot(lambda_vec)
            best_idx = values.idxmin()
            best_value = values[best_idx]
        else:
            best_idx = -1
            best_value = np.PINF

        if h_value < best_value - _PRECISION:
            logger.debug("%sbest_h: val improvement %f", _LINE, best_value - h_value)
            h_idx = len(self.hs)
            self.hs.at[h_idx] = h
            self.predictors.at[h_idx] = classifier
            self.errors.at[h_idx] = h_error
            self.gammas[h_idx] = h_gamma
            self.lambdas[h_idx] = lambda_vec.copy()
            best_idx = h_idx

        return self.hs[best_idx], best_idx 
Example 11
Project: schema-games   Author: vicariousinc   File: objects.py    License: MIT License 5 votes vote down vote up
def __init__(self,
                 position,
                 nzis=None,
                 shape=None,
                 hitpoints=np.PINF,
                 is_entity=True,
                 color=(128, 128, 128),
                 visible=True,
                 indirect_collision_effects=True):

        self._position = np.array(position)
        self.hitpoints = hitpoints
        self.is_entity = is_entity
        self.color = color
        self.visible = visible
        self.is_rectangular = True
        self.indirect_collision_effects = indirect_collision_effects

        assert self.hitpoints > 0
        assert ((nzis is None and shape is not None) or
                (nzis is not None and shape is None))

        # Set non-zero indices of the object mask's
        if nzis is None:
            self._nzis = shape_to_nzis(shape)
        else:
            self._nzis = np.array(nzis)

        if is_entity:
            self.entity_id = BreakoutObject.unique_entity_id
            BreakoutObject.unique_entity_id += MAX_NZIS_PER_ENTITY
            assert len(self._nzis) <= MAX_NZIS_PER_ENTITY
        else:
            self.entity_id = None

        self.object_id = BreakoutObject.unique_object_id
        BreakoutObject.unique_object_id += 1
        BreakoutObject.register_color(self.color)

        # Sets up slots for memoization
        self.reset_cache() 
Example 12
Project: schema-games   Author: vicariousinc   File: play.py    License: MIT License 5 votes vote down vote up
def play_game(environment_class,
              cheat_mode=DEFAULT_CHEAT_MODE,
              debug=DEFAULT_DEBUG,
              fps=30):
    """
    Interactively play an environment.

    Parameters
    ----------
    environment_class : type
        A subclass of schema_games.breakout.core.BreakoutEngine that represents
        a game. A convenient list is included in schema_games.breakout.games.
    cheat_mode : bool
        If True, player has an infinite amount of lives.
    debug : bool
        If True, print debugging messages and perform additional sanity checks.
    fps : int
        Frame rate per second at which to display the game.
    """
    print blue("-" * 80)
    print blue("Starting interactive game. "
               "Press <ESC> at any moment to terminate.")
    print blue("-" * 80)

    env_args = {
        'return_state_as_image': True,
        'debugging': debug,
    }

    if cheat_mode:
        env_args['num_lives'] = np.PINF

    env = environment_class(**env_args)
    keys_to_action = defaultdict(lambda: env.NOOP, {
            (pygame.K_LEFT,): env.LEFT,
            (pygame.K_RIGHT,): env.RIGHT,
        })

    play(env, fps=fps, keys_to_action=keys_to_action, zoom=ZOOM_FACTOR) 
Example 13
Project: prpy   Author: personalrobotics   File: vectorfield.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def PlanToEndEffectorPose(self, robot, goal_pose, timelimit=5.0,
                              pose_error_tol=0.01,
                              integration_interval=10.0,
                              **kw_args):
        """
        Plan to an end effector pose by following a geodesic loss function
        in SE(3) via an optimized Jacobian.

        @param robot
        @param goal_pose desired end-effector pose
        @param timelimit time limit before giving up
        @param pose_error_tol in meters
        @param integration_interval The time interval to integrate over
        @return traj
        """
        manip = robot.GetActiveManipulator()

        def vf_geodesic():
            """
            Define a joint-space vector field, that moves along the
            geodesic (shortest path) from the start pose to the goal pose.
            """
            twist = util.GeodesicTwist(manip.GetEndEffectorTransform(),
                                       goal_pose)
            dqout, tout = util.ComputeJointVelocityFromTwist(
                robot, twist, joint_velocity_limits=numpy.PINF)

            # Go as fast as possible
            vlimits = robot.GetDOFVelocityLimits(robot.GetActiveDOFIndices())
            return min(abs(vlimits[i] / dqout[i])
                       if dqout[i] != 0. else 1.
                       for i in xrange(vlimits.shape[0])) * dqout

        def CloseEnough():
            """
            The termination condition.
            At each integration step, the geodesic error between the
            start and goal poses is compared. If within threshold,
            the integration will terminate.
            """
            pose_error = util.GetGeodesicDistanceBetweenTransforms(
                manip.GetEndEffectorTransform(), goal_pose)
            if pose_error < pose_error_tol:
                return Status.TERMINATE
            return Status.CONTINUE

        traj = self.FollowVectorField(robot, vf_geodesic, CloseEnough,
                                      integration_interval,
                                      timelimit,
                                      **kw_args)

        # Flag this trajectory as unconstrained. This overwrites the
        # constrained flag set by FollowVectorField.
        util.SetTrajectoryTags(traj, {Tags.CONSTRAINED: False}, append=True)
        return traj