Python numpy.isfinite() Examples

The following are 30 code examples for showing how to use numpy.isfinite(). 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: aospy   Author: spencerahill   File: test_data_loader.py    License: Apache License 2.0 6 votes vote down vote up
def test_load_variable_mask_and_scale(load_variable_data_loader):
    def convert_all_to_missing_val(ds, **kwargs):
        ds['condensation_rain'] = 0. * ds['condensation_rain'] + 1.0e20
        ds['condensation_rain'].attrs['_FillValue'] = 1.0e20
        return ds

    load_variable_data_loader.preprocess_func = convert_all_to_missing_val

    data = load_variable_data_loader.load_variable(
        condensation_rain, DatetimeNoLeap(5, 1, 1),
        DatetimeNoLeap(5, 12, 31),
        intvl_in='monthly')

    num_non_missing = np.isfinite(data).sum().item()
    expected_num_non_missing = 0
    assert num_non_missing == expected_num_non_missing 
Example 2
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _convert_observ(self, observ):
    """Convert the observation to 32 bits.

    Args:
      observ: Numpy observation.

    Raises:
      ValueError: Observation contains infinite values.

    Returns:
      Numpy observation with 32-bit data type.
    """
    if not np.isfinite(observ).all():
      raise ValueError('Infinite observation encountered.')
    if observ.dtype == np.float64:
      return observ.astype(np.float32)
    if observ.dtype == np.int64:
      return observ.astype(np.int32)
    return observ 
Example 3
Project: soccer-matlab   Author: utra-robosoccer   File: robot_pendula.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_state(self):
		self.theta, theta_dot = self.j1.current_position()
		x, vx = self.slider.current_position()
		assert( np.isfinite(x) )

		if not np.isfinite(x):
			print("x is inf")
			x = 0

		if not np.isfinite(vx):
			print("vx is inf")
			vx = 0

		if not np.isfinite(self.theta):
			print("theta is inf")
			self.theta = 0

		if not np.isfinite(theta_dot):
			print("theta_dot is inf")
			theta_dot = 0

		return np.array([
			x, vx,
			np.cos(self.theta), np.sin(self.theta), theta_dot
			]) 
Example 4
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _convert_observ(self, observ):
    """Convert the observation to 32 bits.

    Args:
      observ: Numpy observation.

    Raises:
      ValueError: Observation contains infinite values.

    Returns:
      Numpy observation with 32-bit data type.
    """
    if not np.isfinite(observ).all():
      raise ValueError('Infinite observation encountered.')
    if observ.dtype == np.float64:
      return observ.astype(np.float32)
    if observ.dtype == np.int64:
      return observ.astype(np.int32)
    return observ 
Example 5
Project: pymoo   Author: msu-coinlab   File: so_sqlp.py    License: Apache License 2.0 6 votes vote down vote up
def _initialize(self):
        super()._initialize()

        # Clip initial guess to bounds (SLSQP may fail with bounds-infeasible initial point)
        x = asfarray(self.x0.X.flatten())
        xl, xu = self.problem.bounds()
        have_bound = np.isfinite(xl)
        x[have_bound] = np.clip(x[have_bound], xl[have_bound], np.inf)
        have_bound = np.isfinite(xu)
        x[have_bound] = np.clip(x[have_bound], -np.inf, xu[have_bound])
        self.D["X"] = x

        self.pop = Population()
        self._eval_obj()
        self._eval_grad()
        self._update()
        self._call()

        self.major = True 
Example 6
Project: risk-slim   Author: ustunb   File: coefficient_set.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _check_rep(self):

        #name
        assert isinstance(self._name, str)
        assert len(self._name) >= 1

        #bounds
        assert np.isfinite(self.ub)
        assert np.isfinite(self.lb)
        assert self.ub >= self.lb

        # value
        assert self._vtype in self._VALID_TYPES
        assert np.isnan(self.c0) or (self.c0 >= 0.0 and np.isfinite(self.c0))

        return True 
Example 7
Project: me-ica   Author: ME-ICA   File: casting.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def _check_maxexp(np_type, maxexp):
    """ True if fp type `np_type` seems to have `maxexp` maximum exponent

    We're testing "maxexp" as returned by numpy. This value is set to one
    greater than the maximum power of 2 that `np_type` can represent.

    Assumes base 2 representation.  Very crude check

    Parameters
    ----------
    np_type : numpy type specifier
        Any specifier for a numpy dtype
    maxexp : int
        Maximum exponent to test against

    Returns
    -------
    tf : bool
        True if `maxexp` is the correct maximum exponent, False otherwise.
    """
    dt = np.dtype(np_type)
    np_type = dt.type
    two = np_type(2).reshape((1,)) # to avoid upcasting
    return (np.isfinite(two ** (maxexp - 1)) and
            not np.isfinite(two ** maxexp)) 
