コード例 #1
0
    def step(self, action: np.ndarray) -> Tuple[np.ndarray, float, bool, Any]:
        """ Take a step from the current state using the specified action. Action is assumed to be in [-1,1] unless
        the environment was created with do_not_normalize = True.
        :param action: The action to take in the current state for sample_time seconds
        :return: A tuple with (next_state, reward, terminal, additional_info)"""
        if self.do_not_normalize:
            action = self.normalize_action(np.array(action))
            assert -1 <= action.all(
            ) <= 1, 'Action was out of the allowed range'
        else:
            action = np.array(action)
            assert -1 <= action.all(
            ) <= 1, 'Actions should be normalized between -1 and 1'
        self._u = self.denormalize_action(action)

        self._step_log_pre()

        with warnings.catch_warnings():
            self._state, self._reward, self._terminal, self._info = self._env.step(
                action)
        self.step_counter += 1

        self._step_log_post(self._reward, self._terminal)

        return self.state, self.reward, self._terminal, self._info
コード例 #2
0
ファイル: day04.py プロジェクト: chaichontat/advent-of-code
def check_bingo2(c: np.ndarray) -> np.ndarray | None:
    u = c.all(axis=1) | c.all(axis=2)
    u = (~u).all(axis=1)
    res = np.argwhere(u)
    if not res.size:
        return None
    return res[0]
コード例 #3
0
def nanall(
    values: np.ndarray,
    axis: Optional[int] = None,
    skipna: bool = True,
    mask: Optional[np.ndarray] = None,
) -> bool:
    """
    Check if all elements along an axis evaluate to True.

    Parameters
    ----------
    values : ndarray
    axis: int, optional
    skipna : bool, default True
    mask : ndarray[bool], optional
        nan-mask if known

    Returns
    -------
    result : bool

    Examples
    --------
    >>> import pandas.core.nanops as nanops
    >>> s = pd.Series([1, 2, np.nan])
    >>> nanops.nanall(s)
    True

    >>> import pandas.core.nanops as nanops
    >>> s = pd.Series([1, 0])
    >>> nanops.nanall(s)
    False
    """
    values, _, _, _, _ = _get_values(values, skipna, fill_value=True, mask=mask)
    return values.all(axis)
コード例 #4
0
ファイル: masked_reductions.py プロジェクト: Aathi410/Pro123
def mean(values: np.ndarray, mask: np.ndarray, skipna: bool = True):
    if not values.size or mask.all():
        return libmissing.NA
    _sum = _sumprod(np.sum, values=values, mask=mask, skipna=skipna)
    count = np.count_nonzero(~mask)
    mean_value = _sum / count
    return mean_value
コード例 #5
0
def uncertainty(preds: np.ndarray) -> float:
     r"""Function used to calculate the fraction of uncertainty of the predicted confidence interval

     Sometimes the nonconformist inductive conformal predictor returns an interval that contains all
     the possile classes. In these cases no information is provided, thus adding uncertainty to the
     prediction. This function returns the fraction of times the interval created has all the classes.

     Parameters
     ----------
     preds: numpy.ndarray
          The confidence interval, represented by a numpy.ndarray of boolean
          values with size (num_samples, num_classes), where num_classes is the total
          number of classes for the data, and num_samples is the number of samples used
          to create the matrix.

     Returns
     -------
     uncertainty: float
          Number of times the interval created contains all the possible classes.

     Notes
     -----
     This fuction can only be used in confidence interval generated for classification
     cases with the nonconformist package.
     """
     return np.mean(preds.all(axis=1))
コード例 #6
0
ファイル: util.py プロジェクト: ahmedmagdiosman/clevr-xai
def srgb2lin(img_arr: np.ndarray) -> np.ndarray:
    """
    Convert from sRGB to Linear RGB.
    Method from reddit of all places
    https://www.reddit.com/r/blender/comments/8moqk6/rgb_node_difference_between_rgb_values/
    Another reference: https://entropymine.com/imageworsener/srgbformula/

    Parameters
    ---
    img_arr (ndarray)
        Input numpy array
    Result
    ---
    np.ndarray
        Converted array

    """

    # convert to [0,1]
    assert img_arr.all() >= 0
    img_arr = img_arr / 255

    cutoff = 0.0404482362771082
    linear_img = np.where(img_arr >= cutoff, ((img_arr + 0.055) / 1.055)**2.4,
                          img_arr / 12.92)

    return linear_img
コード例 #7
0
def pre_edge_fit(
    x: np.ndarray,
    y: np.ndarray,
    pre_feature_min: float,
    pre_feature_max: float,
    post_feature_min: float,
    post_feature_max: float,
):

    if (x.all() and y.all() and pre_feature_min and pre_feature_max
            and post_feature_min and post_feature_max):

        return calculate_pre_edge_fit(x, y, pre_feature_min, pre_feature_max,
                                      post_feature_min, post_feature_max)

    else:
        return x, y, make_zero_array(x)
コード例 #8
0
def verify_validity(similarity_matrix: ndarray):
    """Verifies validity of a tweet in similarity matrix.

    Verifies validity of a tweet in similarity matrix, if it crosses
    the configured threshold for similarity.

    Args:
        similarity_matrix: A list of lists containing similarity scores

    Returns:
        A Boolean representing validity of the tweet.
    """
    if not isinstance(similarity_matrix, ndarray):
        raise TypeError('Similarity matrix must type numpy.ndarray')
    if not similarity_matrix.all():
        raise ValueError('Similarity matrix must be a valid numpy array')
    row = similarity_matrix[0]
    for column_index in range(1, row.shape[0]):
        if row[column_index] > app_config.SIMILARITY_THRESHOLD:
            return (True, column_index, ResultStatus.ALL_OKAY)
    return (False, None, ResultStatus.ALL_OKAY)
コード例 #9
0
def check_game_over(board: np.ndarray,
                    last_action: Optional[PlayerAction] = None,
                    connected_function=CONNECTION) -> bool:
    """
    Return if the board is a terminal state (either player has won, or a draw).
    :param connected_function:
    :param board:
    :param last_action:
    :return:
    """
    if connected_function(board=board, player=PLAYER1,
                          last_action=last_action):
        return True
    elif connected_function(board=board,
                            player=PLAYER2,
                            last_action=last_action):
        return True
    elif board.all():
        return True
    else:
        return False
コード例 #10
0
ファイル: test_utils.py プロジェクト: dylan-profiler/visions
 def f(array: np.ndarray) -> bool:
     result = tester(array)
     return False if result is None else array.all()
コード例 #11
0
def _is_all_freezing(mean_melting_alt: np.ndarray, t0_alt: np.ndarray,
                     height: np.ndarray) -> bool:
    no_detected_melting = mean_melting_alt.all() is ma.masked
    all_temperatures_below_freezing = (t0_alt <= height[0]).all()
    return no_detected_melting and all_temperatures_below_freezing