Python math.nan() Examples

The following are 30 code examples of math.nan(). 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: OctoBot-Tentacles   Author: Drakkar-Software   File: pattern_analysis.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_pattern(data):
        if len(data) > 0:
            mean_value = np.mean(data) * 0.7
        else:
            mean_value = math.nan
        if math.isnan(mean_value):
            return PatternAnalyser.UNKNOWN_PATTERN
        indexes_under_mean_value = np.where(data > mean_value)[0] \
            if mean_value < 0 \
            else np.where(data < mean_value)[0]

        nb_gaps = 0
        for i in range(len(indexes_under_mean_value)-1):
            if indexes_under_mean_value[i+1]-indexes_under_mean_value[i] > 3:
                nb_gaps += 1

        if nb_gaps > 1:
            return "W" if mean_value < 0 else "M"
        else:
            return "V" if mean_value < 0 else "N"

    # returns a value 0 < value < 1: the higher the stronger is the pattern 
Example #2
Source Project: combine-FEVER-NSMN   Author: easonnie   File: doc_utils.py    License: MIT License 6 votes vote down vote up
def doc_f1(cls, d_list):

        def single_f1(item):
            docid_predicted = item['predicted_docids']
            docid_predicted = set(docid_predicted)
            docid_gt =  [iii for i in item['evidence'] \
                             for ii in i \
                             for iii in ii \
                             if type(iii) == str]
            docid_gt = set(docid_gt)
            docid_intersect = docid_predicted & docid_gt

            if len(docid_gt) == 0:
                return math.nan
            f1 = 2*len(docid_intersect) / (len(docid_gt) + len(docid_predicted))
            return f1

        score_list = map(single_f1, d_list)
        score_list = [s for s in score_list if not math.isnan(s)]
        return sum(score_list) / len(score_list) 
Example #3
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_seldom(self) -> None:
        with self.assertRaisesRegex(ValueError,
                                    r"math domain error"):
            HedgeAssert(self, fl.Seldom()).evaluates({-1.0: nan})
            HedgeAssert(self, fl.Seldom()).evaluates({-0.5: nan})
            HedgeAssert(self, fl.Seldom()).evaluates({inf: nan})
            HedgeAssert(self, fl.Seldom()).evaluates({-inf: nan})

        HedgeAssert(self, fl.Seldom()) \
            .has_name("seldom") \
            .evaluates({0.00: 0.0,
                        0.25: 0.3535533905932738,
                        0.50: 0.5,
                        0.75: 0.6464466094067263,
                        1.00: 1.0,
                        nan: nan}) 
Example #4
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_somewhat(self) -> None:
        with self.assertRaisesRegex(ValueError,
                                    r"math domain error"):
            HedgeAssert(self, fl.Somewhat()).evaluates({-1.0: nan})
            HedgeAssert(self, fl.Somewhat()).evaluates({-0.5: nan})
            HedgeAssert(self, fl.Somewhat()).evaluates({-inf: nan})

        HedgeAssert(self, fl.Somewhat()) \
            .has_name("somewhat") \
            .evaluates({0.00: 0.0,
                        0.25: 0.5,
                        0.50: 0.7071067811865476,
                        0.75: 0.8660254037844386,
                        1.00: 1.0,
                        inf: inf,
                        nan: nan}) 
Example #5
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_lambda(self) -> None:
        HedgeAssert(self, fl.HedgeLambda("my_hedge", lambda x: (
            2.0 * x * x if x <= 0.5 else (1.0 - 2.0 * (1.0 - x) * (1.0 - x))))) \
            .has_name("my_hedge") \
            .evaluates({-1.0: 2.0,
                        -0.5: 0.5,
                        0.00: 0.0,
                        0.25: 0.125,
                        0.50: 0.5,
                        0.75: 0.875,
                        1.00: 1.0,
                        inf: -inf,
                        -inf: inf,
                        nan: nan})

        if __name__ == '__main__':
            unittest.main() 
