Python math.isfinite() Examples

The following are 30 code examples of math.isfinite(). 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 Project: tartiflette   Author: tartiflette   File: float.py    License: MIT License 6 votes vote down vote up
def coerce_output(self, value: Any) -> float:
        """
        Coerce the resolved value for output.
        :param value: value to coerce
        :type value: Any
        :return: the coerced value
        :rtype: float
        """
        # pylint: disable=no-self-use
        try:
            result = value
            if value and isinstance(value, str):
                result = float(value)

            if not isfinite(result):
                raise ValueError

            return result if isinstance(result, float) else float(result)
        except Exception:  # pylint: disable=broad-except
            pass

        raise TypeError(
            f"Float cannot represent non numeric value: < {value} >."
        ) 
Example #2
Source Project: tartiflette   Author: tartiflette   File: float.py    License: MIT License 6 votes vote down vote up
def coerce_input(self, value: Any) -> float:
        """
        Coerce the user input from variable value.
        :param value: value to coerce
        :type value: Any
        :return: the coerced value
        :rtype: float
        """
        # pylint: disable=no-self-use
        # ¯\_(ツ)_/¯ booleans are int: `assert isinstance(True, int) is True`
        try:
            if not isinstance(value, bool) and isfinite(value):
                return float(value)
        except Exception:  # pylint: disable=broad-except
            pass
        raise TypeError(
            f"Float cannot represent non numeric value: < {value} >."
        ) 
Example #3
Source Project: tartiflette   Author: tartiflette   File: boolean.py    License: MIT License 6 votes vote down vote up
def coerce_output(self, value: Any) -> bool:
        """
        Coerce the resolved value for output.
        :param value: value to coerce
        :type value: Any
        :return: the coerced value
        :rtype: bool
        """
        # pylint: disable=no-self-use
        if isinstance(value, bool):
            return value

        try:
            if isfinite(value):
                return bool(value)
        except Exception:  # pylint: disable=broad-except
            pass
        raise TypeError(
            f"Boolean cannot represent a non boolean value: < {value} >."
        ) 
Example #4
Source Project: ibis   Author: ibis-project   File: compiler.py    License: Apache License 2.0 6 votes vote down vote up
def _number_literal_format(translator, expr):
    value = expr.op().value

    if math.isfinite(value):
        # Spark interprets dotted number literals as decimals, not floats.
        # i.e. "select 1.0 as tmp" is a decimal(2,1), not a float or double
        if isinstance(expr.op().dtype, dt.Float64):
            formatted = "{}d".format(repr(value))
        elif isinstance(expr.op().dtype, dt.Floating):
            formatted = "CAST({} AS FLOAT)".format(repr(value))
        else:
            formatted = repr(value)
    else:
        if math.isnan(value):
            formatted_val = 'NaN'
        elif math.isinf(value):
            if value > 0:
                formatted_val = 'Infinity'
            else:
                formatted_val = '-Infinity'
        formatted = "CAST({!r} AS DOUBLE)".format(formatted_val)

    return formatted 
Example #5
Source Project: ibis   Author: ibis-project   File: compiler.py    License: Apache License 2.0 6 votes vote down vote up
def _number_literal_format(translator, expr):
    value = expr.op().value

    if math.isfinite(value):
        formatted = repr(value)
    else:
        if math.isnan(value):
            formatted_val = 'NaN'
        elif math.isinf(value):
            if value > 0:
                formatted_val = 'Infinity'
            else:
                formatted_val = '-Infinity'
        formatted = "CAST({!r} AS DOUBLE)".format(formatted_val)

    return formatted 
Example #6
Source Project: pyfuzzylite   Author: fuzzylite   File: defuzzifier.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def defuzzify(self, term: Term, minimum: float, maximum: float) -> float:
        if not math.isfinite(minimum + maximum):
            return nan
        resolution = self.resolution
        dx = (maximum - minimum) / resolution
        counter = resolution
        left = right = 0
        x_left, x_right = (minimum, maximum)
        left_area = right_area = 0.0

        # TODO: Improve?
        while counter > 0:
            counter = counter - 1
            if left_area <= right_area:
                x_left = minimum + (left + 0.5) * dx
                left_area += term.membership(x_left)
                left += 1
            else:
                x_right = maximum - (right + 0.5) * dx
                right_area += term.membership(x_right)
                right += 1

        # Inverse weighted average to compensate
        return (left_area * x_right + right_area * x_left) / (left_area + right_area) 
