numpy.inf

Here are the examples of the python api numpy.inf taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5748 Examples 7

5 Source : tsp_byedge.py
with MIT License
from ghackebeil

    def bound(self):
        if self._cost is None:
            assert len(self._path) >= 1
            if len(self._path) > 1:
                u = self._path[-2]
                v = self._path[-1]
                self._dist[u, :] = numpy.inf
                self._dist[:, v] = numpy.inf
                self._dist[v][self._path[0]] = numpy.inf
            row_sum = self._row_reduction()
            col_sum = self._col_reduction()
            self._cost = self._partial_cost
            self._cost += row_sum
            self._cost += col_sum
        return self._cost

    def save_state(self, node):

5 Source : gaussian_noise.py
with GNU General Public License v3.0
from gwastro

    def _nowaveform_loglr(self):
        """Convenience function to set loglr values if no waveform generated.
        """
        for det in self._data:
            setattr(self._current_stats, 'loglikelihood', -numpy.inf)
            setattr(self._current_stats, '{}_cplx_loglr'.format(det),
                    -numpy.inf)
            # snr can't be   <   0 by definition, so return 0
            setattr(self._current_stats, '{}_optimal_snrsq'.format(det), 0.)
        return -numpy.inf

    def _loglr(self):

5 Source : test_jagged.py
with BSD 3-Clause "New" or "Revised" License
from scikit-hep

    def test_jagged_type(self):
        a = JaggedArray([0, 3, 3, 5], [3, 3, 5, 10], [0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
        assert a.type == ArrayType(4, numpy.inf, float)

        a = JaggedArray([[0, 3], [3, 5]], [[3, 3], [5, 10]], [0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
        assert a.type == ArrayType(2, 2, numpy.inf, float)

        a = JaggedArray([0, 3, 3, 5], [3, 3, 5, 10], [[0.0], [1.1], [2.2], [3.3], [4.4], [5.5], [6.6], [7.7], [8.8], [9.9]])
        assert a.type == ArrayType(4, numpy.inf, 1, float)

    def test_jagged_fromlocalindex(self):

5 Source : test_jagged.py
with BSD 3-Clause "New" or "Revised" License
from scikit-hep

    def test_jagged_sort(self):
        a = awkward0.fromiter([[2.,3.,1.], [4., -numpy.inf, 5.], [numpy.inf, 4., numpy.nan, -numpy.inf], [numpy.nan], [3., None, 4., -1.]])
        assert a.argsort().tolist() == [[1, 0, 2], [2, 0, 1], [0, 1, 3, 2], [0], [2, 0, 3]]
        assert a.argsort(True).tolist() == [[2, 0, 1], [1, 0, 2], [3, 1, 0, 2], [0], [3, 0, 2]]

    def test_jagged_setitem_bool_indexing(self):

3 Source : saver.py
with Apache License 2.0
from 17Skye17

  def set_last_checkpoints(self, last_checkpoints):
    """DEPRECATED: Use set_last_checkpoints_with_time.

    Sets the list of old checkpoint filenames.

    Args:
      last_checkpoints: A list of checkpoint filenames.

    Raises:
      AssertionError: If last_checkpoints is not a list.
    """
    assert isinstance(last_checkpoints, list)
    # We use a timestamp of +inf so that this checkpoint will never be
    # deleted.  This is both safe and backwards compatible to a previous
    # version of the code which used s[1] as the "timestamp".
    self._last_checkpoints = [(s, np.inf) for s in last_checkpoints]

  def set_last_checkpoints_with_time(self, last_checkpoints_with_time):

3 Source : bounding.py
with MIT License
from 3fon3fonov

def _friends_leaveoneout_radius(points, ftype):
    """Internal method used to compute the radius (half-side-length) for each
    ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using
    leave-one-out (LOO) cross-validation."""

    # Construct KDTree to enable quick nearest-neighbor lookup for
    # our resampled objects.
    kdtree = spatial.KDTree(points)

    if ftype == 'balls':
        # Compute radius to two nearest neighbors (self + neighbor).
        dists, ids = kdtree.query(points, k=2, eps=0, p=2)
    elif ftype == 'cubes':
        # Compute half-side-length to two nearest neighbors (self + neighbor).
        dists, ids = kdtree.query(points, k=2, eps=0, p=np.inf)

    dist = dists[:, 1]  # distances to LOO nearest neighbor

    return dist

3 Source : dynamicsampler.py
with MIT License
from 3fon3fonov

    def reset(self):
        """Re-initialize the sampler."""

        # sampling
        self.it = 1
        self.batch = 0
        self.ncall = 0
        self.bound = []
        self.eff = 1.
        self.base = False

        self.saved_run = RunRecord(dynamic=True)
        self.base_run = RunRecord(dynamic=True)
        self.new_run = RunRecord(dynamic=True)
        self.new_logl_min, self.new_logl_max = -np.inf, np.inf

    @property

3 Source : DateAxisItem.py
with MIT License
from 3fon3fonov

def makeMSStepper(stepSize):
    def stepper(val, n):
        if val   <   MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP:
            return np.inf
        
        val *= 1000
        f = stepSize * 1000
        return (val // (n*f) + 1) * (n*f) / 1000.0
    return stepper

def makeSStepper(stepSize):

3 Source : DateAxisItem.py
with MIT License
from 3fon3fonov

def makeSStepper(stepSize):
    def stepper(val, n):
        if val   <   MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP:
            return np.inf
        
        return (val // (n*stepSize) + 1) * (n*stepSize)
    return stepper

def makeMStepper(stepSize):

3 Source : DateAxisItem.py
with MIT License
from 3fon3fonov

def makeMStepper(stepSize):
    def stepper(val, n):
        if val   <   MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP:
            return np.inf
        
        d = utcfromtimestamp(val)
        base0m = (d.month + n*stepSize - 1)
        d = datetime(d.year + base0m // 12, base0m % 12 + 1, 1)
        return (d - datetime(1970, 1, 1)).total_seconds()
    return stepper

def makeYStepper(stepSize):

3 Source : DateAxisItem.py
with MIT License
from 3fon3fonov

def makeYStepper(stepSize):
    def stepper(val, n):
        if val   <   MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP:
            return np.inf
        
        d = utcfromtimestamp(val)
        next_year = (d.year // (n*stepSize) + 1) * (n*stepSize)
        if next_year > 9999:
            return np.inf
        next_date = datetime(next_year, 1, 1)
        return (next_date - datetime(1970, 1, 1)).total_seconds()
    return stepper

class TickSpec:

3 Source : napari_image_view.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

    def images_bounds(self) -> Tuple[List[int], List[int]]:
        ranges = []
        for image_info in self.image_info.values():
            if not image_info.layers:
                continue
            ranges = [
                (min(a, b), max(c, d), min(e, f))
                for (a, c, e), (b, d, f) in itertools.zip_longest(
                    image_info.layers[0].dims.range, ranges, fillvalue=(np.inf, -np.inf, np.inf)
                )
            ]

        visible = [ranges[i] for i in self.viewer.dims.displayed]
        min_shape, max_shape, _ = zip(*visible)
        size = np.subtract(max_shape, min_shape)
        return size, min_shape

    @staticmethod

3 Source : model_checking.py
with MIT License
from 95616ARG

    def initialize_stats(self, polytopes):
        """Sets the partitioning used by the TransformerLUT hash table.
        """
        self.grid_lb = np.array([np.inf, np.inf])
        self.grid_ub = np.array([-np.inf, -np.inf])
        deltas = []
        self.grid_delta = np.array([np.inf, np.inf])
        for polytope in polytopes:
            box_lb = np.min(polytope, axis=0)
            box_ub = np.max(polytope, axis=0)
            self.grid_lb = np.minimum(self.grid_lb, box_lb)
            self.grid_ub = np.maximum(self.grid_ub, box_ub)
            deltas.append(box_ub - box_lb)
        deltas = np.array(deltas)
        self.grid_delta = np.percentile(deltas, 25, axis=0)

    def keys_for(self, polytope):

3 Source : metrics.py
with MIT License
from 96jhwei

def _upscan(f):
    for i, fi in enumerate(f):
        if fi == np.inf: continue
        for j in range(1,i+1):
            x = fi+j*j
            if f[i-j]   <   x: break
            f[i-j] = x


def dice_coefficient_numpy(binary_segmentation, binary_gt_label):

3 Source : acquisition.py
with MIT License
from a5a

    def evaluate(self, x: np.ndarray, **kwargs) -> np.ndarray:
        """
        Evaluates the acquisition function.

        Parameters
        ----------
        x
            Input to evaluate the acquisition function at

        """
        if self.verbose:
            print("Evaluating Uncertainty at", x)
        _, var = self.surrogate.predict(x)
        var = np.clip(var, 1e-8, np.inf)

        return var


class PI(AcquisitionFunction):

3 Source : acquisition.py
with MIT License
from a5a

    def evaluate(self, x, **kwargs) -> np.ndarray:
        """
        Evaluates the UCB acquisition function.

        Parameters
        ----------
        x
            Input to evaluate the acquisition function at
        """
        if self.verbose:
            print("Evaluating UCB at", x)
        mu, var = self.surrogate.predict(x)
        var = np.clip(var, 1e-8, np.inf)

        s = np.sqrt(var)  # type: np.ndarray
        return -(mu - self.tradeoff * s).flatten()


class PenalisedAcquisition(AcquisitionFunction):

3 Source : posterior_generator.py
with MIT License
from abrazinskas

    def forward_decoder(self, prev_sel_indxs, encoder_out: List[EncoderOut],
                        temperature: float = 1.0):
        scores = self.model.decoder.forward(prev_sel_indxs=prev_sel_indxs,
                                            encoder_out=encoder_out,
                                            incremental_state=self.incremental_state)
        scores[:, :, self.pad_idx] = - np.inf
        probs = softmax(scores.div_(temperature), dim=-1)
        return probs


def sample_doc_indx(probs):

3 Source : util.py
with GNU General Public License v3.0
from acamero

    def __init__(self,
                 **kwargs):
        np.set_printoptions(threshold=np.inf)
        if 'filename' not in kwargs:
            raise Exception("JSONOutput init error: 'filename' missing")
        self.filename = kwargs['filename']
        if ('seed' in kwargs
                and self.filename.rfind(".") > 0):
            self.filename = (self.filename[:self.filename.rfind(".")]
                             + "." + str(kwargs['seed'])
                             + self.filename[self.filename.rfind("."):])
        elif 'seed' in kwargs:
            self.filename += "." + str(kwargs['seed'])

    def output(self,

3 Source : sample-arch.py
with GNU General Public License v3.0
from acamero

    def _save_metrics(self, metrics):
        try:
            np.set_printoptions(threshold=np.inf)
            with open(self.output_file, 'a') as f:
                f.write(str(metrics)+'\n')
            f.close()
        except IOError:
            print('Unable to store the metrics')
   

#########################################################################################################################

if __name__ == '__main__':

3 Source : run_mujoco.py
with MIT License
from AcutronicRobotics

def get_task_name(args):
    task_name = args.algo + "_gail."
    if args.pretrained:
        task_name += "with_pretrained."
    if args.traj_limitation != np.inf:
        task_name += "transition_limitation_%d." % args.traj_limitation
    task_name += args.env_id.split("-")[0]
    task_name = task_name + ".g_step_" + str(args.g_step) + ".d_step_" + str(args.d_step) + \
        ".policy_entcoeff_" + str(args.policy_entcoeff) + ".adversary_entcoeff_" + str(args.adversary_entcoeff)
    task_name += ".seed_" + str(args.seed)
    return task_name


def main(args):

3 Source : _binary_approximation.py
with GNU Lesser General Public License v3.0
from adbuerger

    def max_up_times(self) -> np.ndarray:

        '''
        Get the maximum up times per control, i. e., the time a control
        be can stay activated before it must be deactivated.
        '''

        try:
            return self._max_up_times

        except AttributeError:

            return np.full(self.n_c, np.inf)


    @property

3 Source : _binary_approximation.py
with GNU Lesser General Public License v3.0
from adbuerger

    def total_max_up_times(self) -> np.ndarray:

        '''
        Get the total maximum up times per control, i. e., the total time a
        control can be active over the whole time horizon.
        '''

        try:
            return self._total_max_up_times

        except AttributeError:

            return np.full(self.n_c, np.inf)


    @property

3 Source : stars.py
with Apache License 2.0
from ADDVulcan

def find_by_angles(a1, a2):
    min_dist = np.inf
    best = None
    for i in range(2500):
        d1 = a1 - stardb.stars_next[i][1]
        d2 = a2 - stardb.stars_next[i][3]
        dist = math.sqrt(d1*d1 + d2*d2)
        if dist   <   min_dist:
            best = i
            min_dist = dist
    return best

if __name__ == "__main__":

3 Source : stars_improved.py
with Apache License 2.0
from ADDVulcan

def find_by_angles(a1, a2, ab=None):
    min_dist = np.inf
    best = None
    for i, stars_next in enumerate(stardb_improved.stars_next):
        d1 = a1 - stars_next[0]
        d2 = a2 - stars_next[1]
        if ab:
            d3 = ab - stars_next[2]
        else:
            d3 = 0
        dist = math.sqrt(d1*d1 + d2*d2 + d3*d3)
        if dist   <   min_dist:
            best = i
            min_dist = dist
    return best, min_dist

3 Source : embedding_head.py
with MIT License
from adeline-cs

    def forward(self, q, k, v, mask=None):

        attn = torch.bmm(q, k.transpose(1, 2))
        attn = attn / self.temperature

        if mask is not None:
            attn = attn.masked_fill(mask, -np.inf)

        attn = self.softmax(attn)
        attn = self.dropout(attn)
        output = torch.bmm(attn, v)

        return output, attn

class MultiHeadAttention(nn.Module):

3 Source : test_numeric.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_no_parameter_modification(self):
        x = np.array([np.inf, 1])
        y = np.array([0, np.inf])
        np.allclose(x, y)
        assert_array_equal(x, np.array([np.inf, 1]))
        assert_array_equal(y, np.array([0, np.inf]))

    def test_min_int(self):

3 Source : test_numeric.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_no_parameter_modification(self):
        x = np.array([np.inf, 1])
        y = np.array([0, np.inf])
        np.isclose(x, y)
        assert_array_equal(x, np.array([np.inf, 1]))
        assert_array_equal(y, np.array([0, np.inf]))

    def test_non_finite_scalar(self):

3 Source : test_numeric.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_non_finite_scalar(self):
        # GH7014, when two scalars are compared the output should also be a
        # scalar
        assert_(np.isclose(np.inf, -np.inf) is np.False_)
        assert_(np.isclose(0, np.inf) is np.False_)
        assert_(type(np.isclose(0, np.inf)) is np.bool_)


class TestStdVar(object):

3 Source : test_print.py
with GNU General Public License v3.0
from adityaprakash-bobby

def check_nan_inf_float(tp):
    for x in [np.inf, -np.inf, np.nan]:
        assert_equal(str(tp(x)), _REF[x],
                     err_msg='Failed str formatting for type %s' % tp)

def test_nan_inf_float():

3 Source : test_print.py
with GNU General Public License v3.0
from adityaprakash-bobby

def check_float_type_print(tp):
    for x in [0, 1, -1, 1e20]:
        _test_redirected_print(float(x), tp)

    for x in [np.inf, -np.inf, np.nan]:
        _test_redirected_print(float(x), tp, _REF[x])

    if tp(1e16).itemsize > 4:
        _test_redirected_print(float(1e16), tp)
    else:
        ref = '1e+16'
        _test_redirected_print(float(1e16), tp, ref)

def check_complex_type_print(tp):

3 Source : test_print.py
with GNU General Public License v3.0
from adityaprakash-bobby

def check_complex_type_print(tp):
    # We do not create complex with inf/nan directly because the feature is
    # missing in python   <   2.6
    for x in [0, 1, -1, 1e20]:
        _test_redirected_print(complex(x), tp)

    if tp(1e16).itemsize > 8:
        _test_redirected_print(complex(1e16), tp)
    else:
        ref = '(1e+16+0j)'
        _test_redirected_print(complex(1e16), tp, ref)

    _test_redirected_print(complex(np.inf, 1), tp, '(inf+1j)')
    _test_redirected_print(complex(-np.inf, 1), tp, '(-inf+1j)')
    _test_redirected_print(complex(-np.nan, 1), tp, '(nan+1j)')

def test_float_type_print():

3 Source : test_scalarmath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_int_from_infinite_longdouble(self):
        # gh-627
        x = np.longdouble(np.inf)
        assert_raises(OverflowError, int, x)
        with suppress_warnings() as sup:
            sup.record(np.ComplexWarning)
            x = np.clongdouble(np.inf)
            assert_raises(OverflowError, int, x)
            assert_equal(len(sup.log), 1)

    @dec.knownfailureif(not IS_PYPY,

3 Source : test_scalarmath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_int_from_infinite_longdouble___int__(self):
        x = np.longdouble(np.inf)
        assert_raises(OverflowError, x.__int__)
        with suppress_warnings() as sup:
            sup.record(np.ComplexWarning)
            x = np.clongdouble(np.inf)
            assert_raises(OverflowError, x.__int__)
            assert_equal(len(sup.log), 1)

    @dec.knownfailureif(platform.machine().startswith("ppc64"))

3 Source : test_scalarprint.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_str(self):
        svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan]
        styps = [np.float16, np.float32, np.float64, np.longdouble]
        wanted = [
             ['0.0',  '0.0',  '0.0',  '0.0' ],
             ['-0.0', '-0.0', '-0.0', '-0.0'],
             ['1.0',  '1.0',  '1.0',  '1.0' ],
             ['-1.0', '-1.0', '-1.0', '-1.0'],
             ['inf',  'inf',  'inf',  'inf' ],
             ['-inf', '-inf', '-inf', '-inf'],
             ['nan',  'nan',  'nan',  'nan']]

        for wants, val in zip(wanted, svals):
            for want, styp in zip(wants, styps):
                msg = 'for str({}({}))'.format(np.dtype(styp).name, repr(val))
                assert_equal(str(styp(val)), want, err_msg=msg)

    def test_scalar_cutoffs(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf)


class TestPower(object):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_inf(self):
        inf = np.inf
        x = [inf, -inf,  inf, -inf, inf, 1,  -inf,  1]
        y = [inf,  inf, -inf, -inf, 1,   inf, 1,   -inf]
        z = [inf,  inf,  inf, -inf, inf, inf, 1,    1]
        with np.errstate(invalid='raise'):
            for dt in ['f', 'd', 'g']:
                logxf = np.array(x, dtype=dt)
                logyf = np.array(y, dtype=dt)
                logzf = np.array(z, dtype=dt)
                assert_equal(np.logaddexp2(logxf, logyf), logzf)

    def test_nan(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_inf(self):
        inf = np.inf
        x = [inf, -inf,  inf, -inf, inf, 1,  -inf,  1]
        y = [inf,  inf, -inf, -inf, 1,   inf, 1,   -inf]
        z = [inf,  inf,  inf, -inf, inf, inf, 1,    1]
        with np.errstate(invalid='raise'):
            for dt in ['f', 'd', 'g']:
                logxf = np.array(x, dtype=dt)
                logyf = np.array(y, dtype=dt)
                logzf = np.array(z, dtype=dt)
                assert_equal(np.logaddexp(logxf, logyf), logzf)

    def test_nan(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_special(self):
        assert_equal(ncu.expm1(np.inf), np.inf)
        assert_equal(ncu.expm1(0.), 0.)
        assert_equal(ncu.expm1(-0.), -0.)
        assert_equal(ncu.expm1(np.inf), np.inf)
        assert_equal(ncu.expm1(-np.inf), -1.)


class TestHypot(object):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_any_pinf(self):
        # atan2(+-y, +infinity) returns +-0 for finite y > 0.
        assert_arctan2_ispzero(1, np.inf)
        assert_arctan2_isnzero(-1, np.inf)

    def test_inf_any(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_inf_any(self):
        # atan2(+-infinity, x) returns +-pi/2 for finite x.
        assert_almost_equal(ncu.arctan2( np.inf, 1),  0.5 * np.pi)
        assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi)

    def test_inf_ninf(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_inf_ninf(self):
        # atan2(+-infinity, -infinity) returns +-3*pi/4.
        assert_almost_equal(ncu.arctan2( np.inf, -np.inf),  0.75 * np.pi)
        assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi)

    def test_inf_pinf(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_inf_pinf(self):
        # atan2(+-infinity, +infinity) returns +-pi/4.
        assert_almost_equal(ncu.arctan2( np.inf, np.inf),  0.25 * np.pi)
        assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi)

    def test_nan_any(self):

3 Source : test_umath.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_sign(self):
        a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
        out = np.zeros(a.shape)
        tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])

        with np.errstate(invalid='ignore'):
            res = ncu.sign(a)
            assert_equal(res, tgt)
            res = ncu.sign(a, out)
            assert_equal(res, tgt)
            assert_equal(out, tgt)

    def test_sign_dtype_object(self):

3 Source : test_umath_complex.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_simple(self):
        x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan])
        y_r = x ** 2
        y = np.power(x, 2)
        for i in range(len(x)):
            assert_almost_equal(y[i], y_r[i])

    def test_scalar(self):

3 Source : test_umath_complex.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_scalar(self):
        x = np.array([1, 1j,         2,  2.5+.37j, np.inf, np.nan])
        y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j,      2,      3])
        lx = list(range(len(x)))
        # Compute the values for complex type in python
        p_r = [complex(x[i]) ** complex(y[i]) for i in lx]
        # Substitute a result allowed by C99 standard
        p_r[4] = complex(np.inf, np.nan)
        # Do the same with numpy complex scalars
        n_r = [x[i] ** y[i] for i in lx]
        for i in lx:
            assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i)

    def test_array(self):

3 Source : test_umath_complex.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_array(self):
        x = np.array([1, 1j,         2,  2.5+.37j, np.inf, np.nan])
        y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j,      2,      3])
        lx = list(range(len(x)))
        # Compute the values for complex type in python
        p_r = [complex(x[i]) ** complex(y[i]) for i in lx]
        # Substitute a result allowed by C99 standard
        p_r[4] = complex(np.inf, np.nan)
        # Do the same with numpy arrays
        n_r = x ** y
        for i in lx:
            assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i)

class TestCabs(object):

3 Source : test_umath_complex.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_simple(self):
        x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan])
        y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan])
        y = np.abs(x)
        for i in range(len(x)):
            assert_almost_equal(y[i], y_r[i])

    def test_fabs(self):