Example #6
Source Project: pyfuzzylite   Author: fuzzylite   File: test_variable.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_fuzzify(self) -> None:
        VariableAssert(self, fl.Variable(name="name",
                                         description="description",
                                         minimum=-1.0,
                                         maximum=1.0,
                                         terms=[
                                             fl.Triangle('Low', -1.0, -1.0, 0.0),
                                             fl.Triangle('Medium', -0.5, 0.0, 0.5),
                                             fl.Triangle('High', 0.0, 1.0, 1.0)
                                         ])) \
            .fuzzy_values(
            {-1.00: "1.000/Low + 0.000/Medium + 0.000/High",
             -0.50: "0.500/Low + 0.000/Medium + 0.000/High",
             -0.25: "0.250/Low + 0.500/Medium + 0.000/High",
             0.00: "0.000/Low + 1.000/Medium + 0.000/High",
             0.25: "0.000/Low + 0.500/Medium + 0.250/High",
             0.50: "0.000/Low + 0.000/Medium + 0.500/High",
             0.75: "0.000/Low + 0.000/Medium + 0.750/High",
             1.00: "0.000/Low + 0.000/Medium + 1.000/High",
             math.nan: "nan/Low + nan/Medium + nan/High",
             math.inf: "0.000/Low + 0.000/Medium + 0.000/High",
             -math.inf: "0.000/Low + 0.000/Medium + 0.000/High",
             }) 
Example #7
Source Project: pyfuzzylite   Author: fuzzylite   File: test_variable.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_highest_membership(self) -> None:
        low, medium, high = (fl.Triangle('Low', -1.0, -.5, 0.0),
                             fl.Triangle('Medium', -0.5, 0.0, 0.5),
                             fl.Triangle('High', 0.0, .5, 1.0))
        VariableAssert(self, fl.Variable(name="name",
                                         description="description",
                                         minimum=-1.0,
                                         maximum=1.0,
                                         terms=[low, medium, high])) \
            .highest_memberships(
            {-1.00: (0.0, None),
             -0.75: (0.5, low),
             -0.50: (1.0, low),
             -0.25: (0.5, low),
             0.00: (1.0, medium),
             0.25: (0.5, medium),
             0.50: (1.0, high),
             0.75: (0.5, high),
             1.00: (0.0, None),
             math.nan: (0.0, None),
             math.inf: (0.0, None),
             -math.inf: (0.0, None),
             }) 
Example #8
Source Project: pyfuzzylite   Author: fuzzylite   File: test_variable.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_fuzzy_value(self) -> None:
        InputVariableAssert(self, fl.InputVariable(name="name",
                                                   description="description",
                                                   minimum=-1.0,
                                                   maximum=1.0,
                                                   terms=[
                                                       fl.Triangle('Low', -1.0, -1.0, 0.0),
                                                       fl.Triangle('Medium', -0.5, 0.0, 0.5),
                                                       fl.Triangle('High', 0.0, 1.0, 1.0)
                                                   ])) \
            .fuzzy_values({-1.00: "1.000/Low + 0.000/Medium + 0.000/High",
                           -0.50: "0.500/Low + 0.000/Medium + 0.000/High",
                           -0.25: "0.250/Low + 0.500/Medium + 0.000/High",
                           0.00: "0.000/Low + 1.000/Medium + 0.000/High",
                           0.25: "0.000/Low + 0.500/Medium + 0.250/High",
                           0.50: "0.000/Low + 0.000/Medium + 0.500/High",
                           0.75: "0.000/Low + 0.000/Medium + 0.750/High",
                           1.00: "0.000/Low + 0.000/Medium + 1.000/High",
                           math.nan: "nan/Low + nan/Medium + nan/High",
                           math.inf: "0.000/Low + 0.000/Medium + 0.000/High",
                           -math.inf: "0.000/Low + 0.000/Medium + 0.000/High",
                           }) 
Example #9
Source Project: pyfuzzylite   Author: fuzzylite   File: test_term.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_division_by_zero_fails_with_float(self) -> None:
        self.assertEqual(fl.lib.floating_point_type, float)

        TermAssert(self, fl.Function.create("dbz", "0.0/x")) \
            .membership_fails(0.0, ZeroDivisionError, re.escape("float division by zero")) \
            .has_memberships({fl.inf: 0.0, -fl.inf: -0.0, fl.nan: fl.nan})

        TermAssert(self, fl.Function.create("dbz", "inf/x")) \
            .membership_fails(0.0, ZeroDivisionError, re.escape("float division by zero")) \
            .has_memberships({fl.inf: fl.nan, -fl.inf: fl.nan, fl.nan: fl.nan})

        TermAssert(self, fl.Function.create("dbz", ".-inf/x")) \
            .membership_fails(0.0, ZeroDivisionError, re.escape("float division by zero")) \
            .has_memberships({fl.inf: fl.nan, -fl.inf: fl.nan, -fl.nan: fl.nan})

        TermAssert(self, fl.Function.create("dbz", "nan/x")) \
            .membership_fails(0.0, ZeroDivisionError, re.escape("float division by zero")) \
            .has_memberships({fl.inf: fl.nan, -fl.inf: fl.nan, -fl.nan: fl.nan}) 
