Python math.isclose() Examples

The following are 30 code examples of math.isclose(). 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: test_revival_spike_resistant_ema_throughput_measurement.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def test_rsr_ema_tm_throughput_in_normal_state(tm):
    # [0, 15) - [225, 240) -- 16 not empty windows
    for ts in range(0, 240, 5):
        tm.add_request(ts)

    # [240, 255)
    throughput_before = tm.get_throughput(240)
    assert tm.state == State.NORMAL

    for ts in range(240, 255, 1):  # load increases
        tm.add_request(ts)

    # [255, 270)
    throughput = tm.get_throughput(255)
    assert tm.state == State.NORMAL

    assert isclose(throughput,
                   (2 / 17) * 1 + (1 - 2 / 17) * throughput_before) 
Example #2
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 6 votes vote down vote up
def get_delta(begin):
    """
    get difference between current time and begin from clip in playlist
    """
    current_time = get_time('full_sec')

    if _playlist.length:
        target_playtime = _playlist.length
    else:
        target_playtime = 86400.0

    if _playlist.start >= current_time and not begin == _playlist.start:
        current_time += target_playtime

    current_delta = begin - current_time

    if math.isclose(current_delta, 86400.0, abs_tol=6):
        current_delta -= 86400.0

    ref_time = target_playtime + _playlist.start
    total_delta = ref_time - begin + current_delta

    return current_delta, total_delta 
Example #3
Source File: filters.py    From ffplayout-engine with GNU General Public License v3.0 6 votes vote down vote up
def scale_filter(probe):
    """
    if target resolution is different to source add scale filter,
    apply also an aspect filter, when is different
    """
    filter_chain = []

    if int(probe.video[0]['width']) != _pre_comp.w or \
            int(probe.video[0]['height']) != _pre_comp.h:
        filter_chain.append('scale={}:{}'.format(_pre_comp.w, _pre_comp.h))

    if not math.isclose(probe.video[0]['aspect'],
                        _pre_comp.aspect, abs_tol=0.03):
        filter_chain.append('setdar=dar={}'.format(_pre_comp.aspect))

    return filter_chain 
Example #4
Source File: test_classify.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ecm_init(self):

        m = np.array([0.23, .81, .85, .81, .85, .81])
        u = np.array([0.34, .23, .50, .23, .30, 0.13])

        # Create the train dataset.
        X_train, true_links = binary_vectors(
            1000, 500, m=m, u=u, random_state=535, return_links=True)

        ecm = rl.ECMClassifier(init='random')
        ecm.fit(X_train)
        ecm.predict(X_train)

        print(ecm.m_probs)
        print(ecm.log_m_probs)
        print(ecm.u_probs)
        print(ecm.log_u_probs)

        assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08) 
Example #5
Source File: test_classify.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ecm_init_random_1value(self):

        m = np.array([1.0, .81, .85, .81, .85, .81])
        u = np.array([1.0, .23, .50, .23, .30, 0.13])

        # Create the train dataset.
        X_train, true_links = binary_vectors(
            1000, 500, m=m, u=u, random_state=536, return_links=True)

        ecm = rl.ECMClassifier(init='random')
        ecm.fit(X_train)
        ecm.predict(X_train)

        with pytest.raises(KeyError):
            ecm.m_probs['c_1'][0]

        assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08)
        assert math.isclose(ecm.p, 0.5, abs_tol=0.05) 
Example #6
Source File: test_classify.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ecm_init_jaro_1value(self):

        m = np.array([1.0, 0.85, .85, .81, .85, .81])
        u = np.array([1.0, .10, .50, .23, .30, 0.13])

        # Create the train dataset.
        X_train, true_links = binary_vectors(
            1000, 500, m=m, u=u, random_state=535, return_links=True)

        ecm = rl.ECMClassifier(init='jaro')
        ecm.fit(X_train)
        ecm.predict(X_train)

        with pytest.raises(KeyError):
            ecm.m_probs['c_1'][0]

        assert math.isclose(ecm.m_probs['c_1'][1], 1.0, abs_tol=0.01)
        assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08)
        assert math.isclose(ecm.u_probs['c_1'][1], 1.0, abs_tol=0.01)
        assert math.isclose(ecm.u_probs['c_2'][1], 0.1, abs_tol=0.05)
        assert math.isclose(ecm.p, 0.5, abs_tol=0.05) 