Example #7
Source Project: pyfuzzylite   Author: fuzzylite   File: defuzzifier.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def defuzzify(self, term: Term, minimum: float, maximum: float) -> float:
        if not math.isfinite(minimum + maximum):
            return nan
        resolution = self.resolution
        dx = (maximum - minimum) / resolution
        y_max = -math.inf
        x_smallest = minimum
        x_largest = maximum
        find_x_largest = False
        for i in range(0, resolution):
            x = minimum + (i + 0.5) * dx
            y = term.membership(x)
            if Op.gt(y, y_max):
                y_max = y
                x_smallest = x
                x_largest = x
                find_x_largest = True
            elif find_x_largest and Op.eq(y, y_max):
                x_largest = x
            elif Op.lt(y, y_max):
                find_x_largest = False
        return (x_largest + x_smallest) / 2.0 
Example #8
Source Project: pikepdf   Author: pikepdf   File: test_object.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_decimal_from_float(f):
    d = Decimal(f)
    if isfinite(f) and d.is_finite():
        try:
            # PDF is limited to ~5 sig figs
            decstr = str(d.quantize(Decimal('1.000000')))
        except InvalidOperation:
            return  # PDF doesn't support exponential notation
        try:
            py_d = Object.parse(decstr)
        except RuntimeError as e:
            if 'overflow' in str(e) or 'underflow' in str(e):
                py_d = Object.parse(str(f))

        assert isclose(py_d, d, abs_tol=1e-5), (d, f.hex())
    else:
        with pytest.raises(PdfError):
            Object.parse(str(d)) 
Example #9
Source Project: bfx-hf-indicators-py   Author: bitfinexcom   File: chaikin_oscillator.py    License: Apache License 2.0 6 votes vote down vote up
def update(self, candle):
    self._adl.update(candle)
    adl = self._adl.v()

    if not isfinite(adl):
      return
    
    self._shortEMA.update(adl)
    self._longEMA.update(adl)

    short = self._shortEMA.v()
    long = self._longEMA.v()

    if (isfinite(short) and isfinite(long)):
      super().update(short - long)

    return self.v() 
Example #10
Source Project: bfx-hf-indicators-py   Author: bitfinexcom   File: chaikin_oscillator.py    License: Apache License 2.0 6 votes vote down vote up
def add(self, candle):
    self._adl.add(candle)
    adl = self._adl.v()

    if not isfinite(adl):
      return
    
    self._shortEMA.add(adl)
    self._longEMA.add(adl)

    short = self._shortEMA.v()
    long = self._longEMA.v()

    if (isfinite(short) and isfinite(long)):
      super().add(short - long)

    return self.v() 
Example #11
Source Project: bfx-hf-indicators-py   Author: bitfinexcom   File: acceleration.py    License: Apache License 2.0 6 votes vote down vote up
def add(self, v):
    self._roc.add(v)
    roc = self._roc.v()

    if not isfinite(roc):
      return

    if len(self._buffer) == self._p:
      super().add(roc - self._buffer[0])

    self._buffer.append(roc)

    if len(self._buffer) > self._p:
      del self._buffer[0]

    return self.v() 
Example #12
Source Project: bfx-hf-indicators-py   Author: bitfinexcom   File: macd.py    License: Apache License 2.0 6 votes vote down vote up
def add(self, v):
    slowEMA = self._slowEMA.add(v)
    fastEMA = self._fastEMA.add(v)

    if not isfinite(slowEMA) or not isfinite(fastEMA):
      return

    macd = fastEMA - slowEMA
    signalEMA = self._signalEMA.add(macd)

    if not isfinite(signalEMA):
      return

    histogram = macd - signalEMA

    super().add({
      'macd': macd,
      'signal': signalEMA,
      'histogram': histogram
    })

    return self.v() 