Example #10
Source Project: pyfuzzylite   Author: fuzzylite   File: test_operation.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_str(self) -> None:
        fl.lib.decimals = 3
        self.assertEqual(fl.Op.str(0.3), "0.300")
        self.assertEqual(fl.Op.str(-0.3), "-0.300")
        self.assertEqual(fl.Op.str(3), "3")
        self.assertEqual(fl.Op.str(3.0001), "3.000")

        self.assertEqual(fl.Op.str(math.inf), "inf")
        self.assertEqual(fl.Op.str(-math.inf), "-inf")
        self.assertEqual(fl.Op.str(math.nan), "nan")

        fl.lib.decimals = 5
        self.assertEqual(fl.Op.str(0.3), "0.30000")

        fl.lib.decimals = 0
        self.assertEqual(fl.Op.str(0.3), "0")

        fl.lib.decimals = 3 
Example #11
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 #12
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 #13
Source Project: pyfuzzylite   Author: fuzzylite   File: term.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def membership(self, x: float) -> float:
        if isnan(x):
            return nan

        if self.start == self.end:
            return self.height * 0.0

        if self.start < self.end:
            if x <= self.start:
                return self.height * 0.0
            if x >= self.end:
                return self.height * 1.0
            return self.height * (x - self.start) / (self.end - self.start)

        else:
            if x >= self.start:
                return self.height * 0.0
            if x <= self.end:
                return self.height * 1.0
            return self.height * (self.start - x) / (self.start - self.end) 
Example #14
Source Project: TGC-Designer-Tools   Author: chadrockey   File: infill_image.py    License: Apache License 2.0 5 votes vote down vote up
def apply_mask(np_array, mask, invalid_value=math.nan):
    np_array[ mask < 1 ] = invalid_value
    return np_array 
Example #15
Source Project: mabwiser   Author: fidelity   File: simulator.py    License: Apache License 2.0 5 votes vote down vote up
def _predict_contexts(self, contexts: np.ndarray, is_predict: bool,
                          seeds: Optional[np.ndarray] = None, start_index: Optional[int] = None) -> List:

        # Copy learning policy object
        lp = deepcopy(self.lp)

        # Create an empty list of predictions
        predictions = [None] * len(contexts)

        # For each row in the given contexts
        for index, row in enumerate(contexts):

            # Get random generator
            lp.rng = create_rng(seeds[index])

            # Calculate the distances from the historical contexts
            # Row is 1D so convert it to 2D array for cdist using newaxis
            # Finally, reshape to flatten the output distances list
            row_2d = row[np.newaxis, :]
            distances_to_row = self.distances[start_index + index]

            # Find the neighbor indices within the radius
            # np.where with a condition returns a tuple where the first element is an array of indices
            indices = np.where(distances_to_row <= self.radius)

            # If neighbors exist
            if indices[0].size > 0:

                prediction, exp, stats = self._get_nhood_predictions(lp, row_2d, indices, is_predict)
                predictions[index] = [prediction, exp, len(indices[0]), stats]

            else:  # When there are no neighbors

                # Random arm (or nan expectations)
                prediction = self._get_no_nhood_predictions(lp, is_predict)
                predictions[index] = [prediction, {}, 0, {}]

        # Return the list of predictions
        return predictions 
Example #16
Source Project: mabwiser   Author: fidelity   File: simulator.py    License: Apache License 2.0 5 votes vote down vote up
def _get_no_nhood_predictions(self, lp, is_predict):
        if is_predict:
            # if no_nhood_prob_of_arm is None, select a random int
            # else, select a non-uniform random arm
            # choice returns an array, hence get zero index
            rand_int = lp.rng.choice(len(self.arms), 1, p=self.no_nhood_prob_of_arm)[0]
            return self.arms[rand_int]
        else:
            # Expectations will be nan when there are no neighbors
            return self.arm_to_expectation.copy() 