Example #7
Source File: test_classify.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ecm_init_jaro_skewed(self):

        m = np.array([1.0, 0.85, .85, .81, .85, .81])
        u = np.array([0.0, .10, .50, .23, .30, 0.13])

        # Create the train dataset.
        X_train, true_links = binary_vectors(
            1000, 500, m=m, u=u, random_state=535, return_links=True)

        ecm = rl.ECMClassifier(init='jaro')
        ecm.fit(X_train)
        ecm.predict(X_train)

        assert math.isclose(ecm.m_probs['c_1'][1], 1.0, abs_tol=0.01)
        assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08)
        assert math.isclose(ecm.u_probs['c_1'][1], 0.0, abs_tol=0.01)
        assert math.isclose(ecm.u_probs['c_2'][1], 0.1, abs_tol=0.05)
        assert math.isclose(ecm.p, 0.5, abs_tol=0.05) 
Example #8
Source File: test_classify.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ecm_init_jaro_inf(self):
        m = np.array([0.95, .81, .85, .81, .85, .81])
        u = np.array([0, .23, .50, .23, .30, 0.13])

        # Create the train dataset.
        X_train, true_links = binary_vectors(
            10000, 500, m=m, u=u, random_state=535, return_links=True)

        # Create the train dataset.
        X_test, true_links = binary_vectors(
            1000, 500, m=m, u=u, random_state=535, return_links=True)

        ecm = rl.ECMClassifier()
        ecm.fit(X_train)
        ecm.predict(X_test)

        assert math.isclose(ecm.u_probs['c_1'][1], 0.0, abs_tol=1e-3)
        assert math.isclose(ecm.u_probs['c_1'][0], 1.0, abs_tol=1e-3) 
Example #9
Source File: test_bytes_can_uplink_converter.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def _test_float_point_number(self, type, byteorder):
        float_value = uniform(-3.1415926535, 3.1415926535)

        can_data = [0, 0]
        configs = [{
            "key": type + "Var",
            "is_ts": True,
            "type": type,
            "start": len(can_data),
            "length": 4 if type[0] == "f" else 8,
            "byteorder": byteorder
        }]

        can_data.extend(_struct.pack((">" if byteorder[0] == "b" else "<") + type[0],
                                     float_value))
        tb_data = self.converter.convert(configs, can_data)
        self.assertTrue(isclose(tb_data["telemetry"][type + "Var"], float_value, rel_tol=1e-05)) 
Example #10
Source File: fmarket.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def calc_price_change(ratio, min_price_move=DEF_MIN_PRICE_MOVE,
                      max_price_move=DEF_MAX_PRICE_MOVE):
    """
    Make the price move in proportion to the ratio, up to a ceiling
    of max_price_move.
    """
    direction = 1
    if isclose(ratio, 1.0):
        return 0

    if ratio < 1:
        if ratio == 0:
            ratio = INF
        else:
            ratio = 1 / ratio
        direction = -1

    return direction * min(max_price_move, min_price_move * ratio) 
Example #11
Source File: test_ridge.py    From mabwiser with Apache License 2.0 6 votes vote down vote up
def test_l2_low(self):

        context = np.array([[1, 1, 0, 0, 1], [0, 1, 2, 9, 4], [2, 3, 1, 0, 2]])
        rewards = np.array([3, 2, 1])
        decisions = np.array([1, 1, 1])

        arms, mab = self.predict(arms=[0, 1],
                                 decisions=decisions,
                                 rewards=rewards,
                                 learning_policy=LearningPolicy.LinUCB(alpha=1, l2_lambda=0.1),
                                 context_history=context,
                                 contexts=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1]],
                                 seed=123456,
                                 num_run=1,
                                 is_predict=True)

        self.assertEqual(mab._imp.num_features, 5)
        self.assertEqual(arms, [1, 1])
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[0], 1.59499705, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[1], -0.91856183, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[2], -2.49775977, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[3], 0.14219195, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[4], 1.65819347, abs_tol=0.00000001)) 
Example #12
Source File: test_ridge.py    From mabwiser with Apache License 2.0 6 votes vote down vote up
def test_l2_high(self):

        context = np.array([[1, 1, 0, 0, 1], [0, 1, 2, 9, 4], [2, 3, 1, 0, 2]])
        rewards = np.array([3, 2, 1])
        decisions = np.array([1, 1, 1])
        arms, mab = self.predict(arms=[0, 1],
                                 decisions=decisions,
                                 rewards=rewards,
                                 learning_policy=LearningPolicy.LinUCB(alpha=1, l2_lambda=10),
                                 context_history=context,
                                 contexts=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1]],
                                 seed=123456,
                                 num_run=1,
                                 is_predict=True)

        self.assertEqual(mab._imp.num_features, 5)
        self.assertEqual(arms, [0, 0])
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[0], 0.18310155, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[1], 0.16372811, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[2], -0.00889076, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[3], 0.09434416, abs_tol=0.00000001))
        self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[4], 0.22503229, abs_tol=0.00000001)) 
