Python numbers.Real() Examples

The following are 30 code examples of numbers.Real(). 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 also want to check out all available functions/classes of the module numbers , or try the search function .
Example #1
Source File: httputil.py    From tornado-zh with MIT License 7 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example #2
Source File: laplace.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def set_sensitivity(self, sensitivity):
        """Sets the sensitivity of the mechanism.

        Parameters
        ----------
        sensitivity : float
            The sensitivity of the mechanism.  Must satisfy `sensitivity` > 0.

        Returns
        -------
        self : class

        """
        if not isinstance(sensitivity, Real):
            raise TypeError("Sensitivity must be numeric")

        if sensitivity < 0:
            raise ValueError("Sensitivity must be non-negative")

        self._sensitivity = float(sensitivity)
        return self 
Example #3
Source File: cart.py    From hadrian with Apache License 2.0 6 votes vote down vote up
def toNumpy(self):
            """Changes this field into a Numpy representation *in-place* (destructively replaces the old representation)."""

            if self.tpe == numbers.Real:
                self.data = numpy.array(self.data, dtype=numpy.dtype(float))
            elif self.tpe == basestring:
                unique = sorted(set(self.data))
                intToStr = dict(enumerate(unique))
                strToInt = dict((x, i) for i, x in enumerate(unique))
                converted = numpy.empty(len(self.data), dtype=numpy.dtype(int))
                for i, x in enumerate(self.data):
                    converted[i] = strToInt[x]
                self.intToStr = intToStr
                self.strToInt = strToInt
                self.data = converted
            return self 
Example #4
Source File: ioloop.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def __init__(
        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop
    ) -> None:
        if not isinstance(deadline, numbers.Real):
            raise TypeError("Unsupported deadline %r" % deadline)
        self.deadline = deadline
        self.callback = callback
        self.tdeadline = (
            deadline,
            next(io_loop._timeout_counter),
        )  # type: Tuple[float, int]

    # Comparison methods to sort by deadline, with object id as a tiebreaker
    # to guarantee a consistent ordering.  The heapq module uses __le__
    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
    # use __lt__). 
Example #5
Source File: compat.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def as_str_any(value):
  """Converts to `str` as `str(value)`, but use `as_str` for `bytes`.

  Args:
    value: A object that can be converted to `str`.

  Returns:
    A `str` object.
  """
  if isinstance(value, bytes):
    return as_str(value)
  else:
    return str(value)


# Numpy 1.8 scalars don't inherit from numbers.Integral in Python 3, so we
# need to check them specifically.  The same goes from Real and Complex. 
Example #6
Source File: httputil.py    From tornado-zh with MIT License 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example #7
Source File: utils.py    From pdfplumber with MIT License 6 votes vote down vote up
def _decimalize(v, q = None):
    # If already a decimal, just return itself
    if type(v) == Decimal:
        return v

    # If tuple/list passed, bulk-convert
    elif isinstance(v, (tuple, list)):
        return type(v)(decimalize(x, q) for x in v)

    # Convert int-like
    elif isinstance(v, numbers.Integral):
        return Decimal(int(v))

    # Convert float-like
    elif isinstance(v, numbers.Real):
        if q != None:
            return Decimal(repr(v)).quantize(Decimal(repr(q)),
                rounding=ROUND_HALF_UP)
        else:
            return Decimal(repr(v))
    else:
        raise ValueError("Cannot convert {0} to Decimal.".format(v)) 
Example #8
Source File: gaussian.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def check_inputs(self, value):
        super().check_inputs(value)

        if self._delta is None:
            raise ValueError("Delta must be set")

        if self._sensitivity is None:
            raise ValueError("Sensitivity must be set")

        if self._scale is None:
            self._scale = np.sqrt(2 * np.log(1.25 / self._delta)) * self._sensitivity / self._epsilon

        if not isinstance(value, Real):
            raise TypeError("Value to be randomised must be a number")

        return True 