Example #17
Source Project: cryptotrader   Author: naripok   File: utils.py    License: MIT License 5 votes vote down vote up
def decimal(data):
        try:
            return dec_con.create_decimal(data).quantize(convert_to._quantizer)
        except TypeError:
            if isinstance(data, np.ndarray):
                return convert_to._quantize_array(data.astype(str))
            else:
                return Decimal.from_float(np.float64(data)).quantize(convert_to._quantizer)
        except InvalidOperation:
            if abs(data) > Decimal('1e20'):
                raise InvalidOperation("Numeric overflow in convert_to.decimal")
            elif data == np.nan or math.nan:
                raise InvalidOperation("NaN encountered in convert_to.decimal")
        except Exception as e:
            print(data)
            print(e)
            raise e


# ZMQ sockets helpers 
Example #18
Source Project: scitail   Author: allenai   File: features_field.py    License: Apache License 2.0 5 votes vote down vote up
def as_array(self, padding_lengths: Dict[str, int]) -> numpy.array:
        padded_features = pad_sequence_to_length(self.features,
                                                 padding_lengths['num_features'],
                                                 (lambda: math.nan))
        return numpy.asarray(padded_features, dtype=numpy.float32) 
Example #19
Source Project: scitail   Author: allenai   File: features_field.py    License: Apache License 2.0 5 votes vote down vote up
def empty_field(self):
        return FeaturesField([math.nan] * len(self.features)) 
Example #20
Source Project: redis-memory-analyzer   Author: gamenet   File: Set.py    License: MIT License 5 votes vote down vote up
def analyze(self, keys, total=0):
        key_stat = {
            'headers': ['Match', "Count", "Avg Count", "Value mem", "Real", "Ratio", "System*", "Encoding", "Total", "TTL Min", "TTL Max", "TTL Avg."],
            'data': []
        }

        progress = tqdm(total=total,
                        mininterval=1,
                        desc="Processing Set patterns",
                        leave=False)

        for pattern, data in keys.items():
            agg = SetAggregator(progress_iterator((SetStatEntry(x, self.redis) for x in data), progress), len(data))

            stat_entry = [
                pattern,
                len(data),
                agg.fieldAvgCount,
                agg.valueUsedBytes,
                agg.valueAlignedBytes,
                agg.valueAlignedBytes / (agg.valueUsedBytes if agg.valueUsedBytes > 0 else 1),
                agg.system,
                agg.encoding,
                agg.total,
                agg.ttlMin,
                agg.ttlMax,
                agg.ttlAvg,
            ]

            key_stat['data'].append(stat_entry)

        key_stat['data'].sort(key=lambda x: x[8], reverse=True)
        key_stat['data'].append(make_total_row(key_stat['data'], ['Total:', sum, 0, sum, sum, 0, sum, '', sum, min, max, math.nan]))

        progress.close()

        return key_stat 
Example #21
Source Project: redis-memory-analyzer   Author: gamenet   File: List.py    License: MIT License 5 votes vote down vote up
def analyze(self, keys, total=0):
        key_stat = {
            'headers': ['Match', "Count", "Avg Count", "Min Count", "Max Count", "Stdev Count", "Value mem", "Real", "Ratio", "System", "Encoding", "Total", 'TTL Min', 'TTL Max', 'TTL Avg'],
            'data': []
        }

        progress = tqdm(total=total,
                        mininterval=1,
                        desc="Processing List patterns",
                        leave=False)

        for pattern, data in keys.items():
            agg = ListAggregator(progress_iterator((ListStatEntry(x, self.redis) for x in data), progress), len(data))

            stat_entry = [
                pattern,
                len(data),
                agg.fieldAvgCount,
                agg.fieldMinCount,
                agg.fieldMaxCount,
                agg.fieldStdev,
                agg.valueUsedBytes,
                agg.valueAlignedBytes,
                agg.valueAlignedBytes / (agg.valueUsedBytes if agg.valueUsedBytes > 0 else 1),
                agg.system,
                agg.encoding,
                agg.valueAlignedBytes + agg.system,
                agg.ttlMin,
                agg.ttlMax,
                agg.ttlAvg,
            ]

            key_stat['data'].append(stat_entry)
            progress.update()

        key_stat['data'].sort(key=lambda x: x[8], reverse=True)
        key_stat['data'].append(make_total_row(key_stat['data'], ['Total:', sum, 0, 0, 0, 0, sum, sum, 0, sum, '', sum, min, max, math.nan]))

        progress.close()

        return key_stat 