Example #13
Source File: test_cli.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def test_topic_delay(self):
        average_delay_line_pattern = re.compile(r'average delay: (\d+.\d{3})')
        stats_line_pattern = re.compile(
            r'\s*min: \d+.\d{3}s max: \d+.\d{3}s std dev: \d+.\d{5}s window: \d+'
        )
        with self.launch_topic_command(arguments=['delay', '/cmd_vel']) as topic_command:
            assert topic_command.wait_for_output(functools.partial(
                launch_testing.tools.expect_output, expected_lines=[
                    average_delay_line_pattern, stats_line_pattern
                ], strict=True
            ), timeout=10)
        assert topic_command.wait_for_shutdown(timeout=10)

        head_line = topic_command.output.splitlines()[0]
        average_delay = float(average_delay_line_pattern.match(head_line).group(1))
        assert math.isclose(average_delay, 0.0, abs_tol=10e-3) 
Example #14
Source File: test_cli.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def test_topic_hz(self):
        average_rate_line_pattern = re.compile(r'average rate: (\d+.\d{3})')
        stats_line_pattern = re.compile(
            r'\s*min: \d+.\d{3}s max: \d+.\d{3}s std dev: \d+.\d{5}s window: \d+'
        )
        with self.launch_topic_command(arguments=['hz', '/chatter']) as topic_command:
            assert topic_command.wait_for_output(functools.partial(
                launch_testing.tools.expect_output, expected_lines=[
                    average_rate_line_pattern, stats_line_pattern
                ], strict=True
            ), timeout=10)
        assert topic_command.wait_for_shutdown(timeout=10)

        head_line = topic_command.output.splitlines()[0]
        average_rate = float(average_rate_line_pattern.match(head_line).group(1))
        assert math.isclose(average_rate, 1., rel_tol=1e-2) 
Example #15
Source File: test_cli.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def test_filtered_topic_hz(self):
        average_rate_line_pattern = re.compile(r'average rate: (\d+.\d{3})')
        stats_line_pattern = re.compile(
            r'\s*min: \d+.\d{3}s max: \d+.\d{3}s std dev: \d+.\d{5}s window: \d+'
        )
        with self.launch_topic_command(
            arguments=[
                'hz',
                '--filter',
                'int(m.data.rpartition(\":\")[-1]) % 2 == 0',
                '/chatter'
            ]
        ) as topic_command:
            assert topic_command.wait_for_output(functools.partial(
                launch_testing.tools.expect_output, expected_lines=[
                    average_rate_line_pattern, stats_line_pattern
                ], strict=True
            ), timeout=10), 'Output does not match: ' + topic_command.output
        assert topic_command.wait_for_shutdown(timeout=10)

        head_line = topic_command.output.splitlines()[0]
        average_rate = float(average_rate_line_pattern.match(head_line).group(1))
        assert math.isclose(average_rate, 0.5, rel_tol=1e-2) 
Example #16
Source File: simlike.py    From kevlar with MIT License 6 votes vote down vote up
def process_partition(partitionid, calls, ambigthresh=10):
    passcalls = [c for c in calls if c.filterstr == 'PASS']
    if len(passcalls) == 0:
        return
    maxscore = max([c.attribute('LIKESCORE') for c in passcalls])
    maxcalls = list()
    for c in calls:
        passed = c.filterstr == 'PASS'
        optimal = isclose(c.attribute('LIKESCORE'), maxscore)
        if passed and optimal:
            maxcalls.append(c)
        else:
            c.filter(kevlar.vcf.VariantFilter.PartitionScore)
    for c in maxcalls:
        if ambigthresh and len(maxcalls) > ambigthresh:
            c.filter(kevlar.vcf.VariantFilter.AmbiguousCall)
        else:
            c.annotate('CALLCLASS', partitionid) 