Example #9
Source File: compat.py    From lambda-packs with MIT License 6 votes vote down vote up
def as_str_any(value):
  """Converts to `str` as `str(value)`, but use `as_str` for `bytes`.

  Args:
    value: A object that can be converted to `str`.

  Returns:
    A `str` object.
  """
  if isinstance(value, bytes):
    return as_str(value)
  else:
    return str(value)


# Numpy 1.8 scalars don't inherit from numbers.Integral in Python 3, so we
# need to check them specifically.  The same goes from Real and Complex. 
Example #10
Source File: util.py    From skutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_float(x):
    """Determine whether some object ``x`` is a
    float type (float, np.float, etc).

    Parameters
    ----------

    x : object
        The item to assess


    Returns
    -------

    bool
        True if ``x`` is a float type
    """
    return isinstance(x, (float, np.float)) or \
        (not isinstance(x, (bool, np.bool)) and isinstance(x, numbers.Real)) 
Example #11
Source File: vector.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def set_dimension(self, vector_dim):
        """Sets the dimension `vector_dim` of the domain of the mechanism.

        This dimension relates to the size of the input vector of the function being considered by the mechanism.  This
        corresponds to the size of the random vector produced by the mechanism.

        Parameters
        ----------
        vector_dim : int
            Function input dimension.

        Returns
        -------
        self : class

        """
        if not isinstance(vector_dim, Real) or not np.isclose(vector_dim, int(vector_dim)):
            raise TypeError("d must be integer-valued")
        if not vector_dim >= 1:
            raise ValueError("d must be strictly positive")

        self._vector_dim = int(vector_dim)
        return self 
Example #12
Source File: ibm_float.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def ldexp(cls, fraction, exponent):
        """Make an IBMFloat from fraction and exponent.

        The is the inverse function of IBMFloat.frexp()

        Args:
            fraction: A Real in the range -1.0 to 1.0.
            exponent: An integer in the range -256 to 255 inclusive.
        """
        if not (-1.0 <= fraction <= 1.0):
            raise ValueError("ldexp fraction {!r} out of range -1.0 to +1.0")

        if not (-256 <= exponent < 256):
            raise ValueError("ldexp exponent {!r} out of range -256 to 256")

        ieee = fraction * 2**exponent
        return IBMFloat.from_float(ieee) 
Example #13
Source File: test_validators.py    From exopy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_type_validation(task):
    """Test type validating an entry.

    """
    validator = validators.Feval(types=numbers.Real)

    task.feval = '2*{Loop_val}'
    val, res, msg = validator.check(task, 'feval')
    assert val == 2
    assert res
    assert not msg

    task.feval = '2j*{Loop_val}'
    val, res, msg = validator.check(task, 'feval')
    assert val is None
    assert not res
    assert msg 
Example #14
Source File: optimizer.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
def get_learning_rate_policy_callback(lr_params):
    if isinstance(lr_params, numbers.Real):
                # If argument is real number, set policy to fixed and use given value as base_lr
        lr_params = {'name': 'fixed', 'base_lr': lr_params}

    # Check if lr_params contains all required parameters for selected policy.
    if lr_params['name'] not in lrp.lr_policies:
        raise NotImplementedError("Learning rate policy {lr_name} not supported."
                                  "\nSupported policies are: {policies}".format(
                                      lr_name=lr_params['name'],
                                      policies=lrp.lr_policies.keys())
                                  )
    elif all([x in lr_params.keys() for x in lrp.lr_policies[lr_params['name']]['args']]):
        return lrp.lr_policies[lr_params['name']]['obj'](lr_params)
    else:
        raise ValueError("Too few arguments provided to create policy {lr_name}."
                         "\nGiven: {lr_params}"
                         "\nExpected: {lr_args}".format(
                             lr_name=lr_params['name'],
                             lr_params=lr_params.keys(),
                             lr_args=lrp.lr_policies[lr_params['name']])
                         ) 