Example 8
Project: NTFLib   Author: stitchfix   File: utils.py    License: MIT License 6 votes vote down vote up
def beta_divergence(x_indices, x_vals, beta, A, B, C):
    """Computes the total beta-divergence between the current model and
    a sparse X
    """
    rank = len(x_indices[0])
    b_vals = np.zeros(x_vals.shape, dtype=np.float32)
    parafac_sparse(x_indices, b_vals, A, B, C)
    a, b = x_vals, b_vals
    idx = np.isfinite(a)
    idx &= np.isfinite(b)
    idx &= a > 0
    idx &= b > 0
    a = a[idx]
    b = b[idx]
    if beta == 0:
        return a / b - np.log(a / b) - 1
    if beta == 1:
        return a * (np.log(a) - np.log(b)) + b - a
    return (1. / beta / (beta - 1.) * (a ** beta + (beta - 1.)
            * b ** beta - beta * a * b ** (beta - 1))) 
Example 9
Project: PoseWarper   Author: facebookresearch   File: mot.py    License: Apache License 2.0 6 votes vote down vote up
def _sanitize_dists(self, dists):
        """Replace invalid distances."""
        
        dists = np.copy(dists)
        
        # Note there is an issue in scipy.optimize.linear_sum_assignment where
        # it runs forever if an entire row/column is infinite or nan. We therefore
        # make a copy of the distance matrix and compute a safe value that indicates
        # 'cannot assign'. Also note + 1 is necessary in below inv-dist computation
        # to make invdist bigger than max dist in case max dist is zero.
        
        valid_dists = dists[np.isfinite(dists)]
        INVDIST = 2 * valid_dists.max() + 1 if valid_dists.shape[0] > 0 else 1.
        dists[~np.isfinite(dists)] = INVDIST  

        return dists, INVDIST 
Example 10
Project: RLTrader   Author: notadamking   File: TradingEnv.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _reward(self):
        reward = self.reward_strategy.get_reward(current_step=self.current_step,
                                                 current_price=self._current_price,
                                                 observations=self.observations,
                                                 account_history=self.account_history,
                                                 net_worths=self.net_worths)

        reward = float(reward) if np.isfinite(float(reward)) else 0

        self.rewards.append(reward)

        if self.stationarize_rewards:
            rewards = difference(self.rewards, inplace=False)
        else:
            rewards = self.rewards

        if self.normalize_rewards:
            mean_normalize(rewards, inplace=True)

        rewards = np.array(rewards).flatten()

        return float(rewards[-1]) 