Example #22
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_any(self) -> None:
        HedgeAssert(self, fl.Any()) \
            .has_name("any") \
            .evaluates({-1.0: 1.0,
                        -0.5: 1.0,
                        0.00: 1.0,
                        0.25: 1.0,
                        0.50: 1.0,
                        0.75: 1.0,
                        1.00: 1.0,
                        inf: 1.0,
                        -inf: 1.0,
                        nan: 1.0}) 
Example #23
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_extremely(self) -> None:
        HedgeAssert(self, fl.Extremely()) \
            .has_name("extremely") \
            .evaluates({-1.0: 2.0,
                        -0.5: 0.5,
                        0.00: 0.0,
                        0.25: 0.125,
                        0.50: 0.5,
                        0.75: 0.875,
                        1.00: 1.0,
                        inf: -inf,
                        -inf: inf,
                        nan: nan}) 
Example #24
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not(self) -> None:
        HedgeAssert(self, fl.Not()) \
            .has_name("not") \
            .evaluates({-1.0: 2.0,
                        -0.5: 1.5,
                        0.00: 1.0,
                        0.25: 0.75,
                        0.50: 0.50,
                        0.75: 0.25,
                        1.00: 0.00,
                        inf: -inf,
                        -inf: inf,
                        nan: nan}) 
Example #25
Source Project: pyfuzzylite   Author: fuzzylite   File: test_hedge.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_function(self) -> None:
        HedgeAssert(self, fl.HedgeFunction(fl.Function.create("my_hedge", "x**2"))) \
            .has_name("my_hedge") \
            .evaluates({-1.0: 1.0,
                        -0.5: 0.25,
                        0.00: 0.0,
                        0.25: 0.0625,
                        0.50: 0.25,
                        0.75: 0.5625,
                        1.00: 1.0,
                        inf: inf,
                        -inf: inf,
                        nan: nan}) 
Example #26
Source Project: pyfuzzylite   Author: fuzzylite   File: test_variable.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clear(self) -> None:
        low, medium, high = [fl.Triangle('Low', -1.0, -1.0, 0.0),
                             fl.Triangle('Medium', -0.5, 0.0, 0.5),
                             fl.Triangle('High', 0.0, 1.0, 1.0)]
        variable = fl.OutputVariable(name="name",
                                     description="description",
                                     minimum=-1.0,
                                     maximum=1.0,
                                     terms=[low, medium, high])
        variable.value = 0.0
        variable.previous_value = -1.0
        variable.fuzzy.terms.extend([fl.Activated(term, 0.5) for term in variable.terms])
        OutputVariableAssert(self, variable) \
            .exports_fll("\n".join(["OutputVariable: name",
                                    "  description: description",
                                    "  enabled: true",
                                    "  range: -1.000 1.000",
                                    "  lock-range: false",
                                    "  aggregation: none",
                                    "  defuzzifier: none",
                                    "  default: nan",
                                    "  lock-previous: false",
                                    "  term: Low Triangle -1.000 -1.000 0.000",
                                    "  term: Medium Triangle -0.500 0.000 0.500",
                                    "  term: High Triangle 0.000 1.000 1.000",
                                    ]))

        self.assertEqual(variable.value, 0.0)
        self.assertEqual(variable.previous_value, -1.0)
        self.assertSequenceEqual([term.parameters() for term in variable.fuzzy.terms],
                                 ["(0.500*Low)", "(0.500*Medium)", "(0.500*High)"])
        variable.clear()
        self.assertEqual(math.isnan(variable.value), True)
        self.assertEqual(math.isnan(variable.previous_value), True)
        self.assertSequenceEqual(variable.fuzzy.terms, []) 
Example #27
Source Project: pyfuzzylite   Author: fuzzylite   File: test_term.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def has_membership(self, x: float, mf: float) -> 'TermAssert':
        message = "\n".join([f"{str(self.actual)}",
                             f"expected: \u03BC(x={x:.3f})={mf}, but"])
        if math.isnan(mf):
            self.test.assertEqual(str(fl.nan), str(self.actual.membership(x)), message)
            return self

        # TODO: Find out why we get different values in different platforms
        # compare against exact values on Mac OSX
        if platform.system() == 'Darwin':
            self.test.assertEqual(mf, self.actual.membership(x), message)
        else:  # use approximate values in other platforms
            self.test.assertAlmostEqual(mf, self.actual.membership(x), places=15, msg=message)
        return self 
