Python math.isinf() Examples

The following are code examples for showing how to use math.isinf(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: fractions.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 2
Project: pyblish-win   Author: pyblish   File: fractions.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        # comparisons with complex should raise a TypeError, for consistency
        # with int<->complex, float<->complex, and complex<->complex comparisons.
        if isinstance(other, complex):
            raise TypeError("no ordering relation is defined for complex numbers")
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 3
Project: DOTA_models   Author: ringringyi   File: accountant.py    Apache License 2.0 6 votes vote down vote up
def _compute_delta(self, log_moments, eps):
    """Compute delta for given log_moments and eps.

    Args:
      log_moments: the log moments of privacy loss, in the form of pairs
        of (moment_order, log_moment)
      eps: the target epsilon.
    Returns:
      delta
    """
    min_delta = 1.0
    for moment_order, log_moment in log_moments:
      if math.isinf(log_moment) or math.isnan(log_moment):
        sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
        continue
      if log_moment < moment_order * eps:
        min_delta = min(min_delta,
                        math.exp(log_moment - moment_order * eps))
    return min_delta 
Example 4
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    Apache License 2.0 6 votes vote down vote up
def _compute_delta(log_moments, eps):
  """Compute delta for given log_moments and eps.

  Args:
    log_moments: the log moments of privacy loss, in the form of pairs
      of (moment_order, log_moment)
    eps: the target epsilon.
  Returns:
    delta
  """
  min_delta = 1.0
  for moment_order, log_moment in log_moments:
    if moment_order == 0:
      continue
    if math.isinf(log_moment) or math.isnan(log_moment):
      sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
      continue
    if log_moment < moment_order * eps:
      min_delta = min(min_delta,
                      math.exp(log_moment - moment_order * eps))
  return min_delta 
Example 5
Project: DOTA_models   Author: ringringyi   File: utils.py    Apache License 2.0 6 votes vote down vote up
def GenerateBinomialTable(m):
  """Generate binomial table.

  Args:
    m: the size of the table.
  Returns:
    A two dimensional array T where T[i][j] = (i choose j),
    for 0<= i, j <=m.
  """

  table = numpy.zeros((m + 1, m + 1), dtype=numpy.float64)
  for i in range(m + 1):
    table[i, 0] = 1
  for i in range(1, m + 1):
    for j in range(1, m + 1):
      v = table[i - 1, j] + table[i - 1, j -1]
      assert not math.isnan(v) and not math.isinf(v)
      table[i, j] = v
  return tf.convert_to_tensor(table) 
Example 6
Project: StatNLP-PyTorch   Author: allanj   File: Network.py    GNU General Public License v3.0 6 votes vote down vote up
def inside(self):
        self.inside_scores = autograd.Variable(torch.Tensor(self.count_nodes()).fill_(0.0).cuda() if NetworkConfig.GPU_ID >= 0 else torch.Tensor(self.count_nodes()).fill_(0.0))
        for k in range(self.count_nodes()):
            self.get_inside(k)
        if math.isinf(self.get_insides().data[0]) and self.get_insides() > 0:
            raise Exception("Error: network (ID=", self.network_id, ") has zero inside score")

        # if self.get_instance().is_labeled:
        #     print('inside:', self.get_insides())
            #print(self.param.model.weights)
        #
        #
        # print()
        #
        # print()
        weight = self.get_instance().weight
        return self.get_insides() * weight 
Example 7
Project: jawfish   Author: war-and-code   File: fractions.py    MIT License 6 votes vote down vote up
def from_float(cls, f):
        """Converts a finite float to a rational number, exactly.

        Beware that Fraction.from_float(0.3) != Fraction(3, 10).

        """
        if isinstance(f, numbers.Integral):
            return cls(f)
        elif not isinstance(f, float):
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
        if math.isnan(f):
            raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
        if math.isinf(f):
            raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
        return cls(*f.as_integer_ratio()) 
Example 8
Project: jawfish   Author: war-and-code   File: fractions.py    MIT License 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 9
Project: jawfish   Author: war-and-code   File: fractions.py    MIT License 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 10
Project: python-tabulate   Author: cmck   File: tabulate.py    MIT License 6 votes vote down vote up
def _isnumber(string):
    """
    >>> _isnumber("123.45")
    True
    >>> _isnumber("123")
    True
    >>> _isnumber("spam")
    False
    >>> _isnumber("123e45678")
    False
    >>> _isnumber("inf")
    True
    """
    if not _isconvertible(float, string):
        return False
    elif isinstance(string, (_text_type, _binary_type)) and (
            math.isinf(float(string)) or math.isnan(float(string))):
        return string.lower() in ['inf', '-inf', 'nan']
    return True 
Example 11
Project: kivy-smoothie-host   Author: wolfmanjm   File: dial-gauge.py    GNU General Public License v3.0 6 votes vote down vote up
def draw_setpoint(self, *args):
        # draw a setpoint
        if self.setpoint_canvas:
            self.canvas.after.remove(self.setpoint_canvas)
            self.setpoint_canvas= None

        if math.isnan(self.setpoint_value) or math.isinf(self.setpoint_value):
            return

        v= self.value_to_angle(self.setpoint_value)
        length= self.dial_diameter/2.0-self.tic_length if not self.setpoint_length else self.setpoint_length
        self.setpoint_canvas = InstructionGroup()

        self.setpoint_canvas.add(PushMatrix())
        self.setpoint_canvas.add(Color(*self.setpoint_color))
        self.setpoint_canvas.add(Rotate(angle=v, axis=(0,0,-1), origin= self.dial_center))
        self.setpoint_canvas.add(Translate(self.dial_center[0], self.dial_center[1]))
        self.setpoint_canvas.add(Line(points=[0, 0, 0, length], width=self.setpoint_thickness, cap= 'none'))
        #self.setpoint_canvas.add(SmoothLine(points=[0, 0, 0, length], width=self.setpoint_thickness))
        self.setpoint_canvas.add(PopMatrix())

        self.canvas.after.add(self.setpoint_canvas) 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: fractions.py    GNU General Public License v3.0 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if type(b) is int:
            return a._numerator == b and a._denominator == 1
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 13
Project: NiujiaoDebugger   Author: MrSrc   File: fractions.py    GNU General Public License v3.0 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 14
Project: MetroloPy   Author: nrc-cnrc   File: nummy.py    GNU General Public License v3.0 6 votes vote down vote up
def dof(self):
        """
        float, read-only

        Returns the number or degrees of freedom that the uncertainty of the 
        gummy is based on.  If `gummy.bayesian` is set to `False`, then the Welch-
        Satterthwaite approximation is used to calculate the effective number
        of degrees of freedom for gummys that result from an operation between
        two or more other gummys.  A version of the Welch-Satterthwaite 
        approximation that takes into account correlations is used here, see
        [R. Willink, Metrologia, 44, 340 (2007)].  If `gummy.bayesian` is `True`
        then gummys that are the result from an opertaion between other gummys
        will always have dof = float('inf').
        """
        if isinf(self._dof) and hasattr(self._dist,'dof'):
            dof = self._dist.dof
        else:
            dof = self._dof
        if dof < 1:
            # Occasionally correlations can result in a dof less than 1;
            # see the ummy._get_dof method.
            return 1
        return dof 
Example 15
Project: MetroloPy   Author: nrc-cnrc   File: nummy.py    GNU General Public License v3.0 6 votes vote down vote up
def _copy(s,r,formatting=True,tofloat=False):
        # copies attributes of s to r, called from ummy.copy()
        super(nummy,nummy)._copy(s,r,formatting=formatting,tofloat=tofloat)
        if isinstance(s,nummy):
            r._dist = s._dist
            if formatting:
                r.name = s.name
                r._cimethod = s._cimethod
            else:
                r.name = None
        else:
            r.name = None
            if s._u == 0:
                r._dist = r._x
                return
            dof = s._dof
            if isinf(dof):
                r._dist = NormalDist(s._x,s._u)
            else:
                if r._bayesian:
                    r._dist = TDist(s._x,s._u*(dof-2)/dof,dof)
                    r._dof = float('inf')
                else:
                    r._dist = TDist(s._x,s._u,dof) 
Example 16
Project: postgresql-doc-manager   Author: cureatr   File: postgresql_doc_manager.py    Apache License 2.0 6 votes vote down vote up
def transform_value(self, value):
        if isinstance(value, dict):
            return self.format_document(value)
        elif isinstance(value, list):
            return [self.transform_value(v) for v in value]
        elif isinstance(value, numbers.Number):
            if math.isnan(value):
                raise ValueError("nan")
            elif math.isinf(value):
                raise ValueError("inf")
            return value
        elif isinstance(value, bson.binary.Binary):
            return bson.json_util.default(value)
        elif compat.is_string(value) or isinstance(value, bool) or value is None:
            return value
        return bson.json_util.default(value) 
Example 17
Project: valohai-cli   Author: valohai   File: tabulate.py    MIT License 6 votes vote down vote up
def _isnumber(string):
    """
    >>> _isnumber("123.45")
    True
    >>> _isnumber("123")
    True
    >>> _isnumber("spam")
    False
    >>> _isnumber("123e45678")
    False
    >>> _isnumber("inf")
    True
    """
    if not _isconvertible(float, string):
        return False
    elif isinstance(string, (_text_type, _binary_type)) and (
            math.isinf(float(string)) or math.isnan(float(string))):
        return string.lower() in ['inf', '-inf', 'nan']
    return True 
Example 18
Project: pyblish-win   Author: pyblish   File: decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_float(cls, f):
        """Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        """
        if isinstance(f, (int, long)):        # handle integer inputs
            return cls(f)
        if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
            return cls(repr(f))
        if _math.copysign(1.0, f) == 1.0:
            sign = 0
        else:
            sign = 1
        n, d = abs(f).as_integer_ratio()
        k = d.bit_length() - 1
        result = _dec_from_triple(sign, str(n*5**k), -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 19
Project: pyblish-win   Author: pyblish   File: fractions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_float(cls, f):
        """Converts a finite float to a rational number, exactly.

        Beware that Fraction.from_float(0.3) != Fraction(3, 10).

        """
        if isinstance(f, numbers.Integral):
            return cls(f)
        elif not isinstance(f, float):
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
        if math.isnan(f) or math.isinf(f):
            raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
        return cls(*f.as_integer_ratio()) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_inf_from_str(self):
        self.assertTrue(isinf(float("inf")))
        self.assertTrue(isinf(float("+inf")))
        self.assertTrue(isinf(float("-inf")))
        self.assertTrue(isinf(float("infinity")))
        self.assertTrue(isinf(float("+infinity")))
        self.assertTrue(isinf(float("-infinity")))

        self.assertEqual(repr(float("inf")), "inf")
        self.assertEqual(repr(float("+inf")), "inf")
        self.assertEqual(repr(float("-inf")), "-inf")
        self.assertEqual(repr(float("infinity")), "inf")
        self.assertEqual(repr(float("+infinity")), "inf")
        self.assertEqual(repr(float("-infinity")), "-inf")

        self.assertEqual(repr(float("INF")), "inf")
        self.assertEqual(repr(float("+Inf")), "inf")
        self.assertEqual(repr(float("-iNF")), "-inf")
        self.assertEqual(repr(float("Infinity")), "inf")
        self.assertEqual(repr(float("+iNfInItY")), "inf")
        self.assertEqual(repr(float("-INFINITY")), "-inf")

        self.assertEqual(str(float("inf")), "inf")
        self.assertEqual(str(float("+inf")), "inf")
        self.assertEqual(str(float("-inf")), "-inf")
        self.assertEqual(str(float("infinity")), "inf")
        self.assertEqual(str(float("+infinity")), "inf")
        self.assertEqual(str(float("-infinity")), "-inf")

        self.assertRaises(ValueError, float, "info")
        self.assertRaises(ValueError, float, "+info")
        self.assertRaises(ValueError, float, "-info")
        self.assertRaises(ValueError, float, "in")
        self.assertRaises(ValueError, float, "+in")
        self.assertRaises(ValueError, float, "-in")
        self.assertRaises(ValueError, float, "infinit")
        self.assertRaises(ValueError, float, "+Infin")
        self.assertRaises(ValueError, float, "-INFI")
        self.assertRaises(ValueError, float, "infinitys") 
Example 21
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testCopysign(self):
        self.assertEqual(math.copysign(1, 42), 1.0)
        self.assertEqual(math.copysign(0., 42), 0.0)
        self.assertEqual(math.copysign(1., -42), -1.0)
        self.assertEqual(math.copysign(3, 0.), 3.0)
        self.assertEqual(math.copysign(4., -0.), -4.0)

        self.assertRaises(TypeError, math.copysign)
        # copysign should let us distinguish signs of zeros
        self.assertEqual(math.copysign(1., 0.), 1.)
        self.assertEqual(math.copysign(1., -0.), -1.)
        self.assertEqual(math.copysign(INF, 0.), INF)
        self.assertEqual(math.copysign(INF, -0.), NINF)
        self.assertEqual(math.copysign(NINF, 0.), INF)
        self.assertEqual(math.copysign(NINF, -0.), NINF)
        # and of infinities
        self.assertEqual(math.copysign(1., INF), 1.)
        self.assertEqual(math.copysign(1., NINF), -1.)
        self.assertEqual(math.copysign(INF, INF), INF)
        self.assertEqual(math.copysign(INF, NINF), NINF)
        self.assertEqual(math.copysign(NINF, INF), INF)
        self.assertEqual(math.copysign(NINF, NINF), NINF)
        self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
        self.assertTrue(math.isnan(math.copysign(NAN, INF)))
        self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
        self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
        # copysign(INF, NAN) may be INF or it may be NINF, since
        # we don't know whether the sign bit of NAN is set on any
        # given platform.
        self.assertTrue(math.isinf(math.copysign(INF, NAN)))
        # similarly, copysign(2., NAN) could be 2. or -2.
        self.assertEqual(abs(math.copysign(2., NAN)), 2.) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testIsinf(self):
        self.assertTrue(math.isinf(float("inf")))
        self.assertTrue(math.isinf(float("-inf")))
        self.assertTrue(math.isinf(1E400))
        self.assertTrue(math.isinf(-1E400))
        self.assertFalse(math.isinf(float("nan")))
        self.assertFalse(math.isinf(0.))
        self.assertFalse(math.isinf(1.))

    # RED_FLAG 16-Oct-2000 Tim
    # While 2.0 is more consistent about exceptions than previous releases, it
    # still fails this part of the test on some platforms.  For now, we only
    # *run* test_exceptions() in verbose mode, so that this isn't normally
    # tested. 
Example 23
Project: pyblish-win   Author: pyblish   File: test_cmath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_isinf(self):
        self.assertFalse(cmath.isinf(1))
        self.assertFalse(cmath.isinf(1j))
        self.assertFalse(cmath.isinf(NAN))
        self.assertTrue(cmath.isinf(INF))
        self.assertTrue(cmath.isinf(complex(INF, 0)))
        self.assertTrue(cmath.isinf(complex(0, INF)))
        self.assertTrue(cmath.isinf(complex(INF, INF)))
        self.assertTrue(cmath.isinf(complex(NAN, INF)))
        self.assertTrue(cmath.isinf(complex(INF, NAN))) 
Example 24
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: writer.py    MIT License 5 votes vote down vote up
def _format_value(v):
    if isinstance(v, bool):
        return 'true' if v else 'false'
    if isinstance(v, int) or isinstance(v, long):
        return unicode(v)
    if isinstance(v, float):
        if math.isnan(v) or math.isinf(v):
            raise ValueError("{0} is not a valid TOML value".format(v))
        else:
            return repr(v)
    elif isinstance(v, unicode) or isinstance(v, bytes):
        return _escape_string(v)
    elif isinstance(v, datetime.datetime):
        offs = v.utcoffset()
        offs = _total_seconds(offs) // 60 if offs is not None else 0

        if offs == 0:
            suffix = 'Z'
        else:
            if offs > 0:
                suffix = '+'
            else:
                suffix = '-'
                offs = -offs
            suffix = '{0}{1:.02}{2:.02}'.format(suffix, offs // 60, offs % 60)

        if v.microsecond:
            return v.strftime('%Y-%m-%dT%H:%M:%S.%f') + suffix
        else:
            return v.strftime('%Y-%m-%dT%H:%M:%S') + suffix
    elif isinstance(v, list):
        return _format_list(v)
    else:
        raise RuntimeError(v) 
Example 25
Project: DOTA_models   Author: ringringyi   File: wiki_data.py    Apache License 2.0 5 votes vote down vote up
def is_nan_or_inf(number):
  return math.isnan(number) or math.isinf(number) 
Example 26
Project: DOTA_models   Author: ringringyi   File: accountant.py    Apache License 2.0 5 votes vote down vote up
def _compute_eps(self, log_moments, delta):
    min_eps = float("inf")
    for moment_order, log_moment in log_moments:
      if math.isinf(log_moment) or math.isnan(log_moment):
        sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
        continue
      min_eps = min(min_eps, (log_moment - math.log(delta)) / moment_order)
    return min_eps 
Example 27
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    Apache License 2.0 5 votes vote down vote up
def _to_np_float64(v):
  if math.isnan(v) or math.isinf(v):
    return np.inf
  return np.float64(v)


######################
# FLOAT64 ARITHMETIC #
###################### 
Example 28
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    Apache License 2.0 5 votes vote down vote up
def compute_log_moment(q, sigma, steps, lmbd, verify=False, verbose=False):
  """Compute the log moment of Gaussian mechanism for given parameters.

  Args:
    q: the sampling ratio.
    sigma: the noise sigma.
    steps: the number of steps.
    lmbd: the moment order.
    verify: if False, only compute the symbolic version. If True, computes
      both symbolic and numerical solutions and verifies the results match.
    verbose: if True, print out debug information.
  Returns:
    the log moment with type np.float64, could be np.inf.
  """
  moment = compute_a(sigma, q, lmbd, verbose=verbose)
  if verify:
    mp.dps = 50
    moment_a_mp = compute_a_mp(sigma, q, lmbd, verbose=verbose)
    moment_b_mp = compute_b_mp(sigma, q, lmbd, verbose=verbose)
    np.testing.assert_allclose(moment, moment_a_mp, rtol=1e-10)
    if not np.isinf(moment_a_mp):
      # The following test fails for (1, np.inf)!
      np.testing.assert_array_less(moment_b_mp, moment_a_mp)
  if np.isinf(moment):
    return np.inf
  else:
    return np.log(moment) * steps 
Example 29
Project: bigquerylayers   Author: smandaric   File: json_format.py    GNU General Public License v3.0 5 votes vote down vote up
def _FieldToJsonObject(self, field, value):
    """Converts field value according to Proto3 JSON Specification."""
    if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
      return self._MessageToJsonObject(value)
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
      if self.use_integers_for_enums:
        return value
      enum_value = field.enum_type.values_by_number.get(value, None)
      if enum_value is not None:
        return enum_value.name
      else:
        if field.file.syntax == 'proto3':
          return value
        raise SerializeToJsonError('Enum field contains an integer value '
                                   'which can not mapped to an enum value.')
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
      if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
        # Use base64 Data encoding for bytes
        return base64.b64encode(value).decode('utf-8')
      else:
        return value
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
      return bool(value)
    elif field.cpp_type in _INT64_TYPES:
      return str(value)
    elif field.cpp_type in _FLOAT_TYPES:
      if math.isinf(value):
        if value < 0.0:
          return _NEG_INFINITY
        else:
          return _INFINITY
      if math.isnan(value):
        return _NAN
    return value 
Example 30
Project: fastpair   Author: carsonfarmer   File: test_fastpair.py    MIT License 5 votes vote down vote up
def all_close(s, t, tol=1e-8):
    # Ignores inf and nan values...
    return all(abs(a - b) < tol for a, b in zip(s, t)
               if not isinf(a) and not isinf(b) and
                  not isnan(a) and not isnan(b)) 
Example 31
Project: deb-python-cassandra-driver   Author: openstack   File: encoder.py    Apache License 2.0 5 votes vote down vote up
def cql_encode_float(self, val):
        """
        Encode floats using repr to preserve precision
        """
        if math.isinf(val):
            return 'Infinity' if val > 0 else '-Infinity'
        elif math.isnan(val):
            return 'NaN'
        else:
            return repr(val) 
Example 32
Project: silence-extractor   Author: wciesialka   File: extractor.py    MIT License 5 votes vote down vote up
def translate(value, from_min, from_max, to_min, to_max):
    from_range = from_max - from_min
    to_range = to_max - to_min

    left_mapped = float(value - from_min) / float(from_range)

    translated = to_min + (left_mapped * to_range)

    if translated < 0.0001 or math.isinf(translated):
        return 0
    else:
        return translated 
Example 33
Project: jawfish   Author: war-and-code   File: decimal.py    MIT License 5 votes vote down vote up
def from_float(cls, f):
        """Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        """
        if isinstance(f, int):                # handle integer inputs
            return cls(f)
        if not isinstance(f, float):
            raise TypeError("argument must be int or float.")
        if _math.isinf(f) or _math.isnan(f):
            return cls(repr(f))
        if _math.copysign(1.0, f) == 1.0:
            sign = 0
        else:
            sign = 1
        n, d = abs(f).as_integer_ratio()
        k = d.bit_length() - 1
        result = _dec_from_triple(sign, str(n*5**k), -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 34
Project: jawfish   Author: war-and-code   File: _struct.py    MIT License 5 votes vote down vote up
def isinf(x):
    return x != 0.0 and x / 2 == x 
Example 35
Project: python-esppy   Author: sassoftware   File: jmp_score.py    Apache License 2.0 5 votes vote down vote up
def is_missing(x):
    return math.isnan(x) or math.isinf(x) or x is None 
Example 36
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 5 votes vote down vote up
def shortest_path_distance(self, other, simulate_root=False):
        """
        Returns the distance of the shortest path linking the two synsets (if
        one exists). For each synset, all the ancestor nodes and their
        distances are recorded and compared. The ancestor node common to both
        synsets that can be reached with the minimum number of traversals is
        used. If no ancestor nodes are common, None is returned. If a node is
        compared with itself 0 is returned.

        :type other: Synset
        :param other: The Synset to which the shortest path will be found.
        :return: The number of edges in the shortest path connecting the two
            nodes, or None if no path exists.
        """

        if self == other:
            return 0

        dist_dict1 = self._shortest_hypernym_paths(simulate_root)
        dist_dict2 = other._shortest_hypernym_paths(simulate_root)

        # For each ancestor synset common to both subject synsets, find the
        # connecting path length. Return the shortest of these.

        inf = float('inf')
        path_distance = inf
        for synset, d1 in iteritems(dist_dict1):
            d2 = dist_dict2.get(synset, inf)
            path_distance = min(path_distance, d1 + d2)

        return None if math.isinf(path_distance) else path_distance 
Example 37
Project: kivy-smoothie-host   Author: wolfmanjm   File: dial-gauge.py    GNU General Public License v3.0 5 votes vote down vote up
def value_to_angle(self, v):
        ''' convert the given value to the angle required for the scale '''
        if math.isnan(v) or math.isinf(v) or v < self.scale_min : v= self.scale_min
        return -180.0+self.angle_start+self.angle_offset + ((self.angle_stop-self.angle_start) * ((float(v)-self.scale_min) / (self.scale_max-self.scale_min))) 
Example 38
Project: JukeBox   Author: gauravsarkar97   File: writer.py    MIT License 5 votes vote down vote up
def _format_value(v):
    if isinstance(v, bool):
        return 'true' if v else 'false'
    if isinstance(v, int) or isinstance(v, long):
        return unicode(v)
    if isinstance(v, float):
        if math.isnan(v) or math.isinf(v):
            raise ValueError("{0} is not a valid TOML value".format(v))
        else:
            return repr(v)
    elif isinstance(v, unicode) or isinstance(v, bytes):
        return _escape_string(v)
    elif isinstance(v, datetime.datetime):
        offs = v.utcoffset()
        offs = _total_seconds(offs) // 60 if offs is not None else 0

        if offs == 0:
            suffix = 'Z'
        else:
            if offs > 0:
                suffix = '+'
            else:
                suffix = '-'
                offs = -offs
            suffix = '{0}{1:.02}{2:.02}'.format(suffix, offs // 60, offs % 60)

        if v.microsecond:
            return v.strftime('%Y-%m-%dT%H:%M:%S.%f') + suffix
        else:
            return v.strftime('%Y-%m-%dT%H:%M:%S') + suffix
    elif isinstance(v, list):
        return _format_list(v)
    else:
        raise RuntimeError(v) 
Example 39
Project: OpenBottle   Author: xiaozhuchacha   File: wordnet.py    MIT License 5 votes vote down vote up
def shortest_path_distance(self, other, simulate_root=False):
        """
        Returns the distance of the shortest path linking the two synsets (if
        one exists). For each synset, all the ancestor nodes and their
        distances are recorded and compared. The ancestor node common to both
        synsets that can be reached with the minimum number of traversals is
        used. If no ancestor nodes are common, None is returned. If a node is
        compared with itself 0 is returned.

        :type other: Synset
        :param other: The Synset to which the shortest path will be found.
        :return: The number of edges in the shortest path connecting the two
            nodes, or None if no path exists.
        """

        if self == other:
            return 0

        dist_dict1 = self._shortest_hypernym_paths(simulate_root)
        dist_dict2 = other._shortest_hypernym_paths(simulate_root)

        # For each ancestor synset common to both subject synsets, find the
        # connecting path length. Return the shortest of these.

        inf = float('inf')
        path_distance = inf
        for synset, d1 in iteritems(dist_dict1):
            d2 = dist_dict2.get(synset, inf)
            path_distance = min(path_distance, d1 + d2)

        return None if math.isinf(path_distance) else path_distance 
Example 40
Project: OpenBottle   Author: xiaozhuchacha   File: wordnet.py    MIT License 5 votes vote down vote up
def shortest_path_distance(self, other, simulate_root=False):
        """
        Returns the distance of the shortest path linking the two synsets (if
        one exists). For each synset, all the ancestor nodes and their
        distances are recorded and compared. The ancestor node common to both
        synsets that can be reached with the minimum number of traversals is
        used. If no ancestor nodes are common, None is returned. If a node is
        compared with itself 0 is returned.

        :type other: Synset
        :param other: The Synset to which the shortest path will be found.
        :return: The number of edges in the shortest path connecting the two
            nodes, or None if no path exists.
        """

        if self == other:
            return 0

        dist_dict1 = self._shortest_hypernym_paths(simulate_root)
        dist_dict2 = other._shortest_hypernym_paths(simulate_root)

        # For each ancestor synset common to both subject synsets, find the
        # connecting path length. Return the shortest of these.

        inf = float('inf')
        path_distance = inf
        for synset, d1 in iteritems(dist_dict1):
            d2 = dist_dict2.get(synset, inf)
            path_distance = min(path_distance, d1 + d2)

        return None if math.isinf(path_distance) else path_distance 
Example 41
Project: RouteOptimization   Author: andre-le   File: json_format.py    MIT License 5 votes vote down vote up
def _FieldToJsonObject(self, field, value):
    """Converts field value according to Proto3 JSON Specification."""
    if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
      return self._MessageToJsonObject(value)
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
      enum_value = field.enum_type.values_by_number.get(value, None)
      if enum_value is not None:
        return enum_value.name
      else:
        raise SerializeToJsonError('Enum field contains an integer value '
                                   'which can not mapped to an enum value.')
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
      if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
        # Use base64 Data encoding for bytes
        return base64.b64encode(value).decode('utf-8')
      else:
        return value
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
      return bool(value)
    elif field.cpp_type in _INT64_TYPES:
      return str(value)
    elif field.cpp_type in _FLOAT_TYPES:
      if math.isinf(value):
        if value < 0.0:
          return _NEG_INFINITY
        else:
          return _INFINITY
      if math.isnan(value):
        return _NAN
    return value 
Example 42
Project: RouteOptimization   Author: andre-le   File: compat.py    MIT License 5 votes vote down vote up
def isfinite(x):
        return not isinf(x) and not isnan(x) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testCopysign(self):
        self.assertEqual(math.copysign(1, 42), 1.0)
        self.assertEqual(math.copysign(0., 42), 0.0)
        self.assertEqual(math.copysign(1., -42), -1.0)
        self.assertEqual(math.copysign(3, 0.), 3.0)
        self.assertEqual(math.copysign(4., -0.), -4.0)

        self.assertRaises(TypeError, math.copysign)
        # copysign should let us distinguish signs of zeros
        self.assertEqual(math.copysign(1., 0.), 1.)
        self.assertEqual(math.copysign(1., -0.), -1.)
        self.assertEqual(math.copysign(INF, 0.), INF)
        self.assertEqual(math.copysign(INF, -0.), NINF)
        self.assertEqual(math.copysign(NINF, 0.), INF)
        self.assertEqual(math.copysign(NINF, -0.), NINF)
        # and of infinities
        self.assertEqual(math.copysign(1., INF), 1.)
        self.assertEqual(math.copysign(1., NINF), -1.)
        self.assertEqual(math.copysign(INF, INF), INF)
        self.assertEqual(math.copysign(INF, NINF), NINF)
        self.assertEqual(math.copysign(NINF, INF), INF)
        self.assertEqual(math.copysign(NINF, NINF), NINF)
        self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
        self.assertTrue(math.isnan(math.copysign(NAN, INF)))
        self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
        self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
        # copysign(INF, NAN) may be INF or it may be NINF, since
        # we don't know whether the sign bit of NAN is set on any
        # given platform.
        self.assertTrue(math.isinf(math.copysign(INF, NAN)))
        # similarly, copysign(2., NAN) could be 2. or -2.
        self.assertEqual(abs(math.copysign(2., NAN)), 2.) 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testIsinf(self):
        self.assertTrue(math.isinf(float("inf")))
        self.assertTrue(math.isinf(float("-inf")))
        self.assertTrue(math.isinf(1E400))
        self.assertTrue(math.isinf(-1E400))
        self.assertFalse(math.isinf(float("nan")))
        self.assertFalse(math.isinf(0.))
        self.assertFalse(math.isinf(1.)) 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def test_inf_constant(self):
        self.assertTrue(math.isinf(math.inf))
        self.assertGreater(math.inf, 0.0)
        self.assertEqual(math.inf, float("inf"))
        self.assertEqual(-math.inf, float("-inf"))

    # RED_FLAG 16-Oct-2000 Tim
    # While 2.0 is more consistent about exceptions than previous releases, it
    # still fails this part of the test on some platforms.  For now, we only
    # *run* test_exceptions() in verbose mode, so that this isn't normally
    # tested. 
Example 46
Project: NiujiaoDebugger   Author: MrSrc   File: test_statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def test_inf(self):
        INF = float("INF")
        class MyFloat(float):
            pass
        class MyDecimal(Decimal):
            pass
        for inf in (INF, -INF):
            for type_ in (float, MyFloat, Decimal, MyDecimal):
                x = type_(inf)
                ratio = statistics._exact_ratio(x)
                self.assertEqual(ratio, (x, None))
                self.assertEqual(type(ratio[0]), type_)
                self.assertTrue(math.isinf(ratio[0])) 
Example 47
Project: NiujiaoDebugger   Author: MrSrc   File: test_statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def test_inf(self):
        # Test mean with infinities.
        raw = [1, 3, 5, 7, 9]  # Use only ints, to avoid TypeError later.
        for kind in (float, Decimal):
            for sign in (1, -1):
                inf = kind("inf")*sign
                data = raw + [inf]
                result = self.func(data)
                self.assertTrue(math.isinf(result))
                self.assertEqual(result, inf) 
Example 48
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_isinf(self):
        self.assertFalse(cmath.isinf(1))
        self.assertFalse(cmath.isinf(1j))
        self.assertFalse(cmath.isinf(NAN))
        self.assertTrue(cmath.isinf(INF))
        self.assertTrue(cmath.isinf(complex(INF, 0)))
        self.assertTrue(cmath.isinf(complex(0, INF)))
        self.assertTrue(cmath.isinf(complex(INF, INF)))
        self.assertTrue(cmath.isinf(complex(NAN, INF)))
        self.assertTrue(cmath.isinf(complex(INF, NAN))) 
Example 49
Project: Health-Checker   Author: KriAga   File: writer.py    MIT License 5 votes vote down vote up
def _format_value(v):
    if isinstance(v, bool):
        return 'true' if v else 'false'
    if isinstance(v, int) or isinstance(v, long):
        return unicode(v)
    if isinstance(v, float):
        if math.isnan(v) or math.isinf(v):
            raise ValueError("{0} is not a valid TOML value".format(v))
        else:
            return repr(v)
    elif isinstance(v, unicode) or isinstance(v, bytes):
        return _escape_string(v)
    elif isinstance(v, datetime.datetime):
        offs = v.utcoffset()
        offs = _total_seconds(offs) // 60 if offs is not None else 0

        if offs == 0:
            suffix = 'Z'
        else:
            if offs > 0:
                suffix = '+'
            else:
                suffix = '-'
                offs = -offs
            suffix = '{0}{1:.02}{2:.02}'.format(suffix, offs // 60, offs % 60)

        if v.microsecond:
            return v.strftime('%Y-%m-%dT%H:%M:%S.%f') + suffix
        else:
            return v.strftime('%Y-%m-%dT%H:%M:%S') + suffix
    elif isinstance(v, list):
        return _format_list(v)
    else:
        raise RuntimeError(v) 
Example 50
Project: Health-Checker   Author: KriAga   File: writer.py    MIT License 5 votes vote down vote up
def _format_value(v):
    if isinstance(v, bool):
        return 'true' if v else 'false'
    if isinstance(v, int) or isinstance(v, long):
        return unicode(v)
    if isinstance(v, float):
        if math.isnan(v) or math.isinf(v):
            raise ValueError("{0} is not a valid TOML value".format(v))
        else:
            return repr(v)
    elif isinstance(v, unicode) or isinstance(v, bytes):
        return _escape_string(v)
    elif isinstance(v, datetime.datetime):
        offs = v.utcoffset()
        offs = _total_seconds(offs) // 60 if offs is not None else 0

        if offs == 0:
            suffix = 'Z'
        else:
            if offs > 0:
                suffix = '+'
            else:
                suffix = '-'
                offs = -offs
            suffix = '{0}{1:.02}{2:.02}'.format(suffix, offs // 60, offs % 60)

        if v.microsecond:
            return v.strftime('%Y-%m-%dT%H:%M:%S.%f') + suffix
        else:
            return v.strftime('%Y-%m-%dT%H:%M:%S') + suffix
    elif isinstance(v, list):
        return _format_list(v)
    else:
        raise RuntimeError(v) 
Example 51
Project: Health-Checker   Author: KriAga   File: wordnet.py    MIT License 5 votes vote down vote up
def shortest_path_distance(self, other, simulate_root=False):
        """
        Returns the distance of the shortest path linking the two synsets (if
        one exists). For each synset, all the ancestor nodes and their
        distances are recorded and compared. The ancestor node common to both
        synsets that can be reached with the minimum number of traversals is
        used. If no ancestor nodes are common, None is returned. If a node is
        compared with itself 0 is returned.

        :type other: Synset
        :param other: The Synset to which the shortest path will be found.
        :return: The number of edges in the shortest path connecting the two
            nodes, or None if no path exists.
        """

        if self == other:
            return 0

        dist_dict1 = self._shortest_hypernym_paths(simulate_root)
        dist_dict2 = other._shortest_hypernym_paths(simulate_root)

        # For each ancestor synset common to both subject synsets, find the
        # connecting path length. Return the shortest of these.

        inf = float('inf')
        path_distance = inf
        for synset, d1 in iteritems(dist_dict1):
            d2 = dist_dict2.get(synset, inf)
            path_distance = min(path_distance, d1 + d2)

        return None if math.isinf(path_distance) else path_distance 
Example 52
Project: MetroloPy   Author: nrc-cnrc   File: ummy.py    GNU General Public License v3.0 5 votes vote down vote up
def _add(self,b):
        if not isinstance(b,ummy):
            return type(self)(self._x + b,self._u,dof=self._ref,utype=self._refs)
    
        c = self.correlation(b)
        x = self._x + b._x
        u = _combu(self._u,b._u,c)
        
        if u == 0:
            return type(b)(x)
        
        if self._u == 0:
            return type(b)(x,u,dof=b._ref,utype=b._refs)
        
        if b._u == 0:
            return type(b)(x,u,dof=self._ref,utype=self._refs)
        
        dua = self._u/u
        dub = b._u/u
        if not isinf(self._ref.dof) or not isinf(b._ref.dof):
            dof = self._get_dof(self._dof,b._dof,dua,dub,c)
        else:
            dof = float('inf')
            
        r = type(b)(x,u=u,dof=dof)
    
        r._combc(self,b,dua,dub,c)
        
        return r 
Example 53
Project: MetroloPy   Author: nrc-cnrc   File: ummy.py    GNU General Public License v3.0 5 votes vote down vote up
def _sub(self,b):           
        if not isinstance(b,ummy):
            return type(self)(self._x - b,self._u,dof=self._ref,utype=self._refs)
            
        c = self.correlation(b)
        x = self._x - b._x
        u = _combu(self._u,-b._u,c)
            
        if u == 0:
            return type(b)(x)
        
        if self._u == 0:
            return type(b)(x,u,dof=b._ref,utype=-b._refs)
        
        if b._u == 0:
            return type(b)(x,u,dof=self._ref,utype=self._refs)
        
        dua = self._u/u
        dub = -b._u/u
        if not isinf(self._ref.dof) or not isinf(b._ref.dof):
            dof = self._get_dof(self._dof,b._dof,dua,dub,c)
        else:
            dof = float('inf')
        
        r = type(b)(x,u=u,dof=dof)
        
        r._combc(self,b,dua,dub,c)

        return r 
Example 54
Project: MetroloPy   Author: nrc-cnrc   File: ummy.py    GNU General Public License v3.0 5 votes vote down vote up
def _mul(self,b):
        if not isinstance(b,ummy):
            refs = -self._refs if b < 0 else self._refs
            return type(self)(self._x*b,abs(self._u*b),dof=self._ref,utype=refs)
                                        
        c = self.correlation(b)
        x = self._x*b._x
        dua = b._x*self._u
        dub = self._x*b._u
        u = _combu(dua,dub,c)
            
        if u == 0:
            return type(b)(x)
        
        if self._u == 0:
            refs = -b._refs if self._x < 0 else b._refs
            return type(b)(x,u,dof=b._ref,utype=refs)
        
        if b._u == 0:
            refs = -self._refs if b._x < 0 else self._refs
            return type(b)(x,u,dof=self._ref,utype=refs)
        
        dua = dua/u
        dub = dub/u
        if not isinf(self._ref.dof) or not isinf(b._ref.dof):
            dof = self._get_dof(self._dof,b._dof,dua,dub,c)
        else:
            dof = float('inf')
            
        r = type(b)(x,u=u,dof=dof)
        
        r._combc(self,b,dua,dub,c)

        return r 
Example 55
Project: MetroloPy   Author: nrc-cnrc   File: gummy.py    GNU General Public License v3.0 5 votes vote down vote up
def _dof_to_str(dof,fmt=None):
        if isinf(dof) or dof > 99:
            if fmt == 'html':
                return '&infin;'
            if fmt == 'latex':
                return r'\infty'
            if fmt == 'ascii':
                return 'inf'
            return '\u221E'
            
        if isinstance(dof,Integral):
            return str(dof)
        return '{:.1f}'.format(dof) 
Example 56
Project: hypothesis-couchdb   Author: kxepal   File: test_json.py    Apache License 2.0 5 votes vote down vote up
def check_number(self, value):
        self.assertIsInstance(value, (int, float))
        self.assertFalse(math.isinf(value))
        self.assertFalse(math.isnan(value)) 
Example 57
Project: deoplete-asm   Author: deoplete-plugins   File: json_format.py    MIT License 5 votes vote down vote up
def _FieldToJsonObject(self, field, value):
    """Converts field value according to Proto3 JSON Specification."""
    if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
      return self._MessageToJsonObject(value)
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
      enum_value = field.enum_type.values_by_number.get(value, None)
      if enum_value is not None:
        return enum_value.name
      else:
        raise SerializeToJsonError('Enum field contains an integer value '
                                   'which can not mapped to an enum value.')
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
      if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
        # Use base64 Data encoding for bytes
        return base64.b64encode(value).decode('utf-8')
      else:
        return value
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
      return bool(value)
    elif field.cpp_type in _INT64_TYPES:
      return str(value)
    elif field.cpp_type in _FLOAT_TYPES:
      if math.isinf(value):
        if value < 0.0:
          return _NEG_INFINITY
        else:
          return _INFINITY
      if math.isnan(value):
        return _NAN
    return value 
Example 58
Project: Alexa-Ecovacs   Author: EtienneMD   File: python_api.py    MIT License 5 votes vote down vote up
def __repr__(self):
        """
        Return a string communicating both the expected value and the tolerance
        for the comparison being made, e.g. '1.0 +- 1e-6'.  Use the unicode
        plus/minus symbol if this is python3 (it's too hard to get right for
        python2).
        """
        if isinstance(self.expected, complex):
            return str(self.expected)

        # Infinities aren't compared using tolerances, so don't show a
        # tolerance.
        if math.isinf(self.expected):
            return str(self.expected)

        # If a sensible tolerance can't be calculated, self.tolerance will
        # raise a ValueError.  In this case, display '???'.
        try:
            vetted_tolerance = '{:.1e}'.format(self.tolerance)
        except ValueError:
            vetted_tolerance = '???'

        if sys.version_info[0] == 2:
            return '{0} +- {1}'.format(self.expected, vetted_tolerance)
        else:
            return u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance) 
Example 59
Project: Alexa-Ecovacs   Author: EtienneMD   File: python_api.py    MIT License 5 votes vote down vote up
def __eq__(self, actual):
        """
        Return true if the given value is equal to the expected value within
        the pre-specified tolerance.
        """

        # Short-circuit exact equality.
        if actual == self.expected:
            return True

        # Allow the user to control whether NaNs are considered equal to each
        # other or not.  The abs() calls are for compatibility with complex
        # numbers.
        if math.isnan(abs(self.expected)):
            return self.nan_ok and math.isnan(abs(actual))

        # Infinity shouldn't be approximately equal to anything but itself, but
        # if there's a relative tolerance, it will be infinite and infinity
        # will seem approximately equal to everything.  The equal-to-itself
        # case would have been short circuited above, so here we can just
        # return false if the expected value is infinite.  The abs() call is
        # for compatibility with complex numbers.
        if math.isinf(abs(self.expected)):
            return False

        # Return true if the two numbers are within the tolerance.
        return abs(self.expected - actual) <= self.tolerance 
Example 60
Project: chord-sequence-chooser   Author: bwetherfield   File: writer.py    MIT License 5 votes vote down vote up
def _format_value(v):
    if isinstance(v, bool):
        return 'true' if v else 'false'
    if isinstance(v, int) or isinstance(v, long):
        return unicode(v)
    if isinstance(v, float):
        if math.isnan(v) or math.isinf(v):
            raise ValueError("{0} is not a valid TOML value".format(v))
        else:
            return repr(v)
    elif isinstance(v, unicode) or isinstance(v, bytes):
        return _escape_string(v)
    elif isinstance(v, datetime.datetime):
        offs = v.utcoffset()
        offs = _total_seconds(offs) // 60 if offs is not None else 0

        if offs == 0:
            suffix = 'Z'
        else:
            if offs > 0:
                suffix = '+'
            else:
                suffix = '-'
                offs = -offs
            suffix = '{0}{1:.02}{2:.02}'.format(suffix, offs // 60, offs % 60)

        if v.microsecond:
            return v.strftime('%Y-%m-%dT%H:%M:%S.%f') + suffix
        else:
            return v.strftime('%Y-%m-%dT%H:%M:%S') + suffix
    elif isinstance(v, list):
        return _format_list(v)
    else:
        raise RuntimeError(v) 
Example 61
Project: UnsupervisedMT-TensorFlow   Author: lovecambi   File: trainer.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_stats(stats, info, global_step, steps_per_stats, log_f):
    """Update info and check for overflow."""
    # Update info
    info["avg_step_time"] = stats["step_time"] / steps_per_stats
    info["avg_train_ae_loss"] = stats["ae_loss"] / steps_per_stats
    info["avg_train_bt_loss"] = stats["bt_loss"] / steps_per_stats

    is_overflow = False
    for avg_loss in [info["avg_train_ae_loss"], info["avg_train_bt_loss"]]:
        if math.isnan(avg_loss) or math.isinf(avg_loss) or avg_loss > 1e20:
            misc_utils.print_out("  step %d overflow loss, stop early" % global_step, log_f)
            is_overflow = True
            break
    return is_overflow 
Example 62
Project: sym   Author: bjodah   File: test_Lambdify.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_Lambdify_invalid_args(key):
    se = Backend(key)
    x = se.Symbol('x')
    log = se.Lambdify([x], [se.log(x)])
    div = se.Lambdify([x], [1/x])
    assert math.isnan(log([-1])[0])
    assert math.isinf(-log([0])[0])
    assert math.isinf(div([0])[0])
    assert math.isinf(-div([-0])[0]) 
Example 63
Project: aetros-cli   Author: aetros   File: KerasCallback.py    MIT License 5 votes vote down vote up
def filter_invalid_json_values(self, dict):
        for k, v in six.iteritems(dict):
            if isinstance(v, (np.ndarray, np.generic)):
                dict[k] = v.tolist()
            if math.isnan(v) or math.isinf(v):
                dict[k] = -1 
Example 64
Project: benchexec   Author: sosy-lab   File: columns.py    Apache License 2.0 5 votes vote down vote up
def _get_significant_digits(value):
    if isnan(float(value)) or isinf(float(value)):
        return 0

    # Regular expression returns multiple groups:
    #
    # Group GROUP_SIGN: Optional sign of value
    # Group GROUP_INT_PART: Digits in front of decimal point
    # Group GROUP_DEC_PART: Optional decimal point and digits after it
    # Group GROUP_SIG_DEC_DIGITS: Digits after decimal point, starting at the first value not 0
    # Group GROUP_EXP: Optional exponent part (e.g. 'e-5')
    # Group GROUP_EXP_SIGN: Optional sign of exponent part
    # Group GROUP_EXP_VALUE: Value of exponent part (e.g. '5' for 'e-5')
    # Use these groups to compute the number of zeros that have to be added to the current number's
    # decimal positions.
    match = REGEX_MEASURE.match(value)

    if int(match.group(GROUP_INT_PART)) == 0 and float(value) != 0:
        sig_digits = len(match.group(GROUP_SIG_DEC_PART))

    else:
        if float(value) != 0:
            sig_digits = len(match.group(GROUP_INT_PART))
        else:
            # If the value consists of only zeros, do not count the 0 in front of the decimal
            sig_digits = 0
        if match.group(GROUP_DEC_PART):
            sig_digits += len(match.group(GROUP_DEC_PART)) - 1  # -1 for decimal point

    return sig_digits 
Example 65
Project: SherpaHighLevel   Author: Shedino   File: fgFDM.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set(self, varname, value, idx=0, units=None):
        '''set a variable value'''
        if not varname in self.mapping.vars:
            raise fgFDMError('Unknown variable %s' % varname)
        if idx >= self.mapping.vars[varname].arraylength:
            raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % (
                varname, idx, self.mapping.vars[varname].arraylength))
        if units:
            value = self.convert(value, units, self.mapping.vars[varname].units)
        # avoid range errors when packing into 4 byte floats
        if math.isinf(value) or math.isnan(value) or math.fabs(value) > 3.4e38:
            value = 0
        self.values[self.mapping.vars[varname].index + idx] = value 
Example 66
Project: pyblish-win   Author: pyblish   File: test_cmath.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
                           msg=None):
        """Fail if the two floating-point numbers are not almost equal.

        Determine whether floating-point values a and b are equal to within
        a (small) rounding error.  The default values for rel_err and
        abs_err are chosen to be suitable for platforms where a float is
        represented by an IEEE 754 double.  They allow an error of between
        9 and 19 ulps.
        """

        # special values testing
        if math.isnan(a):
            if math.isnan(b):
                return
            self.fail(msg or '{!r} should be nan'.format(b))

        if math.isinf(a):
            if a == b:
                return
            self.fail(msg or 'finite result where infinity expected: '
                      'expected {!r}, got {!r}'.format(a, b))

        # if both a and b are zero, check whether they have the same sign
        # (in theory there are examples where it would be legitimate for a
        # and b to have opposite signs; in practice these hardly ever
        # occur).
        if not a and not b:
            if math.copysign(1., a) != math.copysign(1., b):
                self.fail(msg or 'zero has wrong sign: expected {!r}, '
                          'got {!r}'.format(a, b))

        # if a-b overflows, or b is infinite, return False.  Again, in
        # theory there are examples where a is within a few ulps of the
        # max representable float, and then b could legitimately be
        # infinite.  In practice these examples are rare.
        try:
            absolute_error = abs(b-a)
        except OverflowError:
            pass
        else:
            # test passes if either the absolute error or the relative
            # error is sufficiently small.  The defaults amount to an
            # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
            # machine.
            if absolute_error <= max(abs_err, rel_err * abs(a)):
                return
        self.fail(msg or
                  '{!r} and {!r} are not sufficiently close'.format(a, b)) 
Example 67
Project: smartformat   Author: what-studio   File: local.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def format_field_by_match(self, value, match):
        """Formats a field by a Regex match of the format spec pattern."""
        groups = match.groups()
        fill, align, sign, sharp, zero, width, comma, prec, type_ = groups
        if not comma and not prec and type_ not in list('fF%'):
            return None
        if math.isnan(value) or math.isinf(value):
            return None
        locale = self.numeric_locale
        # Format number value.
        prefix = get_prefix(sign)
        if type_ == 'd':
            if prec is not None:
                raise ValueError('precision not allowed in '
                                 'integer format specifier')
            string = format_number(value, 0, prefix, locale)
        elif type_ in 'fF%':
            format_ = format_percent if type_ == '%' else format_number
            string = format_(value, int(prec or DEFAULT_PREC), prefix, locale)
        else:
            # Don't handle otherwise.
            return None
        if not comma:
            # Formatted number always contains group symbols.
            # Remove the symbols if not required.
            string = remove_group_symbols(string, locale)
        if not (fill or align or zero or width):
            return string
        # Fix a layout.
        spec = ''.join([fill or u'', align or u'>',
                        zero or u'', width or u''])
        return format(string, spec)


# f = LocalFormatter('hi_IN')
# print(f.format(u'{0:^020,.5f}', 123456789.123456789))
# print(str.format(u'{0:^020,.5f}', 123456789.123456789))
# print(f.format(u'{0:^+020,.5f}', 123456789.123456789))
# print(str.format(u'{0:^+020,.5f}', 123456789.123456789))
# print(f.format(u'{0:^010,.5f}', float('inf')))
# print(str.format(u'{0:^010,.5f}', float('inf')))
# print(f.format(u'{0:.10%}', 123456))
# print(f.format(u'{0:,.10%}', 123456)) 
Example 68
Project: Repobot   Author: Desgard   File: newround.py    MIT License 4 votes vote down vote up
def from_float_26(f):
    """Converts a float to a decimal number, exactly.

    Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
    Since 0.1 is not exactly representable in binary floating point, the
    value is stored as the nearest representable value which is
    0x1.999999999999ap-4.  The exact equivalent of the value in decimal
    is 0.1000000000000000055511151231257827021181583404541015625.

    >>> Decimal.from_float(0.1)
    Decimal('0.1000000000000000055511151231257827021181583404541015625')
    >>> Decimal.from_float(float('nan'))
    Decimal('NaN')
    >>> Decimal.from_float(float('inf'))
    Decimal('Infinity')
    >>> Decimal.from_float(-float('inf'))
    Decimal('-Infinity')
    >>> Decimal.from_float(-0.0)
    Decimal('-0')

    """
    import math as _math
    from decimal import _dec_from_triple    # only available on Py2.6 and Py2.7 (not 3.3)

    if isinstance(f, (int, long)):        # handle integer inputs
        return Decimal(f)
    if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
        return Decimal(repr(f))
    if _math.copysign(1.0, f) == 1.0:
        sign = 0
    else:
        sign = 1
    n, d = abs(f).as_integer_ratio()
    # int.bit_length() method doesn't exist on Py2.6:
    def bit_length(d):
        if d != 0:
            return len(bin(abs(d))) - 2
        else:
            return 0
    k = bit_length(d) - 1
    result = _dec_from_triple(sign, str(n*5**k), -k)
    return result 
Example 69
Project: kivy-smoothie-host   Author: wolfmanjm   File: extruder_widget.py    GNU General Public License v3.0 4 votes vote down vote up
def update_temp(self, temperatures):
        ''' called to update the temperature display'''
        if self.temp_changed:
            # This allows the setpoint to update on smoothie before using it to turn the heater on/off again
            self.temp_changed = False
            return

        for type in temperatures:
            temp, setpoint = temperatures[type]
            self.ids.graph_view.update_temperature(type, temp, setpoint)

            if type == 'bed':
                if math.isinf(temp):
                    self.bed_dg.value = float('inf')
                    continue
                self.bed_dg.value = temp

                if not math.isnan(setpoint):
                    if setpoint > 0:
                        self.ids.set_bed_temp.text = str(setpoint)
                        self.bed_dg.setpoint_value = setpoint
                    else:
                        self.bed_dg.setpoint_value = float('nan')
                        if self.bed_switch.active:
                            self.bed_switch.active = False

            elif type == 'hotend0' or type == 'hotend1':
                if (self.ids.tool_t0.state == 'down' and type == 'hotend0') or (self.ids.tool_t1.state == 'down' and type == 'hotend1'):
                    if math.isinf(temp):
                        self.hotend_dg.value = float('inf')
                        continue
                    self.hotend_dg.value = temp

                    if not math.isnan(setpoint):
                        if setpoint > 0:
                            self.ids.set_hotend_temp.text = str(setpoint)
                            self.hotend_dg.setpoint_value = setpoint
                        else:
                            self.hotend_dg.setpoint_value = float('nan')
                            if self.hotend_switch.active:
                                self.hotend_switch.active = False
                else:
                    self.hotend_dg.value = float('inf')

            else:
                Logger.error('Extruder: unknown temp type - ' + type) 
Example 70
Project: NiujiaoDebugger   Author: MrSrc   File: _pydecimal.py    GNU General Public License v3.0 4 votes vote down vote up
def from_float(cls, f):
        """Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        """
        if isinstance(f, int):                # handle integer inputs
            sign = 0 if f >= 0 else 1
            k = 0
            coeff = str(abs(f))
        elif isinstance(f, float):
            if _math.isinf(f) or _math.isnan(f):
                return cls(repr(f))
            if _math.copysign(1.0, f) == 1.0:
                sign = 0
            else:
                sign = 1
            n, d = abs(f).as_integer_ratio()
            k = d.bit_length() - 1
            coeff = str(n*5**k)
        else:
            raise TypeError("argument must be int or float.")

        result = _dec_from_triple(sign, coeff, -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: test_float.py    GNU General Public License v3.0 4 votes vote down vote up
def test_inf_from_str(self):
        self.assertTrue(isinf(float("inf")))
        self.assertTrue(isinf(float("+inf")))
        self.assertTrue(isinf(float("-inf")))
        self.assertTrue(isinf(float("infinity")))
        self.assertTrue(isinf(float("+infinity")))
        self.assertTrue(isinf(float("-infinity")))

        self.assertEqual(repr(float("inf")), "inf")
        self.assertEqual(repr(float("+inf")), "inf")
        self.assertEqual(repr(float("-inf")), "-inf")
        self.assertEqual(repr(float("infinity")), "inf")
        self.assertEqual(repr(float("+infinity")), "inf")
        self.assertEqual(repr(float("-infinity")), "-inf")

        self.assertEqual(repr(float("INF")), "inf")
        self.assertEqual(repr(float("+Inf")), "inf")
        self.assertEqual(repr(float("-iNF")), "-inf")
        self.assertEqual(repr(float("Infinity")), "inf")
        self.assertEqual(repr(float("+iNfInItY")), "inf")
        self.assertEqual(repr(float("-INFINITY")), "-inf")

        self.assertEqual(str(float("inf")), "inf")
        self.assertEqual(str(float("+inf")), "inf")
        self.assertEqual(str(float("-inf")), "-inf")
        self.assertEqual(str(float("infinity")), "inf")
        self.assertEqual(str(float("+infinity")), "inf")
        self.assertEqual(str(float("-infinity")), "-inf")

        self.assertRaises(ValueError, float, "info")
        self.assertRaises(ValueError, float, "+info")
        self.assertRaises(ValueError, float, "-info")
        self.assertRaises(ValueError, float, "in")
        self.assertRaises(ValueError, float, "+in")
        self.assertRaises(ValueError, float, "-in")
        self.assertRaises(ValueError, float, "infinit")
        self.assertRaises(ValueError, float, "+Infin")
        self.assertRaises(ValueError, float, "-INFI")
        self.assertRaises(ValueError, float, "infinitys")

        self.assertRaises(ValueError, float, "++Inf")
        self.assertRaises(ValueError, float, "-+inf")
        self.assertRaises(ValueError, float, "+-infinity")
        self.assertRaises(ValueError, float, "--Infinity") 
Example 72
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 4 votes vote down vote up
def ulp(x):
    """Return the value of the least significant bit of a
    float x, such that the first float bigger than x is x+ulp(x).
    Then, given an expected result x and a tolerance of n ulps,
    the result y should be such that abs(y-x) <= n * ulp(x).
    The results from this function will only make sense on platforms
    where native doubles are represented in IEEE 754 binary64 format.
    """
    x = abs(float(x))
    if math.isnan(x) or math.isinf(x):
        return x

    # Find next float up from x.
    n = struct.unpack('<q', struct.pack('<d', x))[0]
    x_next = struct.unpack('<d', struct.pack('<q', n + 1))[0]
    if math.isinf(x_next):
        # Corner case: x was the largest finite float. Then it's
        # not an exact power of two, so we can take the difference
        # between x and the previous float.
        x_prev = struct.unpack('<d', struct.pack('<q', n - 1))[0]
        return x - x_prev
    else:
        return x_next - x

# Here's a pure Python version of the math.factorial algorithm, for
# documentation and comparison purposes.
#
# Formula:
#
#   factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
#
# where
#
#   factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
#
# The outer product above is an infinite product, but once i >= n.bit_length,
# (n >> i) < 1 and the corresponding term of the product is empty.  So only the
# finitely many terms for 0 <= i < n.bit_length() contribute anything.
#
# We iterate downwards from i == n.bit_length() - 1 to i == 0.  The inner
# product in the formula above starts at 1 for i == n.bit_length(); for each i
# < n.bit_length() we get the inner product for i from that for i + 1 by
# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}.  In Python terms,
# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: test_statistics.py    GNU General Public License v3.0 4 votes vote down vote up
def approx_equal(x, y, tol=1e-12, rel=1e-7):
    """approx_equal(x, y [, tol [, rel]]) => True|False

    Return True if numbers x and y are approximately equal, to within some
    margin of error, otherwise return False. Numbers which compare equal
    will also compare approximately equal.

    x is approximately equal to y if the difference between them is less than
    an absolute error tol or a relative error rel, whichever is bigger.

    If given, both tol and rel must be finite, non-negative numbers. If not
    given, default values are tol=1e-12 and rel=1e-7.

    >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0)
    True
    >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0)
    False

    Absolute error is defined as abs(x-y); if that is less than or equal to
    tol, x and y are considered approximately equal.

    Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is
    smaller, provided x or y are not zero. If that figure is less than or
    equal to rel, x and y are considered approximately equal.

    Complex numbers are not directly supported. If you wish to compare to
    complex numbers, extract their real and imaginary parts and compare them
    individually.

    NANs always compare unequal, even with themselves. Infinities compare
    approximately equal if they have the same sign (both positive or both
    negative). Infinities with different signs compare unequal; so do
    comparisons of infinities with finite numbers.
    """
    if tol < 0 or rel < 0:
        raise ValueError('error tolerances must be non-negative')
    # NANs are never equal to anything, approximately or otherwise.
    if math.isnan(x) or math.isnan(y):
        return False
    # Numbers which compare equal also compare approximately equal.
    if x == y:
        # This includes the case of two infinities with the same sign.
        return True
    if math.isinf(x) or math.isinf(y):
        # This includes the case of two infinities of opposite sign, or
        # one infinity and one finite number.
        return False
    # Two finite numbers.
    actual_error = abs(x - y)
    allowed_error = max(tol, rel*max(abs(x), abs(y)))
    return actual_error <= allowed_error


# This class exists only as somewhere to stick a docstring containing
# doctests. The following docstring and tests were originally in a separate
# module. Now that it has been merged in here, I need somewhere to hang the.
# docstring. Ultimately, this class will die, and the information below will
# either become redundant, or be moved into more appropriate places. 
Example 74
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 4 votes vote down vote up
def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
                           msg=None):
        """Fail if the two floating-point numbers are not almost equal.

        Determine whether floating-point values a and b are equal to within
        a (small) rounding error.  The default values for rel_err and
        abs_err are chosen to be suitable for platforms where a float is
        represented by an IEEE 754 double.  They allow an error of between
        9 and 19 ulps.
        """

        # special values testing
        if math.isnan(a):
            if math.isnan(b):
                return
            self.fail(msg or '{!r} should be nan'.format(b))

        if math.isinf(a):
            if a == b:
                return
            self.fail(msg or 'finite result where infinity expected: '
                      'expected {!r}, got {!r}'.format(a, b))

        # if both a and b are zero, check whether they have the same sign
        # (in theory there are examples where it would be legitimate for a
        # and b to have opposite signs; in practice these hardly ever
        # occur).
        if not a and not b:
            if math.copysign(1., a) != math.copysign(1., b):
                self.fail(msg or 'zero has wrong sign: expected {!r}, '
                          'got {!r}'.format(a, b))

        # if a-b overflows, or b is infinite, return False.  Again, in
        # theory there are examples where a is within a few ulps of the
        # max representable float, and then b could legitimately be
        # infinite.  In practice these examples are rare.
        try:
            absolute_error = abs(b-a)
        except OverflowError:
            pass
        else:
            # test passes if either the absolute error or the relative
            # error is sufficiently small.  The defaults amount to an
            # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
            # machine.
            if absolute_error <= max(abs_err, rel_err * abs(a)):
                return
        self.fail(msg or
                  '{!r} and {!r} are not sufficiently close'.format(a, b)) 
Example 75
Project: MetroloPy   Author: nrc-cnrc   File: ummy.py    GNU General Public License v3.0 4 votes vote down vote up
def _truediv(self,b):   
        if not isinstance(b,ummy):
            if b == 0:
                raise ZeroDivisionError('division by zero')
            if (isinstance(self._x,Integral) and 
                isinstance(b,Integral)):
                x = MFraction(self._x,b)
            else:
                x = self._x/b
            refs = -self._refs if b < 0 else self._refs
            return type(self)(x,abs(self._u/b),dof=self._ref,utype=refs)
                
        c = self.correlation(b)
        if b._x == 0:
            raise ZeroDivisionError('division by zero')
        else:
            if (isinstance(self._x,Integral) and 
                isinstance(b._x,Integral)):
                x = MFraction(self._x,b._x)
            else:
                x = self._x/b._x
            
        dua = self._u/b._x
        dub = -(self._x*b._u/b._x)/b._x
        
        u = _combu(dua,dub,c)
        
        if u == 0:
            return type(b)(x)
        
        if self._u == 0:
            refs = b._refs if self._x < 0 else -b._refs
            return type(b)(x,u,dof=b._ref,utype=refs)
        
        if b._u == 0:
            refs = -self._refs if b._x < 0 else self._refs
            return type(b)(x,u,dof=self._ref,utype=refs)
        
        dua = dua/u
        dub = dub/u
        if not isinf(self._ref.dof) or not isinf(b._ref.dof):
            dof = self._get_dof(self._dof,b._dof,dua,dub,c)
        else:
            dof = float('inf')
            
        r = type(b)(x,u=u,dof=dof)
        
        r._combc(self,b,dua,dub,c)

        return r 
Example 76
Project: MetroloPy   Author: nrc-cnrc   File: ummy.py    GNU General Public License v3.0 4 votes vote down vote up
def _pow(self,b):
        if isinstance(b,ummy) and b._u == 0:
            b = b._x
        if not isinstance(b,ummy):
            if b == 0:
                    return type(self)(1)
            if (isinstance(self._x,Integral) and 
                isinstance(b,Integral) and b < 0):
                x = MFraction(1,self._x**-b)
            else:
                x = self._x**b
            u = abs(b*self._x**(b-1)*self._u)
            if self._x < 0:
                sgn = int(-((-1)**b))
            else:
                sgn = 1
            if b < 0:
                sgn = -sgn
            return type(self)(x,u,dof=self._ref,utype=sgn*self._refs)

        if self._x <= 0:
            raise ValueError('a negative or zero value cannot raised to a power which has an uncertainty')            
                
        c = self.correlation(b)
        if (isinstance(self._x,Integral) and 
                isinstance(b._x,Integral) and b._x < 0):
            x = MFraction(1,self._x**-b._x)
        else:
            x = self._x**b._x
        dua = b._x*self._x**(b._x-1)*self._u
        lgx = log(self._x)
        try:
            lgx = type(self._x)(lgx)
        except:
            pass
        dub = lgx*self._x**b._x*b._u
        u = _combu(dua,dub,c)
        
        if u == 0:
            return type(b)(x)
        
        if self._u == 0:
            refs = -b._refs if self._x < 0 else b._refs
            return type(b)(x,u,dof=b._ref,utype=refs)
        
        dua = dua/u
        dub = dub/u
        
        if not isinf(self._ref.dof) or not isinf(b._ref.dof):
            dof = self._get_dof(self._dof,b._dof,dua,dub,c)
        else:
            dof = float('inf')
            
        r = type(b)(x,u=u,dof=dof)
        
        r._combc(self,b,dua,dub,c)

        return r 
Example 77
Project: MetroloPy   Author: nrc-cnrc   File: gummy.py    GNU General Public License v3.0 4 votes vote down vote up
def _iset_U(self,k=None,unit=None,u=None):
        # this is called when k, p, unit, or uunit is changed to get the new
        # value of _U
        
        if u is None:
            u = self._u
            
        if unit is None:
            if isinstance(self._U,gummy):
                unit = self._U._unit
            
        if u == 0:
            if unit is None:
                return 0
            else:
                return gummy(0,unit=unit)
        
        if isinf(u) or isnan(u):
            if unit is None:
                return u
            else:
                return gummy(u,unit=unit)
                
        if k is None:
            k = self._k
        
        if unit is None or unit is self._unit:
            return _ku(k,u)
                
        else:
            if self._unit.linear:
                try:
                    if self._unit.is_dimensionless:
                        raise NoUnitConversionFoundError()
                    return gummy(_ku(k,u),unit=self.unit).convert(unit)
                    
                except NoUnitConversionFoundError:
                    try:
                        r = abs(_ku(k,u)/self._x)
                        return gummy(r).convert(unit)
                    except ZeroDivisionError:
                        if not Unit.unit(unit).is_dimensionless:
                            raise NoUnitConversionFoundError('no conversion found from unit ' + str(unit) + ' to one')
                        return gummy(float('inf'),unit=unit)
            else:
                return gummy(self._unit.to_uunit(_ku(k,u),unit),unit) 
Example 78
Project: lightwood   Author: mindsdb   File: cesium_ts.py    MIT License 4 votes vote down vote up
def encode(self, values_data, times=None):
        """
        Encode a column data into time series

        :param values_data: a list of timeseries data eg: ['91.0 92.0 93.0 94.0', '92.0 93.0 94.0 95.0' ...]
        :param times: (optional) a list of lists such that, len(times[i])=len(values_data[i]) for all i in range(len(times))
        :return: a torch.floatTensor
        """
        features_to_use = self._features
        ret = []
        for i, values in enumerate(values_data):
            values = list(map(lambda x: float(x), values.split()))
            if times is None:
                times_row = np.array([float(i) for i in range(1, len(values) + 1)])
            else:
                times_row = np.array(list(map(lambda x: float(x), times[i].split()))) # np.array(times[i])
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                row = featurize.featurize_time_series(times=times_row,
                                                      values=np.array(values),
                                                      errors=None,
                                                      features_to_use=features_to_use)

            vector_row = []
            for col in features_to_use:
                val = list(row[col][0])[0]
                val1 = 0
                if (val in ['nan', None, 'NaN', False]) \
                        or math.isnan(val) or math.isinf(val):
                    val = 0
                    val1 = 1

                if col in FEATURES_WITH_DEFAULT_NONE:
                    vector_row += [val, val1]  # val1 is 1 if its null
                else:
                    vector_row += [val]
            ret += [vector_row]
        ret_tensor = self._pytorch_wrapper(ret)
        return ret_tensor


# only run the test if this file is called from debugger 
Example 79
Project: HyperGAN   Author: HyperGAN   File: 2d-sequence.py    MIT License 4 votes vote down vote up
def train(config, args):
    title = "[hypergan] 2d-test " + args.config
    GlobalViewer.title = title
    GlobalViewer.enabled = args.viewer

    with tf.device(args.device):
        config.generator["class"]="class:__main__.Sequence2DGenerator"
        config.discriminator["class"]="class:__main__.Sequence2DDiscriminator"
        gan = hg.GAN(config, inputs = Sequence2DInputDistribution(args))

        sampler = Sequence2DSampler(gan)

        tf.train.start_queue_runners(sess=gan.session)
        samples = 0
        steps = args.steps
        sampler.sample("samples/000000.png", args.save_samples)

        #metrics = [accuracy_x_to_g, accuracy_g_to_x]
        #sum_metrics = [0 for metric in metrics]
        for i in range(steps):
            gan.step({gan.inputs.current_step: i})

            if args.viewer and i % args.sample_every == 0:
                samples += 1
                print("Sampling "+str(samples), args.save_samples)
                sample_file="samples/%06d.png" % (samples)
                sampler.sample(sample_file, args.save_samples)

            #if i > steps * 9.0/10:
            #    for k, metric in enumerate(gan.session.run(metrics)):
            #        sum_metrics[k] += metric 
            #if i % 300 == 0:
            #    for k, metric in enumerate(gan.metrics.keys()):
            #        metric_value = gan.session.run(gan.metrics[metric])
            #        print("--", metric,  metric_value)
            #        if math.isnan(metric_value) or math.isinf(metric_value):
            #            print("Breaking due to invalid metric")
            #            return None

        tf.reset_default_graph()
        gan.session.close()

    return {}#sum_metrics 
Example 80
Project: HyperGAN   Author: HyperGAN   File: 2d-distribution.py    MIT License 4 votes vote down vote up
def train(config, args):
    title = "[hypergan] 2d-test " + args.config
    GlobalViewer.title = title
    GlobalViewer.enabled = args.viewer

    with tf.device(args.device):
        config.generator['end_features'] = 2
        config.generator["class"]="class:__main__.Custom2DGenerator" # TODO
        config.discriminator["class"]="class:__main__.Custom2DDiscriminator" # TODO
        gan = hg.GAN(config, inputs = Custom2DInputDistribution(args))
        gan.name = args.config

        accuracy_x_to_g=distribution_accuracy(gan.inputs.x, gan.generator.sample)
        accuracy_g_to_x=distribution_accuracy(gan.generator.sample, gan.inputs.x)

        sampler = Custom2DSampler(gan)
        gan.selected_sampler = sampler

        tf.train.start_queue_runners(sess=gan.session)
        samples = 0
        steps = args.steps
        sampler.sample("samples/000000.png", args.save_samples)

        metrics = [accuracy_x_to_g, accuracy_g_to_x]
        sum_metrics = [0 for metric in metrics]
        for i in range(steps):
            gan.step()

            if args.viewer and i % args.sample_every == 0:
                samples += 1
                print("Sampling "+str(samples), args.save_samples)
                sample_file="samples/%06d.png" % (samples)
                sampler.sample(sample_file, args.save_samples)

            if i > steps * 9.0/10:
                for k, metric in enumerate(gan.session.run(metrics)):
                    sum_metrics[k] += metric 
            if i % 300 == 0:
                for k, metric in enumerate(gan.metrics().keys()):
                    metric_value = gan.session.run(gan.metrics()[metric])
                    print("--", metric,  metric_value)
                    if math.isnan(metric_value) or math.isinf(metric_value):
                        print("Breaking due to invalid metric")
                        return None

        tf.reset_default_graph()
        gan.session.close()

    return sum_metrics