Example 11
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 6 votes vote down vote up
def test_generic(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            vals = nan_to_num(np.array((-1., 0, 1))/0.)
        assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
        assert_(vals[1] == 0)
        assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
        assert_equal(type(vals), np.ndarray)

        # perform the same test but in-place
        with np.errstate(divide='ignore', invalid='ignore'):
            vals = np.array((-1., 0, 1))/0.
        result = nan_to_num(vals, copy=False)

        assert_(result is vals)
        assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
        assert_(vals[1] == 0)
        assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
        assert_equal(type(vals), np.ndarray) 
Example 12
Project: aospy   Author: spencerahill   File: region.py    License: Apache License 2.0 5 votes vote down vote up
def ts(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR,
           land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR):
        """Create yearly time-series of region-averaged data.

        Parameters
        ----------
        data : xarray.DataArray
            The array to create the regional timeseries of
        lon_cyclic : { None, True, False }, optional (default True)
            Whether or not the longitudes of ``data`` span the whole globe,
            meaning that they should be wrapped around as necessary to cover
            the Region's full width.
        lat_str, lon_str, land_mask_str, sfc_area_str : str, optional
            The name of the latitude, longitude, land mask, and surface area
            coordinates, respectively, in ``data``.  Defaults are the
            corresponding values in ``aospy.internal_names``.

        Returns
        -------
        xarray.DataArray
            The timeseries of values averaged within the region and within each
            year, one value per year.

        """
        data_masked = self.mask_var(data, lon_cyclic=lon_cyclic,
                                    lon_str=lon_str, lat_str=lat_str)
        sfc_area = data[sfc_area_str]
        sfc_area_masked = self.mask_var(sfc_area, lon_cyclic=lon_cyclic,
                                        lon_str=lon_str, lat_str=lat_str)
        land_mask = _get_land_mask(data, self.do_land_mask,
                                   land_mask_str=land_mask_str)
        weights = sfc_area_masked * land_mask
        # Mask weights where data values are initially invalid in addition
        # to applying the region mask.
        weights = weights.where(np.isfinite(data))
        weights_reg_sum = weights.sum(lon_str).sum(lat_str)
        data_reg_sum = (data_masked * sfc_area_masked *
                        land_mask).sum(lat_str).sum(lon_str)
        return data_reg_sum / weights_reg_sum 
Example 13
Project: aospy   Author: spencerahill   File: times.py    License: Apache License 2.0 5 votes vote down vote up
def yearly_average(arr, dt):
    """Average a sub-yearly time-series over each year.

    Resulting timeseries comprises one value for each year in which the
    original array had valid data.  Accounts for (i.e. ignores) masked values
    in original data when computing the annual averages.

    Parameters
    ----------
    arr : xarray.DataArray
        The array to be averaged
    dt : xarray.DataArray
        Array of the duration of each timestep

    Returns
    -------
    xarray.DataArray
        Has the same shape and mask as the original ``arr``, except for the
        time dimension, which is truncated to one value for each year that
        ``arr`` spanned

    """
    assert_matching_time_coord(arr, dt)
    yr_str = TIME_STR + '.year'
    # Retain original data's mask.
    dt = dt.where(np.isfinite(arr))
    return ((arr*dt).groupby(yr_str, restore_coord_dims=True).sum(TIME_STR) /
            dt.groupby(yr_str, restore_coord_dims=True).sum(TIME_STR)) 
Example 14
Project: dustmaps   Author: gregreen   File: marshall.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, map_fname=None):
        """
        Args:
            map_fname (Optional[:obj:`str`]): Filename at which the map is stored.
                Defaults to ``None``, meaning that the default filename is used.
        """
        if map_fname is None:
            map_fname = os.path.join(data_dir(), 'marshall', 'marshall.h5')

        with h5py.File(map_fname, 'r') as f:
            self._l = f['l'][:]
            self._b = f['b'][:]
            self._A = f['A'][:]
            self._sigma_A = f['sigma_A'][:]
            self._dist = f['dist'][:]
            self._sigma_dist = f['sigma_dist'][:]

        # self._l.shape = (self._l.size,)
        # self._b.shape = (self._b.size,)
        # self._A.shape = (self._A.shape[0], self._A.shape[1]*self._A.shape[2])

        # Shape of the (l,b)-grid
        self._shape = self._l.shape

        # Number of distance bins in each sightline
        self._n_dists = np.sum(np.isfinite(self._dist), axis=2)

        # idx = ~np.isfinite(self._dist)
        # if np.any(idx):
        #     self._dist[idx] = np.inf

        self._l_bounds = (-100., 100.) # min,max Galactic longitude, in deg
        self._b_bounds = (-10., 10.)    # min,max Galactic latitude, in deg
        self._inv_pix_scale = 4.        # 1 / (pixel scale, in deg) 
Example 15
Project: neuropythy   Author: noahbenson   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def segment_intersection_2D(p12arg, p34arg, atol=1e-8):
    '''
    segment_intersection((a, b), (c, d)) yields the intersection point between the line segments
    that pass from point a to point b and from point c to point d. If there is no intersection
    point, then (numpy.nan, numpy.nan) is returned.
    '''
    (p1,p2) = p12arg
    (p3,p4) = p34arg
    pi = np.asarray(line_intersection_2D(p12arg, p34arg, atol=atol))
    p1 = np.asarray(p1)
    p2 = np.asarray(p2)
    p3 = np.asarray(p3)
    p4 = np.asarray(p4)
    u12 = p2 - p1
    u34 = p4 - p3
    cfn = lambda px,iis: (px if iis is None or len(px.shape) == 1 or px.shape[1] == len(iis) else
                          px[:,iis])
    dfn = lambda a,b:     a[0]*b[0] + a[1]*b[1]
    sfn = lambda a,b:     ((a-b)                 if len(a.shape) == len(b.shape) else
                           (np.transpose([a])-b) if len(a.shape) <  len(b.shape) else
                           (a - np.transpose([b])))
    fn  = lambda px,iis:  (1 - ((dfn(cfn(u12,iis), sfn(         px, cfn(p1,iis))) > 0) *
                                (dfn(cfn(u34,iis), sfn(         px, cfn(p3,iis))) > 0) *
                                (dfn(cfn(u12,iis), sfn(cfn(p2,iis),          px)) > 0) *
                                (dfn(cfn(u34,iis), sfn(cfn(p4,iis),          px)) > 0)))
    if len(pi.shape) == 1:
        if not np.isfinite(pi[0]): return (np.nan, np.nan)
        bad = fn(pi, None)
        return (np.nan, np.nan) if bad else pi
    else:
        nonpar = np.where(np.isfinite(pi[0]))[0]
        bad = fn(cfn(pi, nonpar), nonpar)
        (xi,yi) = pi
        bad = nonpar[np.where(bad)[0]]
        xi[bad] = np.nan
        yi[bad] = np.nan
        return (xi,yi) 