Example #13
Source Project: bfx-hf-indicators-py   Author: bitfinexcom   File: relative_volatility_index.py    License: Apache License 2.0 6 votes vote down vote up
def update(self, v):
    if self._prevInputValue == None:
      return self.v()

    self._stddev.update(v)
    stddev = self._stddev.v()

    if not isfinite(stddev):
      return self.v()
    
    [u, d] = RVI.ud(v, self._prevInputValue, stddev)

    self._uEMA.update(u)
    self._dEMA.update(d)

    uSum = self._uEMA.v()
    dSum = self._dEMA.v()

    if uSum == dSum:
      return super().update(0)
    else:
      return super().update(100 * (uSum / (uSum + dSum))) 
Example #14
Source Project: Neuraxle   Author: Neuraxio   File: distributions.py    License: Apache License 2.0 6 votes vote down vote up
def rvs(self) -> float:
        """
        Will return a float value in the specified range as specified at creation.

        :return: a float.
        """
        if self.hard_clip_min is None and self.hard_clip_max is None:
            result = float(np.random.normal(self._mean, self._std))
        else:
            a = -np.inf
            b = np.inf

            if self.hard_clip_min is not None:
                a = (self.hard_clip_min - self._mean) / self._std

            if self.hard_clip_max is not None:
                b = (self.hard_clip_max - self._mean) / self._std

            result = truncnorm.rvs(a=a, b=b, loc=self._mean, scale=self._std)

        if not math.isfinite(result):
            return self.rvs()
        return float(result) 
Example #15
Source Project: Neuraxle   Author: Neuraxio   File: distributions.py    License: Apache License 2.0 6 votes vote down vote up
def rvs(self) -> float:
        """
        Will return a float value in the specified range as specified at creation.
        Note: the range at creation was in log space. The return value is after taking an exponent.

        :return: a float.
        """
        if self.hard_clip_min is None and self.hard_clip_max is None:
            result = 2 ** float(np.random.normal(self.log2_space_mean, self.log2_space_std))
        else:
            a = -np.inf
            b = np.inf

            if self.hard_clip_min is not None:
                a = (math.log2(self.hard_clip_min) - self.log2_space_mean) / self.log2_space_std

            if self.hard_clip_max is not None:
                b = (math.log2(self.hard_clip_max) - self.log2_space_mean) / self.log2_space_std

            result = 2 ** float(truncnorm.rvs(a=a, b=b, loc=self.log2_space_mean, scale=self.log2_space_std))

        if not math.isfinite(result):
            return self.rvs()

        return float(result) 
Example #16
Source Project: archipack   Author: s-leger   File: algorithms.py    License: GNU General Public License v3.0 6 votes vote down vote up
def intersection(p1, p2, q1, q2, ret):
        px = p1.y - p2.y
        py = p2.x - p1.x
        pw = p1.x * p2.y - p2.x * p1.y
        
        qx = q1.y - q2.y
        qy = q2.x - q1.x
        qw = q1.x * q2.y - q2.x * q1.y

        x = py * qw - qy * pw
        y = qx * pw - px * qw
        w = px * qy - qx * py

        xInt = x / w
        yInt = y / w

        if not isfinite(xInt) or not isfinite(yInt):
            raise ArithmeticError()

        ret.x, ret.y = xInt, yInt 
Example #17
Source Project: tg2019task   Author: umanlp   File: evaluate.py    License: MIT License 6 votes vote down vote up
def mean_average_precision_score(gold, pred, callback=None):
    total, count = 0., 0

    for question in gold.values():
        if question.id in pred:
            ranks = compute_ranks(list(question.explanations), pred[question.id])

            score = average_precision(ranks)

            if not math.isfinite(score):
                score = 0.

            total += score
            count += 1

            if callback:
                callback(question.id, score)

    mean_ap = total / count if count > 0 else 0.

    return mean_ap 
Example #18
Source Project: influxdb-client-python   Author: influxdata   File: point.py    License: MIT License 6 votes vote down vote up
def _append_fields(fields):
    _return = []

    for field, value in sorted(iteritems(fields)):
        if value is None:
            continue

        if isinstance(value, float) or isinstance(value, Decimal):
            if not math.isfinite(value):
                continue
            _return.append(f'{_escape_key(field)}={str(value)}')
        elif isinstance(value, int) and not isinstance(value, bool):
            _return.append(f'{_escape_key(field)}={str(value)}i')
        elif isinstance(value, bool):
            _return.append(f'{_escape_key(field)}={str(value).lower()}')
        elif isinstance(value, str):
            _return.append(f'{_escape_key(field)}="{_escape_string(value)}"')
        else:
            raise ValueError()

    return f"{','.join(_return)}" 