Example #28
Source Project: pyfuzzylite   Author: fuzzylite   File: test_term.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_term(self) -> None:
        self.assertEqual(fl.Term().name, "")
        self.assertEqual(fl.Term("X").name, "X")
        self.assertEqual(fl.Term("X").height, 1.0)
        self.assertEqual(fl.Term("X", .5).height, .5)

        self.assertEqual(str(fl.Term("xxx", 0.5)), "term: xxx Term 0.500")
        self.assertEqual(fl.Term().is_monotonic(), False)

        with self.assertRaisesRegex(NotImplementedError, ""):
            fl.Term().membership(math.nan)
        with self.assertRaisesRegex(NotImplementedError, ""):
            fl.Term().tsukamoto(math.nan, math.nan, math.nan)

        # does nothing, for test coverage
        fl.Term().update_reference(None)

        discrete_triangle = fl.Triangle("triangle", -1.0, 0.0, 1.0).discretize(-1, 1, 10)
        self.assertEqual(fl.Discrete.dict_from(discrete_triangle.xy),
                         {-1.0: 0.0,
                          -0.8: 0.19999999999999996,
                          -0.6: 0.4,
                          -0.3999999999999999: 0.6000000000000001,
                          -0.19999999999999996: 0.8,
                          0.0: 1.0,
                          0.20000000000000018: 0.7999999999999998,
                          0.40000000000000013: 0.5999999999999999,
                          0.6000000000000001: 0.3999999999999999,
                          0.8: 0.19999999999999996,
                          1.0: 0.0}) 
Example #29
Source Project: pyfuzzylite   Author: fuzzylite   File: test_term.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_binary(self) -> None:
        TermAssert(self, fl.Binary("binary")) \
            .exports_fll("term: binary Binary nan nan") \
            .takes_parameters(2) \
            .is_not_monotonic() \
            .configured_as("0 inf") \
            .exports_fll("term: binary Binary 0.000 inf") \
            .has_memberships({-0.5: 0.0,
                              -0.4: 0.0,
                              -0.25: 0.0,
                              -0.1: 0.0,
                              0.0: 1.0,
                              0.1: 1.0,
                              0.25: 1.0,
                              0.4: 1.0,
                              0.5: 1.0,
                              math.nan: math.nan,
                              math.inf: 1.0,
                              -math.inf: 0.0}) \
            .configured_as("0 -inf 0.5") \
            .exports_fll("term: binary Binary 0.000 -inf 0.500") \
            .has_memberships({-0.5: 0.5,
                              -0.4: 0.5,
                              -0.25: 0.5,
                              -0.1: 0.5,
                              0.0: 0.5,
                              0.1: 0.0,
                              0.25: 0.0,
                              0.4: 0.0,
                              0.5: 0.0,
                              math.nan: math.nan,
                              math.inf: 0.0,
                              -math.inf: 0.5}) 
Example #30
Source Project: pyfuzzylite   Author: fuzzylite   File: test_term.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_concave(self) -> None:
        TermAssert(self, fl.Concave("concave")) \
            .exports_fll("term: concave Concave nan nan") \
            .takes_parameters(2) \
            .is_monotonic() \
            .configured_as("0.00 0.50") \
            .exports_fll("term: concave Concave 0.000 0.500") \
            .has_memberships({-0.5: 0.3333333333333333,
                              -0.4: 0.35714285714285715,
                              -0.25: 0.4,
                              -0.1: 0.45454545454545453,
                              0.0: 0.5,
                              0.1: 0.5555555555555556,
                              0.25: 0.6666666666666666,
                              0.4: 0.8333333333333334,
                              0.5: 1.0,
                              math.nan: math.nan,
                              math.inf: 1.0,
                              -math.inf: 0.0}) \
            .configured_as("0.00 -0.500 0.5") \
            .exports_fll("term: concave Concave 0.000 -0.500 0.500") \
            .has_memberships({-0.5: 0.5,
                              -0.4: 0.4166666666666667,
                              -0.25: 0.3333333333333333,
                              -0.1: 0.2777777777777778,
                              0.0: 0.25,
                              0.1: 0.22727272727272727,
                              0.25: 0.2,
                              0.4: 0.17857142857142858,
                              0.5: 0.16666666666666666,
                              math.nan: math.nan,
                              math.inf: 0.0,
                              -math.inf: 0.5})