Example #15
Source File: vector_v3.py    From pythonic-api with MIT License 5 votes vote down vote up
def __mul__(self, scalar):
        if isinstance(scalar, numbers.Real):
            return Vector(n * scalar for n in self)
        else:
            return NotImplemented 
Example #16
Source File: vector_v4.py    From pythonic-api with MIT License 5 votes vote down vote up
def __mul__(self, scalar):
        if isinstance(scalar, numbers.Real):
            return Vector(n * scalar for n in self)
        else:
            return NotImplemented 
Example #17
Source File: vector_v6.py    From pythonic-api with MIT License 5 votes vote down vote up
def __mul__(self, scalar):
        if isinstance(scalar, numbers.Real):
            return Vector(n * scalar for n in self)
        else:
            return NotImplemented 
Example #18
Source File: vector0a.py    From pythonic-api with MIT License 5 votes vote down vote up
def __mul__(self, scalar):
        if isinstance(scalar, numbers.Real):
            return Vector(n * scalar for n in self) 
        else:
            return NotImplemented 
Example #19
Source File: vector_v5.py    From pythonic-api with MIT License 5 votes vote down vote up
def __mul__(self, scalar):
        if isinstance(scalar, numbers.Real):
            return Vector(n * scalar for n in self)
        else:
            return NotImplemented 
Example #20
Source File: test_abc.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_complex(self):
        for t in sctypes['complex']:
            assert_(isinstance(t(), numbers.Complex), 
                    "{0} is not instance of Complex".format(t.__name__))
            assert_(issubclass(t, numbers.Complex),
                    "{0} is not subclass of Complex".format(t.__name__))
            assert_(not isinstance(t(), numbers.Real), 
                    "{0} is instance of Real".format(t.__name__))
            assert_(not issubclass(t, numbers.Real),
                    "{0} is subclass of Real".format(t.__name__)) 
Example #21
Source File: ioloop.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def add_timeout(self, deadline, callback, *args, **kwargs):
        """Runs the ``callback`` at the time ``deadline`` from the I/O loop.

        Returns an opaque handle that may be passed to
        `remove_timeout` to cancel.

        ``deadline`` may be a number denoting a time (on the same
        scale as `IOLoop.time`, normally `time.time`), or a
        `datetime.timedelta` object for a deadline relative to the
        current time.  Since Tornado 4.0, `call_later` is a more
        convenient alternative for the relative case since it does not
        require a timedelta object.

        Note that it is not safe to call `add_timeout` from other threads.
        Instead, you must use `add_callback` to transfer control to the
        `IOLoop`'s thread, and then call `add_timeout` from there.

        Subclasses of IOLoop must implement either `add_timeout` or
        `call_at`; the default implementations of each will call
        the other.  `call_at` is usually easier to implement, but
        subclasses that wish to maintain compatibility with Tornado
        versions prior to 4.0 must use `add_timeout` instead.

        .. versionchanged:: 4.0
           Now passes through ``*args`` and ``**kwargs`` to the callback.
        """
        if isinstance(deadline, numbers.Real):
            return self.call_at(deadline, callback, *args, **kwargs)
        elif isinstance(deadline, datetime.timedelta):
            return self.call_at(self.time() + timedelta_to_seconds(deadline),
                                callback, *args, **kwargs)
        else:
            raise TypeError("Unsupported deadline %r" % deadline) 
Example #22
Source File: test_abc.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_floats(self):
        for t in sctypes['float']:
            assert_(isinstance(t(), numbers.Real), 
                    "{0} is not instance of Real".format(t.__name__))
            assert_(issubclass(t, numbers.Real),
                    "{0} is not subclass of Real".format(t.__name__))
            assert_(not isinstance(t(), numbers.Rational), 
                    "{0} is instance of Rational".format(t.__name__))
            assert_(not issubclass(t, numbers.Rational),
                    "{0} is subclass of Rational".format(t.__name__)) 