3 Source : test_function_base.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_simple(self):
        a = [1, 2, 3]
        b = [1, 2, np.inf]
        c = [1, 2, np.nan]
        np.lib.asarray_chkfinite(a)
        assert_raises(ValueError, np.lib.asarray_chkfinite, b)
        assert_raises(ValueError, np.lib.asarray_chkfinite, c)

    def test_dtype_order(self):

3 Source : test_function_base.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_wrong_ddof(self):
        with warnings.catch_warnings(record=True):
            warnings.simplefilter('always', RuntimeWarning)
            assert_array_equal(cov(self.x1, ddof=5),
                               np.array([[np.inf, -np.inf],
                                         [-np.inf, np.inf]]))

    def test_1D_rowvar(self):

3 Source : test_twodim_base.py
with GNU General Public License v3.0
from adityaprakash-bobby

def test_tril_triu_with_inf():
    # Issue 4859
    arr = np.array([[1, 1, np.inf],
                    [1, 1, 1],
                    [np.inf, 1, 1]])
    out_tril = np.array([[1, 0, 0],
                         [1, 1, 0],
                         [np.inf, 1, 1]])
    out_triu = out_tril.T
    assert_array_equal(np.triu(arr), out_triu)
    assert_array_equal(np.tril(arr), out_tril)


def test_tril_triu_dtype():

See More Examples