Example #17
Source File: test_preprocess_func.py    From tmtoolkit with Apache License 2.0 6 votes vote down vote up
def test_doc_frequencies_example():
    docs = [
        list('abc'),
        list('abb'),
        list('ccc'),
        list('da'),
    ]

    abs_df = doc_frequencies(docs)
    assert dict(abs_df) == {
        'a': 3,
        'b': 2,
        'c': 2,
        'd': 1,
    }

    rel_df = doc_frequencies(docs, proportions=True)
    math.isclose(rel_df['a'], 3/4)
    math.isclose(rel_df['b'], 2/4)
    math.isclose(rel_df['c'], 2/4)
    math.isclose(rel_df['d'], 1/4) 
Example #18
Source File: ball.py    From pypong with MIT License 6 votes vote down vote up
def paddle_bounce(self, paddle):
        ''' Changes ball's direction and curve when bouncing off the
            paddle. '''
        paddle_edge = paddle.x + 1 if paddle.player == 1 else paddle.x
        if isclose(self.x, paddle_edge, abs_tol=consts.BALL_RADIUS):
            if (self.y + consts.BALL_RADIUS >=
                    paddle.y) and (self.y - consts.BALL_RADIUS <=
                                   paddle.y + consts.PADDLE_LENGTH):
                self.x_direction_right = not self.x_direction_right
                if (self.y + consts.BALL_RADIUS >
                        paddle.y + consts.PADDLE_LENGTH -
                        consts.PADDLE_TIP) or (self.y - consts.BALL_RADIUS <
                                               paddle.y + consts.PADDLE_TIP):
                    self.curved = True
                else:
                    self.curved = False 
Example #19
Source File: test_external.py    From textdistance with MIT License 6 votes vote down vote up
def test_qval(left, right, alg):
    for lib in libraries.get_libs(alg):
        conditions = lib.conditions or {}
        internal_func = getattr(textdistance, alg)(external=False, **conditions)
        external_func = lib.get_function()
        # algorithm doesn't support q-grams
        if not hasattr(internal_func, 'qval'):
            continue
        for qval in (None, 1, 2, 3):
            internal_func.qval = qval
            # if qval unsopporting already set for lib
            s1, s2 = internal_func._get_sequences(left, right)
            if not lib.check_conditions(internal_func, s1, s2):
                continue

            # test
            int_result = internal_func(left, right)
            s1, s2 = lib.prepare(s1, s2)
            ext_result = external_func(s1, s2)
        assert isclose(int_result, ext_result), str(lib) 
Example #20
Source File: test_moving_average.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def test_ema_event_frequency_estimator_respects_reaction_time(step):
    now = 0.0
    half_time = 120.0
    estimator = EMAEventFrequencyEstimator(now, half_time)
    assert estimator.value == 0

    while now < half_time:
        estimator.update_time(now)
        estimator.add_events(step)
        now += step
    estimator.update_time(now)
    assert math.isclose(estimator.value, 0.5, rel_tol=0.07)

    while now < 2.0 * half_time:
        estimator.update_time(now)
        estimator.add_events(step)
        now += step
    estimator.update_time(now)
    assert math.isclose(estimator.value, 0.75, rel_tol=0.07) 
Example #21
Source File: test_softmax.py    From mabwiser with Apache License 2.0 6 votes vote down vote up
def test2_unused_arm(self):

        arm, mab = self.predict(arms=[1, 2, 3, 4],
                                decisions=[1, 1, 1, 2, 2, 3, 3, 3, 3, 3],
                                rewards=[0, 1, 1, 0, 0, 0, 0, 1, 1, 1],
                                learning_policy=LearningPolicy.Softmax(tau=1),
                                seed=123456,
                                num_run=20,
                                is_predict=True)

        self.assertTrue(4 in mab._imp.arm_to_expectation.keys())
        self.assertEqual(arm[13], 4)

        e_x = mab._imp.arm_to_exponent[4]
        prob = mab._imp.arm_to_expectation[4]

        self.assertTrue(math.isclose(e_x, 0.513, abs_tol=0.001))
        self.assertTrue(math.isclose(prob, 0.173, abs_tol=0.001)) 