Example #19
Source Project: oj   Author: online-judge-tools   File: test.py    License: MIT License 6 votes vote down vote up
def compare_as_floats(xs_: str, ys_: str, error: float) -> bool:
    def f(x):
        try:
            y = float(x)
            if not math.isfinite(y):
                log.warning('not an real number found: %f', y)
            return y
        except ValueError:
            return x

    xs = list(map(f, xs_.split()))
    ys = list(map(f, ys_.split()))
    if len(xs) != len(ys):
        return False
    for x, y in zip(xs, ys):
        if isinstance(x, float) and isinstance(y, float):
            if not math.isclose(x, y, rel_tol=error, abs_tol=error):
                return False
        else:
            if x != y:
                return False
    return True 
Example #20
Source Project: apex   Author: NVIDIA   File: distributed_fused_adam_v2.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __launch_step_kernel(self, p, p_copy, m, v, g):
        combined_scale = self._global_scale
        if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm):
            combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6)
            combined_scale = self._global_scale / min(1, combined_scale)
        bias_correction = 1 if self._param_group['bias_correction'] else 0
        beta1, beta2 = self._param_group['betas']
        fused_adam_cuda.reversible_adam(
                p, p_copy, m, v, g,
                self._param_group['lr'],
                beta1,
                beta2,
                self._param_group['eps'],
                combined_scale,
                self._param_state['step']+1,
                self.eps_mode,
                bias_correction,
                self._param_group['weight_decay']) 
Example #21
Source Project: apex   Author: NVIDIA   File: distributed_fused_adam_v2.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revert_step(self):
        """Revert effect of previously calling partial_step.
        """
        # Call undo kernel once per step
        combined_scale = self._global_scale
        if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm):
            combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6)
            combined_scale = self._global_scale / min(1, combined_scale)
        bias_correction = 1 if self._param_group['bias_correction'] else 0
        beta1, beta2 = self._param_group['betas']
        fused_adam_cuda.maybe_adam_undo(
                    torch.empty([0]),
                    self._fp32_p,
                    self._fp32_m,
                    self._fp32_v,
                    self._fp16_g,
                    self._param_group['lr'],
                    beta1,
                    beta2,
                    self._param_group['eps'],
                    combined_scale,
                    self._param_state['step']+1,
                    self.eps_mode,
                    bias_correction,
                    self._param_group['weight_decay']) 
Example #22
Source Project: apex   Author: NVIDIA   File: distributed_fused_adam.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __launch_step_kernel(self, p, p_copy, m, v, g):
        combined_scale = self._global_scale
        if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm):
            combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6)
            combined_scale = self._global_scale / min(1, combined_scale)
        bias_correction = 1 if self._param_group['bias_correction'] else 0
        beta1, beta2 = self._param_group['betas']
        fused_adam_cuda.reversible_adam(
                p, p_copy, m, v, g,
                self._param_group['lr'],
                beta1,
                beta2,
                self._param_group['eps'],
                combined_scale,
                self._param_state['step']+1,
                self.eps_mode,
                bias_correction,
                self._param_group['weight_decay']) 
Example #23
Source Project: apex   Author: NVIDIA   File: distributed_fused_adam.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revert_step(self):
        """Revert effect of previously calling partial_step.
        """
        # Call undo kernel once per step
        combined_scale = self._global_scale
        if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm):
            combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6)
            combined_scale = self._global_scale / min(1, combined_scale)
        bias_correction = 1 if self._param_group['bias_correction'] else 0
        beta1, beta2 = self._param_group['betas']
        fused_adam_cuda.maybe_adam_undo(
                    torch.empty([0]),
                    self._fp32_p,
                    self._fp32_m,
                    self._fp32_v,
                    self._fp16_g,
                    self._param_group['lr'],
                    beta1,
                    beta2,
                    self._param_group['eps'],
                    combined_scale,
                    self._param_state['step']+1,
                    self.eps_mode,
                    bias_correction,
                    self._param_group['weight_decay']) 