Example #23
Source File: base.py    From nevergrad with MIT License 5 votes vote down vote up
def _update_archive_and_bests(self, candidate: p.Parameter, value: float) -> None:
        x = candidate.get_standardized_data(reference=self.parametrization)
        if not isinstance(value, (Real, float)):  # using "float" along "Real" because mypy does not understand "Real" for now Issue #3186
            raise TypeError(f'"tell" method only supports float values but the passed value was: {value} (type: {type(value)}.')
        if np.isnan(value) or value == np.inf:
            warnings.warn(f"Updating fitness with {value} value")
        mvalue: tp.Optional[utils.MultiValue] = None
        if x not in self.archive:
            self.archive[x] = utils.MultiValue(candidate, value, reference=self.parametrization)
        else:
            mvalue = self.archive[x]
            mvalue.add_evaluation(value)
            # both parameters should be non-None
            if mvalue.parameter.loss > candidate.loss:  # type: ignore
                mvalue.parameter = candidate   # keep best candidate
        # update current best records
        # this may have to be improved if we want to keep more kinds of best values

        for name in ["optimistic", "pessimistic", "average"]:
            if mvalue is self.current_bests[name]:  # reboot
                best = min(self.archive.values(), key=lambda mv, n=name: mv.get_estimation(n))  # type: ignore
                # rebuild best point may change, and which value did not track the updated value anyway
                self.current_bests[name] = best
            else:
                if self.archive[x].get_estimation(name) <= self.current_bests[name].get_estimation(name):
                    self.current_bests[name] = self.archive[x]
                # deactivated checks
                # if not (np.isnan(value) or value == np.inf):
                #     if not self.current_bests[name].x in self.archive:
                #         bval = self.current_bests[name].get_estimation(name)
                #         avals = (min(v.get_estimation(name) for v in self.archive.values()),
                #                  max(v.get_estimation(name) for v in self.archive.values()))
                #         raise RuntimeError(f"Best value should exist in the archive at num_tell={self.num_tell})\n"
                #                            f"Best value is {bval} and archive is within range {avals} for {name}")
        if self.pruning is not None:
            self.archive = self.pruning(self.archive) 
Example #24
Source File: test_abstract_numbers.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_complex(self):
        self.assertFalse(issubclass(complex, Real))
        self.assertTrue(issubclass(complex, Complex))

        c1, c2 = complex(3, 2), complex(4,1)
        # XXX: This is not ideal, but see the comment in math_trunc().
        self.assertRaises(AttributeError, math.trunc, c1)
        self.assertRaises(TypeError, float, c1)
        self.assertRaises(TypeError, int, c1) 
Example #25
Source File: test_abstract_numbers.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_float(self):
        self.assertFalse(issubclass(float, Rational))
        self.assertTrue(issubclass(float, Real))

        self.assertEqual(7.3, float(7.3).real)
        self.assertEqual(0, float(7.3).imag)
        self.assertEqual(7.3, float(7.3).conjugate()) 
Example #26
Source File: test_decimal.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_abc(self):
        self.assertTrue(issubclass(Decimal, numbers.Number))
        self.assertFalse(issubclass(Decimal, numbers.Real))
        self.assertIsInstance(Decimal(0), numbers.Number)
        self.assertNotIsInstance(Decimal(0), numbers.Real) 
Example #27
Source File: regularizers.py    From lambda-packs with MIT License 5 votes vote down vote up
def l2_regularizer(scale, scope=None):
  """Returns a function that can be used to apply L2 regularization to weights.

  Small values of L2 can help prevent overfitting the training data.

  Args:
    scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
    scope: An optional scope name.

  Returns:
    A function with signature `l2(weights)` that applies L2 regularization.

  Raises:
    ValueError: If scale is negative or if scale is not a float.
  """
  if isinstance(scale, numbers.Integral):
    raise ValueError('scale cannot be an integer: %s' % (scale,))
  if isinstance(scale, numbers.Real):
    if scale < 0.:
      raise ValueError('Setting a scale less than 0 on a regularizer: %g.' %
                       scale)
    if scale == 0.:
      logging.info('Scale of 0 disables regularizer.')
      return lambda _: None

  def l2(weights):
    """Applies l2 regularization to weights."""
    with ops.name_scope(scope, 'l2_regularizer', [weights]) as name:
      my_scale = ops.convert_to_tensor(scale,
                                       dtype=weights.dtype.base_dtype,
                                       name='scale')
      return standard_ops.multiply(my_scale, nn.l2_loss(weights), name=name)

  return l2 