Example 16
Project: neuropythy   Author: noahbenson   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def lines_touch_2D(ab, cd, atol=1e-8):
    '''
    lines_touch_2D((a,b), (c,d)) is equivalent to lines_colinear((a,b), (c,d)) |
    numpy.isfinite(line_intersection_2D((a,b), (c,d))[0])
    '''
    return (lines_colinear(ab, cd, atol=atol) |
            np.isfinite(line_intersection_2D(ab, cd, atol=atol)[0])) 
Example 17
Project: neuropythy   Author: noahbenson   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def segments_touch_2D(ab, cd, atol=1e-8):
    '''
    segmentss_touch_2D((a,b), (c,d)) is equivalent to segments_colinear((a,b), (c,d)) |
    numpy.isfinite(segment_intersection_2D((a,b), (c,d))[0])
    '''
    return (segments_colinear(ab, cd, atol=atol) |
            np.isfinite(segment_intersection_2D(ab, cd, atol=atol)[0])) 
Example 18
Project: neuropythy   Author: noahbenson   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def line_segment_intersection_2D(p12arg, p34arg, atol=1e-8):
    '''
    line_segment_intersection((a, b), (c, d)) yields the intersection point between the line
    passing through points a and b and the line segment that passes from point c to point d. If
    there is no intersection point, then (numpy.nan, numpy.nan) is returned.
    '''
    (p1,p2) = p12arg
    (p3,p4) = p34arg
    pi = np.asarray(line_intersection_2D(p12arg, p34arg, atol=atol))
    p3 = np.asarray(p3)
    u34 = p4 - p3
    cfn = lambda px,iis: (px if iis is None or len(px.shape) == 1 or px.shape[1] == len(iis) else
                          px[:,iis])
    dfn = lambda a,b:     a[0]*b[0] + a[1]*b[1]
    sfn = lambda a,b:     ((a-b)                 if len(a.shape) == len(b.shape) else
                           (np.transpose([a])-b) if len(a.shape) <  len(b.shape) else
                           (a - np.transpose([b])))
    fn  = lambda px,iis:  (1 - ((dfn(cfn(u34,iis), sfn(         px, cfn(p3,iis))) > 0) *
                                (dfn(cfn(u34,iis), sfn(cfn(p4,iis),          px)) > 0)))
    if len(pi.shape) == 1:
        if not np.isfinite(pi[0]): return (np.nan, np.nan)
        bad = fn(pi, None)
        return (np.nan, np.nan) if bad else pi
    else:
        nonpar = np.where(np.isfinite(pi[0]))[0]
        bad = fn(cfn(pi, nonpar), nonpar)
        (xi,yi) = pi
        bad = nonpar[np.where(bad)[0]]
        xi[bad] = np.nan
        yi[bad] = np.nan
        return (xi,yi) 
Example 19
Project: neuropythy   Author: noahbenson   File: retinotopy.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _retinotopy_vectors_to_float(ang, ecc, wgt, weight_min=0):
    ok = np.isfinite(wgt) & np.isfinite(ecc) & np.isfinite(ang)
    ok[ok] &= wgt[ok] > weight_min
    bad = np.logical_not(ok)
    if np.sum(bad) > 0:
        wgt = np.array(wgt)
        wgt[bad] = 0
    return (ang, ecc, wgt) 
Example 20
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def nanlog(x, null=np.nan):
    '''
    nanlog(x) is equivalent to numpy.log(x) except that it avoids calling log on 0 and non-finie
      values; in place of these values, it returns the value null (which is nan by default).
    '''
    x = np.asarray(x)
    ii0 = np.where(np.isfinite(x))
    ii  = np.where(x[ii0] > 0)[0]
    if len(ii) == numel(x): return np.log(x)
    res = np.full(x.shape, null)
    ii = tuple([u[ii] for u in ii0])
    res[ii] = np.log(x[ii])
    return res 
