Python math.isinf() Examples

The following are 30 code examples of math.isinf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: importance.py    From cgpm with 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 #2
Source File: gaussian_moments.py    From DOTA_models with 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
Source File: fractions.py    From jawfish with 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 #4
Source File: fractions.py    From jawfish with 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 #5
Source File: fractions.py    From jawfish with 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 #6
Source File: utils.py    From DOTA_models with 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 #7
Source File: dial-gauge.py    From kivy-smoothie-host with 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
Source File: interp.py    From hadrian with 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
Source File: parse.py    From hadrian with 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
Source File: pfatest.py    From hadrian with 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 #11
Source File: accountant.py    From DOTA_models with 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 #12
Source File: la.py    From hadrian with 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 #13
Source File: dist.py    From hadrian with 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 #14
Source File: dist.py    From hadrian with 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 #15
Source File: dist.py    From hadrian with 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 #16
Source File: dist.py    From hadrian with 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 #17
Source File: dist.py    From hadrian with 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 #18
Source File: parse.py    From hadrian with 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 #19
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, m, n, k):
        if m + n < k or m < 0 or n <= 0 or m + n == 0 or k < 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 x > m:
            return 0.0
        else:
            return HypergeometricDistribution(m, n, k, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example #20
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, min, max):
        if math.isinf(min) or math.isnan(min) or math.isinf(max) or math.isnan(max) or min >= max:
            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)
        return UniformDistribution(min, max, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example #21
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, m, n, k):
        if m + n < k or m < 0 or n <= 0 or m + n == 0 or k < 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 x > m:
            return 0.0
        else:
            return HypergeometricDistribution(m, n, k, self.errcodeBase + 0, self.name, pos).PDF(x) 
Example #22
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, prob):
        if math.isinf(prob) or math.isnan(prob) or prob <= 0 or prob > 1:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif not (0.0 <= p <= 1):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif p == 1:
            return float("inf")
        else:
            return GeometricDistribution(prob, self.errcodeBase + 0, self.name, pos).QF(p) 
Example #23
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, prob):
        if math.isinf(prob) or math.isnan(prob) 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)
        else:
            return GeometricDistribution(prob, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example #24
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, min, max):
        if math.isinf(min) or math.isnan(min) or math.isinf(max) or math.isnan(max) or min >= max:
            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)
        else:
            return UniformDistribution(min, max, self.errcodeBase + 0, self.name, pos).QF(p) 
Example #25
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, df):
        if df <= 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)
        else:
            return TDistribution(df, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example #26
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, location, scale):
        if math.isinf(location) or math.isnan(location) or math.isinf(scale) or math.isnan(scale) or scale <= 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:
            return float("inf")
        elif p == 0:
            return float("-inf")
        else:
            return CauchyDistribution(location, scale, self.errcodeBase + 0, self.name, pos).QF(p) 
Example #27
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, meanlog, sdlog):
        if math.isinf(meanlog) or math.isnan(meanlog) or math.isinf(sdlog) or math.isnan(sdlog) or sdlog <= 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)
        else:
            return LognormalDistribution(meanlog, sdlog, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example #28
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, meanlog, sdlog):
        if math.isinf(meanlog) or math.isnan(meanlog) or math.isinf(sdlog) or math.isnan(sdlog) or sdlog <= 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:
            return float("inf")
        else:
            return LognormalDistribution(meanlog, sdlog, self.errcodeBase + 0, self.name, pos).QF(p) 
Example #29
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, df):
        if df <= 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)
        else:
            return TDistribution(df, self.errcodeBase + 0, self.name, pos).PDF(x) 
Example #30
Source File: dist.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, 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 not (0.0 <= p <= 1):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif p == 1:
            return float(size)
        elif p == 0:
            return 0.0
        else:
            return BinomialDistribution(size, prob, self.errcodeBase + 0, self.name, pos).QF(p)