Example #28
Source File: regularizers.py    From lambda-packs with MIT License 5 votes vote down vote up
def l1_regularizer(scale, scope=None):
  """Returns a function that can be used to apply L1 regularization to weights.

  L1 regularization encourages sparsity.

  Args:
    scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
    scope: An optional scope name.

  Returns:
    A function with signature `l1(weights)` that apply L1 regularization.

  Raises:
    ValueError: If scale is negative or if scale is not a float.
  """
  if isinstance(scale, numbers.Integral):
    raise ValueError('scale cannot be an integer: %s' % scale)
  if isinstance(scale, numbers.Real):
    if scale < 0.:
      raise ValueError('Setting a scale less than 0 on a regularizer: %g' %
                       scale)
    if scale == 0.:
      logging.info('Scale of 0 disables regularizer.')
      return lambda _: None

  def l1(weights, name=None):
    """Applies L1 regularization to weights."""
    with ops.name_scope(scope, 'l1_regularizer', [weights]) as name:
      my_scale = ops.convert_to_tensor(scale,
                                       dtype=weights.dtype.base_dtype,
                                       name='scale')
      return standard_ops.multiply(
          my_scale,
          standard_ops.reduce_sum(standard_ops.abs(weights)),
          name=name)

  return l1 
Example #29
Source File: layers.py    From lingvo with Apache License 2.0 5 votes vote down vote up
def FProp(self, theta, inputs):
    """Apply dropout to inputs.

    Args:
      theta: A `.NestedMap` object containing weights' values of this layer and
        its children layers.
      inputs: The inputs tensor.

    Returns:
      inputs with dropout applied at training time.
    """
    p = self.params
    if not self.do_eval or p.dropout_at_eval:
      if isinstance(p.keep_prob, numbers.Real) and p.keep_prob == 1.0:
        return inputs
      if p.noise_shape_broadcast_dims:
        noise_shape = p.noise_shape or py_utils.GetShape(inputs)
        for dim in p.noise_shape_broadcast_dims:
          if dim >= len(noise_shape):
            raise ValueError('Invalid broadcasted dim {}'.format(dim))
          noise_shape[dim] = 1
      else:
        noise_shape = p.noise_shape
      ret = self._Dropout(theta, inputs, noise_shape)
      ret.set_shape(inputs.get_shape())
      return ret
    else:
      return inputs 
Example #30
Source File: regularizers.py    From tensornets with MIT License 5 votes vote down vote up
def l2_regularizer(scale, scope=None):
  """Returns a function that can be used to apply L2 regularization to weights.

  Small values of L2 can help prevent overfitting the training data.

  Args:
    scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
    scope: An optional scope name.

  Returns:
    A function with signature `l2(weights)` that applies L2 regularization.

  Raises:
    ValueError: If scale is negative or if scale is not a float.
  """
  if isinstance(scale, numbers.Integral):
    raise ValueError('scale cannot be an integer: %s' % (scale,))
  if isinstance(scale, numbers.Real):
    if scale < 0.:
      raise ValueError('Setting a scale less than 0 on a regularizer: %g.' %
                       scale)
    if scale == 0.:
      logging.info('Scale of 0 disables regularizer.')
      return lambda _: None

  def l2(weights):
    """Applies l2 regularization to weights."""
    with ops.name_scope(scope, 'l2_regularizer', [weights]) as name:
      my_scale = ops.convert_to_tensor(scale,
                                       dtype=weights.dtype.base_dtype,
                                       name='scale')
      return standard_ops.multiply(my_scale, nn.l2_loss(weights), name=name)

  return l2