Example 21
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def curve_intersection(c1, c2, grid=16):
    '''
    curve_intersect(c1, c2) yields the parametric distances (t1, t2) such that c1(t1) == c2(t2).
      
    The optional parameter grid may specify the number of grid-points
    to use in the initial search for a start-point (default: 16).
    '''
    from scipy.optimize import minimize
    from neuropythy.geometry import segment_intersection_2D
    if c1.coordinates.shape[1] > c2.coordinates.shape[1]:
        (t1,t2) = curve_intersection(c2, c1, grid=grid)
        return (t2,t1)
    # before doing a search, see if there are literal exact intersections of the segments
    x1s  = c1.coordinates.T
    x2s  = c2.coordinates
    for (ts,te,xs,xe) in zip(c1.t[:-1], c1.t[1:], x1s[:-1], x1s[1:]):
        pts = segment_intersection_2D((xs,xe), (x2s[:,:-1], x2s[:,1:]))
        ii = np.where(np.isfinite(pts[0]))[0]
        if len(ii) > 0:
            ii = ii[0]
            def f(t): return np.sum((c1(t[0]) - c2(t[1]))**2)
            t01 = 0.5*(ts + te)
            t02 = 0.5*(c2.t[ii] + c2.t[ii+1])
            (t1,t2) = minimize(f, (t01, t02)).x
            return (t1,t2)
    if pimms.is_vector(grid): (ts1,ts2) = [c.t[0] + (c.t[-1] - c.t[0])*grid for c in (c1,c2)]
    else:                     (ts1,ts2) = [np.linspace(c.t[0], c.t[-1], grid) for c in (c1,c2)]
    (pts1,pts2) = [c(ts) for (c,ts) in zip([c1,c2],[ts1,ts2])]
    ds = np.sqrt([np.sum((pts2.T - pp)**2, axis=1) for pp in pts1.T])
    (ii,jj) = np.unravel_index(np.argmin(ds), ds.shape)
    (t01,t02) = (ts1[ii], ts2[jj])
    ttt = []
    def f(t): return np.sum((c1(t[0]) - c2(t[1]))**2)
    (t1,t2) = minimize(f, (t01, t02)).x
    return (t1,t2) 
Example 22
Project: neuropythy   Author: noahbenson   File: __init__.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mesh(self):
        '''
        test_mesh() ensures that many general mesh properties and methods are working.
        '''
        import neuropythy.geometry as geo
        logging.info('neuropythy: Testing meshes and properties...')
        # get a random subject's mesh
        sub  = ny.data['benson_winawer_2018'].subjects['S1204']
        hem  = sub.hemis[('lh','rh')[np.random.randint(2)]]
        msh  = hem.white_surface
        # few simple things
        self.assertEqual(msh.coordinates.shape[0], 3)
        self.assertEqual(msh.tess.faces.shape[0], 3)
        self.assertEqual(msh.tess.edges.shape[0], 2)
        self.assertEqual(msh.vertex_count, msh.coordinates.shape[1])
        # face areas and edge lengths should all be non-negative
        self.assertGreaterEqual(np.min(msh.face_areas), 0)
        self.assertGreaterEqual(np.min(msh.edge_lengths), 0)
        # test the properties
        self.assertTrue('blerg' in msh.with_prop(blerg=msh.prop('curvature')).properties)
        self.assertFalse('curvature' in msh.wout_prop('curvature').properties)
        self.assertEqual(msh.properties.row_count, msh.vertex_count)
        self.assertLessEqual(np.abs(np.mean(msh.prop('curvature'))), 0.1)
        # use the property interface to grab a fancy masked property
        v123_areas = msh.property('midgray_surface_area',
                                  mask=('inf-prf_visual_area', (1,2,3)),
                                  null=0)
        v123_area = np.sum(v123_areas)
        self.assertLessEqual(v123_area, 15000)
        self.assertGreaterEqual(v123_area, 500)
        (v1_ecc, v1_rad) = msh.property(['prf_eccentricity','prf_radius'],
                                        mask=('inf-prf_visual_area', 1),
                                        weights='prf_variance_explained',
                                        weight_min=0.1,
                                        clipped=0,
                                        null=np.nan)
        wh = np.isfinite(v1_ecc) & np.isfinite(v1_rad)
        self.assertGreater(np.corrcoef(v1_ecc[wh], v1_rad[wh])[0,0], 0.5) 
