Python math.isinf() Examples

The following are 30 code examples for showing how to use math.isinf(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: DOTA_models   Author: ringringyi   File: accountant.py    License: 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 2
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    License: 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 3
Project: DOTA_models   Author: ringringyi   File: utils.py    License: 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 4
Project: jawfish   Author: war-and-code   File: fractions.py    License: 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 5
Project: jawfish   Author: war-and-code   File: fractions.py    License: 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 6
Project: jawfish   Author: war-and-code   File: fractions.py    License: 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 7
Project: kivy-smoothie-host   Author: wolfmanjm   File: dial-gauge.py    License: 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 8
Project: hadrian   Author: modelop   File: interp.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, *args):
        if len(args) == 3:
            numbins, low, high = args
            if low >= high or math.isnan(low) or math.isnan(high):
                raise PFARuntimeException("bad histogram range", self.errcodeBase + 0, self.name, pos)
            if numbins < 1:
                raise PFARuntimeException("bad histogram scale", self.errcodeBase + 1, self.name, pos)
            if math.isnan(x) or x < low or x >= high:
                raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos)

            out = int(math.floor(numbins * div((x - low), (high - low))))

            if out < 0 or out >= numbins:
                raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos)
            return out
        else:
            origin, width = args
            if math.isnan(origin) or math.isinf(origin):
                raise PFARuntimeException("bad histogram range", self.errcodeBase + 0, self.name, pos)
            if width <= 0.0 or math.isnan(width):
                raise PFARuntimeException("bad histogram scale", self.errcodeBase + 1, self.name, pos)
            if math.isnan(x) or math.isinf(x):
                raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos)
            else:
                return int(math.floor(div((x - origin), width))) 
Example 9
Project: hadrian   Author: modelop   File: parse.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, str):
        try:
            out = float(str)
        except ValueError:
            raise PFARuntimeException("not a single-precision float", self.errcodeBase + 0, self.name, pos)
        if math.isnan(out):
            return out
        elif math.isinf(out):
            return out
        elif out > FLOAT_MAX_VALUE:
            return float("inf")
        elif -out > FLOAT_MAX_VALUE:
            return float("-inf")
        elif abs(out) < FLOAT_MIN_VALUE:
            return 0.0
        else:
            return out 
Example 10
Project: hadrian   Author: modelop   File: parse.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, str):
        try:
            out = float(str)
        except ValueError:
            raise PFARuntimeException("not a double-precision float", self.errcodeBase + 0, self.name, pos)
        if math.isnan(out):
            return out
        elif math.isinf(out):
            return out
        elif out > DOUBLE_MAX_VALUE:
            return float("inf")
        elif -out > DOUBLE_MAX_VALUE:
            return float("-inf")
        elif abs(out) < DOUBLE_MIN_VALUE:
            return 0.0
        else:
            return out 
Example 11
Project: hadrian   Author: modelop   File: pfatest.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, state_):
        chi2 = state_["chi2"]
        dof = state_["dof"]
        if dof < 0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif dof == 0:
            if chi2 > 0:
                return 1.0
            else:
                return 0.0
        elif math.isnan(chi2):
            return float("nan")
        elif math.isinf(chi2):
            if chi2 > 0:
                return 1.0
            else:
                return 0.0
        else:
            return float(Chi2Distribution(dof, self.errcodeBase + 0, self.name, pos).CDF(chi2)) 
Example 12
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, *others):
        if len(others) == 2:
            mu, sigma = others
        else:
            mu = others[0]["mean"]
            if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0:
                raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
            else:
                sigma = math.sqrt(others[0]["variance"])
        if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif sigma == 0.0:
            if x != mu:
                return float("-inf")
            else:
                return float("inf")
        else:
            return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).LL(x) 
Example 13
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, *others):
        if len(others) == 2:
            mu, sigma = others
        else:
            mu = others[0]["mean"]
            if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0:
                raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
            else:
                sigma = math.sqrt(others[0]["variance"])
        if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif sigma == 0.0:
            if x < mu:
                return 0.0
            else:
                return 1.0
        else:
            return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example 14
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, *others):
        if len(others) == 2:
            mu, sigma = others
        else:
            mu = others[0]["mean"]
            if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0:
                raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
            else:
                sigma = math.sqrt(others[0]["variance"])
        if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif not (0.0 <= p <= 1.0):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif p == 1.0:
            return float("inf")
        elif p == 0.0:
            return float("-inf")
        elif sigma == 0.0:
            return mu
        else:
            return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).QF(p) 
Example 15
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, shape, scale):
        if math.isinf(shape) or math.isnan(shape) or math.isinf(scale) or math.isnan(scale) or shape < 0 or scale < 0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif shape == 0 or scale == 0:
            if x != 0:
                return 0.0
            else:
                return float("inf")
        elif x < 0:
            return 0.0
        elif x == 0:
            if shape < 1:
                return float("inf")
            elif shape == 1:
                return 1.0/scale
            else:
                return 0.0
        else:
            return GammaDistribution(shape, scale, self.errcodeBase + 0, self.name, pos).PDF(x) 