Example #22
Source File: test_revival_spike_resistant_ema_throughput_measurement.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def test_rsr_ema_throughput_measurement_creation():
    tm = RevivalSpikeResistantEMAThroughputMeasurement(window_size=5,
                                                       min_cnt=9)

    assert tm.window_size == 5
    assert tm.min_cnt == 9
    assert isclose(tm.alpha, 0.2)

    assert tm.state == State.FADED

    assert tm.window_start_ts is None  # must not be initialized in `__init__`
    assert tm.reqs_in_window == 0
    assert tm.throughput == 0

    assert tm.throughput_before_idle == 0
    assert tm.idle_start_ts is None  # must not be initialized in `__init__`
    assert tm.empty_windows_count == 0 
Example #23
Source File: filters.py    From ffplayout-engine with GNU General Public License v3.0 6 votes vote down vote up
def pad_filter(probe):
    """
    if source and target aspect is different,
    fix it with pillarbox or letterbox
    """
    filter_chain = []

    if not math.isclose(probe.video[0]['aspect'],
                        _pre_comp.aspect, abs_tol=0.03):
        if probe.video[0]['aspect'] < _pre_comp.aspect:
            filter_chain.append(
                'pad=ih*{}/{}/sar:ih:(ow-iw)/2:(oh-ih)/2'.format(_pre_comp.w,
                                                                 _pre_comp.h))
        elif probe.video[0]['aspect'] > _pre_comp.aspect:
            filter_chain.append(
                'pad=iw:iw*{}/{}/sar:(ow-iw)/2:(oh-ih)/2'.format(_pre_comp.h,
                                                                 _pre_comp.w))

    return filter_chain 
Example #24
Source File: test_jaccard.py    From textdistance with MIT License 5 votes vote down vote up
def test_compare_with_tversky_as_set(left, right):
    td = textdistance.Tversky(ks=[1, 1], as_set=True).distance(left, right)
    jd = ALG(as_set=True).distance(left, right)
    assert isclose(jd, td) 
Example #25
Source File: numerical.py    From orbit-predictor with MIT License 5 votes vote down vote up
def is_sun_synchronous(predictor, rtol=1e-3, epoch=None):
    """Check if predictor corresponds to Sun-synchronous orbit within tolerance.

    """
    if epoch is None:
        epoch = dt.datetime.now()

    sma_km, ecc, inc_deg, *_ = predictor.get_position(epoch).osculating_elements
    p = sma_km * (1 - ecc ** 2)
    n = mean_motion(sma_km)

    raan_dot_sec = - 3 * n * R_E_KM ** 2 * J2 / (2 * p ** 2) * cos(radians(inc_deg))

    return isclose(raan_dot_sec, OMEGA, rel_tol=rtol) 
Example #26
Source File: test_jaro_winkler.py    From textdistance with MIT License 5 votes vote down vote up
def test_distance(left, right, expected):
    actual = ALG(winklerize=True, external=False)(left, right)
    assert isclose(actual, expected)

    actual = ALG(winklerize=True, external=True)(left, right)
    assert isclose(actual, expected) 
Example #27
Source File: test_strcmp95.py    From textdistance with MIT License 5 votes vote down vote up
def test_distance(left, right, expected):
    actual = ALG(external=False)(left, right)
    assert isclose(actual, expected)

    actual = ALG(external=True)(left, right)
    assert isclose(actual, expected) 
Example #28
Source File: test_jaro.py    From textdistance with MIT License 5 votes vote down vote up
def test_distance(left, right, expected):
    actual = ALG(winklerize=False, external=False)(left, right)
    assert isclose(actual, expected)

    actual = ALG(winklerize=False, external=True)(left, right)
    assert isclose(actual, expected) 
Example #29
Source File: test_external.py    From textdistance with MIT License 5 votes vote down vote up
def test_compare(left, right, alg):
    for lib in libraries.get_libs(alg):
        conditions = lib.conditions or {}
        internal_func = getattr(textdistance, alg)(external=False, **conditions)
        external_func = lib.get_function()
        if external_func is None:
            raise RuntimeError('cannot import {}'.format(str(lib)))

        if not lib.check_conditions(internal_func, left, right):
            continue

        int_result = internal_func(left, right)
        s1, s2 = lib.prepare(left, right)
        ext_result = external_func(s1, s2)
        assert isclose(int_result, ext_result), str(lib) 
Example #30
Source File: test_jaccard.py    From textdistance with MIT License 5 votes vote down vote up
def test_compare_with_tversky(left, right):
    td = textdistance.Tversky(ks=[1, 1]).distance(left, right)
    jd = ALG().distance(left, right)
    assert isclose(jd, td)