Example 23
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def clip_global_norm(arrays, max_norm, check_isfinite=True):
    """Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`.

    Parameters
    ----------
    arrays : list of NDArray
    max_norm : float
    check_isfinite : bool, default True
         If True, check that the total_norm is finite (not nan or inf). This
         requires a blocking .asscalar() call.

    Returns
    -------
    NDArray or float
      Total norm. Return type is NDArray of shape (1,) if check_isfinite is
      False. Otherwise a float is returned.

    """
    def _norm(array):
        if array.stype == 'default':
            x = array.reshape((-1,))
            return ndarray.dot(x, x)
        return array.norm().square()
    assert len(arrays) > 0
    ctx = arrays[0].context
    total_norm = ndarray.add_n(*[_norm(arr).as_in_context(ctx) for arr in arrays])
    total_norm = ndarray.sqrt(total_norm)
    if check_isfinite:
        if not np.isfinite(total_norm.asscalar()):
            warnings.warn(
                UserWarning('nan or inf is detected. '
                            'Clipping results will be undefined.'), stacklevel=2)
    scale = max_norm / (total_norm + 1e-8)
    scale = ndarray.min(ndarray.concat(scale, ndarray.ones(1, ctx=ctx), dim=0))
    for arr in arrays:
        arr *= scale.as_in_context(arr.context)
    if check_isfinite:
        return total_norm.asscalar()
    else:
        return total_norm 
Example 24
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _is_finite(self, space):
    return np.isfinite(space.low).all() and np.isfinite(space.high).all() 
Example 25
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _convert_reward(self, reward):
    """Convert the reward to 32 bits.

    Args:
      reward: Numpy reward.

    Raises:
      ValueError: Rewards contain infinite values.

    Returns:
      Numpy reward with 32-bit data type.
    """
    if not np.isfinite(reward).all():
      raise ValueError('Infinite reward encountered.')
    return np.array(reward, dtype=np.float32) 
Example 26
Project: soccer-matlab   Author: utra-robosoccer   File: robot_locomotors.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def apply_action(self, a):
		assert (np.isfinite(a).all())
		for n, j in enumerate(self.ordered_joints):
			j.set_motor_torque(self.power * j.power_coef * float(np.clip(a[n], -1, +1))) 
Example 27
Project: soccer-matlab   Author: utra-robosoccer   File: robot_locomotors.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def apply_action(self, a):
		assert( np.isfinite(a).all() )
		force_gain = 1
		for i, m, power in zip(range(17), self.motors, self.motor_power):
			m.set_motor_torque(float(force_gain * power * self.power * np.clip(a[i], -1, +1))) 
Example 28
Project: soccer-matlab   Author: utra-robosoccer   File: robot_manipulators.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def apply_action(self, a):
		assert (np.isfinite(a).all())
		self.shoulder_pan_joint.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))
		self.shoulder_lift_joint.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))
		self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))
		self.elbow_flex_joint.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1)))
		self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[4], -1, +1)))
		self.wrist_flex_joint.set_motor_torque(0.05 * float(np.clip(a[5], -1, +1)))
		self.wrist_roll_joint.set_motor_torque(0.05 * float(np.clip(a[6], -1, +1))) 
Example 29
Project: soccer-matlab   Author: utra-robosoccer   File: robot_manipulators.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def apply_action(self, a):
		assert (np.isfinite(a).all())
		self.shoulder_pan_joint.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))
		self.shoulder_lift_joint.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))
		self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))
		self.elbow_flex_joint.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1)))
		self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[4], -1, +1)))
		self.wrist_flex_joint.set_motor_torque(0.05 * float(np.clip(a[5], -1, +1)))
		self.wrist_roll_joint.set_motor_torque(0.05 * float(np.clip(a[6], -1, +1))) 
Example 30
Project: soccer-matlab   Author: utra-robosoccer   File: robot_manipulators.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def apply_action(self, a):
		assert (np.isfinite(a).all())
		self.shoulder_pan_joint.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))
		self.shoulder_lift_joint.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))
		self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))
		self.elbow_flex_joint.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1)))
		self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[4], -1, +1)))
		self.wrist_flex_joint.set_motor_torque(0.05 * float(np.clip(a[5], -1, +1)))
		self.wrist_roll_joint.set_motor_torque(0.05 * float(np.clip(a[6], -1, +1)))