Example 16
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, size, prob):
        if math.isinf(prob) or math.isnan(prob) or size <= 0 or prob < 0 or prob > 1:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif x < 0:
            return 0.0
        elif x >= size:
            return 1.0
        elif prob == 1:
            if x < size:
                return 0.0
            else:
                return 1.0
        elif prob == 0:
            return 1.0
        else:
            return BinomialDistribution(size, prob, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example 17
Project: hadrian   Author: modelop   File: la.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        if isinstance(x, (list, tuple)) and all(isinstance(xi, (list, tuple)) for xi in x):
            rows = len(x)
            if rows < 1:
                raise PFARuntimeException("too few rows/cols", self.errcodeBase + 0, self.name, pos)
            cols = len(x[0])
            if cols < 1:
                raise PFARuntimeException("too few rows/cols", self.errcodeBase + 0, self.name, pos)
            if raggedArray(x):
                raise PFARuntimeException("ragged columns", self.errcodeBase + 1, self.name, pos)
            if rows != cols:
                raise PFARuntimeException("non-square matrix", self.errcodeBase + 2, self.name, pos)
            if any(any(math.isnan(z) or math.isinf(z) for z in row) for row in x):
                raise PFARuntimeException("non-finite matrix", self.errcodeBase + 3, self.name, pos)
            return matrixToArrays(self.calculate(arraysToMatrix(x), rows))

        elif isinstance(x, dict) and all(isinstance(x[i], dict) for i in x.keys()):
            keys = list(rowKeys(x).union(colKeys(x)))
            if len(keys) < 1 or all(len(z) == 0 for z in x.values()):
                raise PFARuntimeException("too few rows/cols", self.errcodeBase + 0, self.name, pos)
            if any(any(math.isnan(z) or math.isinf(z) for z in row.values()) for row in x.values()):
                raise PFARuntimeException("non-finite matrix", self.errcodeBase + 3, self.name, pos)
            return matrixToMaps(self.calculate(mapsToMatrix(x, keys, keys), len(keys)), map(str, xrange(len(keys))), keys) 
Example 18
Project: cgpm   Author: probcomp   File: importance.py    License: Apache License 2.0 6 votes vote down vote up
def logpdf(self, rowid, targets, constraints=None, inputs=None):
        if constraints is None:
            constraints = {}
        if inputs is None:
            inputs = {}
        # Compute joint probability.
        samples_joint, weights_joint = zip(*[
            self.weighted_sample(
                rowid, [], gu.merged(targets, constraints), inputs)
            for _i in xrange(self.accuracy)
        ])
        logp_joint = gu.logmeanexp(weights_joint)
        # Compute marginal probability.
        samples_marginal, weights_marginal = zip(*[
            self.weighted_sample(rowid, [], constraints, inputs)
            for _i in xrange(self.accuracy)
        ]) if constraints else ({}, [0.])
        if all(isinf(l) for l in weights_marginal):
            raise ValueError('Zero density constraints: %s' % (constraints,))
        logp_constraints = gu.logmeanexp(weights_marginal)
        # Return log ratio.
        return logp_joint - logp_constraints 
Example 19
Project: DOTA_models   Author: ringringyi   File: wiki_data.py    License: 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 20
Project: DOTA_models   Author: ringringyi   File: accountant.py    License: 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 21
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    License: 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 22
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    License: 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 23
Project: jawfish   Author: war-and-code   File: _struct.py    License: MIT License 5 votes vote down vote up
def isinf(x):
    return x != 0.0 and x / 2 == x 
Example 24
Project: python-esppy   Author: sassoftware   File: jmp_score.py    License: 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 25
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: 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 26
Project: kivy-smoothie-host   Author: wolfmanjm   File: dial-gauge.py    License: 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 27
Project: hadrian   Author: modelop   File: rand.py    License: Apache License 2.0 5 votes vote down vote up
def selectIndex(self, rand, distribution, pos):
        cumulativeSum = [0.0]
        for x in distribution:
            if math.isnan(x) or math.isinf(x):
                raise PFARuntimeException("distribution must be finite", self.errcodeBase + 1, self.name, pos)
            elif x < 0:
                raise PFARuntimeException("distribution must be non-negative", self.errcodeBase + 2, self.name, pos)
            cumulativeSum.append(cumulativeSum[-1] + x)
        total = cumulativeSum[-1]
        if total == 0.0:
            raise PFARuntimeException("distribution must be non-empty", self.errcodeBase + 0, self.name, pos)
        position = rand.uniform(0.0, total)
        for i, y in enumerate(cumulativeSum):
            if position < y:
                return i - 1 
Example 28
Project: hadrian   Author: modelop   File: impute.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        return math.isinf(x) 
Example 29
Project: hadrian   Author: modelop   File: impute.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        return not math.isnan(x) and not math.isinf(x) 
Example 30
Project: hadrian   Author: modelop   File: impute.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, default):
        if math.isnan(x) or math.isinf(x):
            return default
        else:
            return x