Example #24
Source Project: gluon-ts   Author: awslabs   File: test_backtest.py    License: Apache License 2.0 6 votes vote down vote up
def test_forecast_parser():
    # verify that logged for estimator, datasets and metrics can be recovered
    # from their string representation

    dataset_info, train_ds, test_ds = constant_dataset()

    estimator = make_estimator(
        dataset_info.metadata.freq, dataset_info.prediction_length
    )
    assert repr(estimator) == repr(load_code(repr(estimator)))

    stats = calculate_dataset_statistics(train_ds)
    assert stats == eval(
        repr(stats), globals(), {"gluonts": gluonts}
    )  # TODO: use load

    evaluator = Evaluator(quantiles=[0.1, 0.5, 0.9])
    agg_metrics, _ = backtest_metrics(train_ds, test_ds, estimator, evaluator)

    # reset infinite metrics to 0 (otherwise the assertion below fails)
    for key, val in agg_metrics.items():
        if not math.isfinite(val):
            agg_metrics[key] = 0.0

    assert agg_metrics == load_code(dump_code(agg_metrics)) 
Example #25
Source Project: hypothesis-jsonschema   Author: Zac-HD   File: _canonicalise.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def iterencode(self, o: Any, _one_shot: bool = False) -> Any:
        """Replace a stdlib method, so we encode integer-valued floats as ints."""

        def floatstr(o: float) -> str:
            # This is the bit we're overriding - integer-valued floats are
            # encoded as integers, to support JSONschemas's uniqueness.
            assert math.isfinite(o)
            if o == int(o):
                return repr(int(o))
            return repr(o)

        return _make_iterencode(
            {},
            self.default,
            encode_basestring_ascii,
            self.indent,
            floatstr,
            self.key_separator,
            self.item_separator,
            self.sort_keys,
            self.skipkeys,
            _one_shot,
        )(o, 0) 
Example #26
Source Project: TGC-Designer-Tools   Author: chadrockey   File: GeoPointCloud.py    License: Apache License 2.0 5 votes vote down vote up
def addFromImage(self, image, image_scale, latlon_origin, proj):
        # Insert points
        X = []
        Y = []
        Z = []
        I = []
        C = []

        for row in range(0, image.shape[0]):
            for column in range(0, image.shape[1]):
                z = image[row, column]
                if math.isfinite(z):
                    x, y = self.cv2ToENU(row, column, image_scale)
                    X.append(x)
                    Y.append(y)
                    Z.append(z)
                    I.append(0.0)
                    C.append(0.0)

        self.addDataSet(X, Y, Z, I, C)

        # Need to store the lowest coordinates in case we cropped the image by not inserting invalid pixels
        # These will become zero when removeBias() is called and helps center large or offset courses to fit
        # Within the 2k square
        west_most_point = numpy.min(self.point_matrix[:,0]) # Offset from 0.0 left edge to west most point
        south_most_point = numpy.min(self.point_matrix[:,1]) # Offset from 0.0 bottom edge to south most point

        # Calculate the origin of these points
        self._proj = proj
        uncropped_origin = self.latlonToProj(latlon_origin[0], latlon_origin[1])
        # Move the original origin up to the new left/bottom point
        self._origin = (uncropped_origin[0] + west_most_point, uncropped_origin[1] + south_most_point)

        # Clear properties
        self.removeBias()
        self.resetProperties() 
Example #27
Source Project: python-pytest-cases   Author: smarie   File: example_code.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def isfinite(x):
        """
        isfinite(x) -> bool

        Return True if x is neither an infinity nor a NaN, and False otherwise.
        """
        return not (isinf(x) or isnan(x)) 
Example #28
Source Project: python-pytest-cases   Author: smarie   File: example_code.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def super_function_i_want_to_test(a, b):
    """
    An example function to be tested
    :param a:
    :param b:
    :return:
    """
    if not isfinite(a):
        raise InfiniteInput('a')
    if not isfinite(b):
        raise InfiniteInput('b')

    return a + 1, b + 1 
Example #29
Source Project: python-pytest-cases   Author: smarie   File: example_code.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def super_function_i_want_to_test2(a, b):
    """
    An example function to be tested
    :param a:
    :param b:
    :return:
    """
    if not isfinite(a):
        raise InfiniteInput('a')
    if not isfinite(b):
        raise InfiniteInput('b')

    return a + 1, b + 1 
Example #30
Source Project: bioforum   Author: reBiocoder   File: fields.py    License: MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid')