Fuzzy Rules Functions#

Fuzzy Rules and Inference Engine for Ex-Fuzzy Library

This module contains the core classes and functions for fuzzy rule definition, management, and inference. It implements a complete fuzzy inference system supporting Type-1, Type-2, and General Type-2 fuzzy sets with various t-norm operations and defuzzification methods.

Main Components:
  • Rule classes: RuleSimple for individual rule representation

  • RuleBase classes: RuleBaseT1, RuleBaseT2, RuleBaseGT2 for rule collections

  • MasterRuleBase: Container for multiple rule bases (multi-class problems)

  • Inference engines: Support for Mamdani and Takagi-Sugeno inference

  • Defuzzification: Centroid, height, and other defuzzification methods

  • T-norm operations: Product, minimum, and other aggregation functions

The module supports complex fuzzy reasoning workflows including rule firing strength computation, aggregation across multiple rules, and final defuzzification to crisp outputs. It also includes support for rule modifiers (e.g., “very”, “somewhat”) and dominance scores for rule quality assessment.

ex_fuzzy.rules.compute_antecedents_memberships(antecedents, x)[source]#

Compute membership degrees for input values across all fuzzy variables.

This function calculates the membership degrees of input values for each linguistic variable in the antecedents. It returns a structured representation that can be used for efficient rule evaluation and inference.

Parameters:
  • antecedents (list[fs.fuzzyVariable]) – List of fuzzy variables representing the antecedents (input variables) of the fuzzy system

  • x (np.array) – Input vector with values for each antecedent variable. Shape should be (n_samples, n_variables) or (n_variables,) for single sample

Returns:

List containing membership dictionaries for each antecedent variable.

Each dictionary maps linguistic term indices to their membership degrees.

Return type:

list[dict]

Example

>>> # For 2 variables with 3 linguistic terms each
>>> antecedents = [temp_var, pressure_var]
>>> x = np.array([25.0, 101.3])  # temperature=25°C, pressure=101.3kPa
>>> memberships = compute_antecedents_memberships(antecedents, x)
>>> # memberships[0] contains temperature memberships: {0: 0.2, 1: 0.8, 2: 0.0}
>>> # memberships[1] contains pressure memberships: {0: 0.0, 1: 0.6, 2: 0.4}

Note

This function is typically used internally during rule evaluation but can be useful for debugging membership degree calculations or analyzing input fuzzification.

exception ex_fuzzy.rules.RuleError(message)[source]#

Bases: Exception

Exception raised when a fuzzy rule is incorrectly defined or invalid.

This exception is used throughout the rules module to indicate various rule-related errors such as invalid antecedent specifications, inconsistent membership functions, or malformed rule structures.

message#

Human-readable description of the error

Type:

str

Example

>>> try:
...     rule = RuleSimple([-1, -1, -1], 0)  # Invalid: all don't-care antecedents
... except RuleError as e:
...     print(f"Rule error: {e}")
__init__(message)[source]#

Initialize the RuleError exception.

Parameters:

message (str) – Descriptive error message explaining what went wrong

class ex_fuzzy.rules.Rule(antecedents, consequent)[source]#

Bases: object

Class of Rule designed to work with one single rule. It contains the whole inference functionally in itself.

__init__(antecedents, consequent)[source]#

Creates a rule with the given antecedents and consequent.

Parameters:
  • antecedents (list[FS]) – list of fuzzy sets.

  • consequent (FS) – fuzzy set.

membership(x, tnorm=<function _myprod>)[source]#

Computes the membership of one input to the antecedents of the rule.

Parameters:
  • x (array) – input to compute the membership.

  • tnorm – t-norm to use in the inference process.

consequent_centroid()[source]#

Returns the centroid of the consequent using a Karnik and Mendel algorithm.

class ex_fuzzy.rules.RuleSimple(antecedents, consequent=0, modifiers=None)[source]#

Bases: object

Simplified Rule Representation for Optimized Computation.

This class represents fuzzy rules in a simplified format optimized for computational efficiency in rule base operations. It uses integer encoding for antecedents and consequents to minimize memory usage and speed up rule evaluation processes.

antecedents#

Integer-encoded antecedents where: - -1: Variable not used in the rule - 0-N: Index of the linguistic variable used for the ith input

Type:

list[int]

consequent#

Integer index of the consequent linguistic variable

Type:

int

modifiers#

Optional modifiers for rule adaptation

Type:

np.array

Example

>>> # Rule: IF x1 is Low AND x2 is High THEN y is Medium
>>> # Assuming Low=0, High=1, Medium=1
>>> rule = RuleSimple([0, 1], consequent=1)
>>> print(rule.antecedents)  # [0, 1]
>>> print(rule.consequent)  # 1

Note

This simplified representation is designed for high-performance rule evaluation in large rule bases where memory and speed are critical.

__init__(antecedents, consequent=0, modifiers=None)[source]#

Creates a rule with the given antecedents and consequent.

Parameters:
  • antecedents (list[int]) – List of integers indicating the linguistic variable used for each input (-1 for unused variables)

  • consequent (int, optional) – Integer indicating the linguistic variable used for the consequent. Defaults to 0.

  • modifiers (np.array, optional) – Array of modifier values for rule adaptation. Defaults to None.

Example

>>> # Create a rule with two antecedents and one consequent
>>> rule = RuleSimple([0, 2, -1], consequent=1)  # x1=0, x2=2, x3=unused, y=1
__getitem__(ix)[source]#

Returns the antecedent value for the given index.

Parameters:

ix (int) – Index of the antecedent to return

Returns:

The antecedent value at the specified index

Return type:

int

Example

>>> rule = RuleSimple([0, 1, 2])
>>> print(rule[1])  # 1
__setitem__(ix, value)[source]#

Sets the antecedent value for the given index.

Parameters:
  • ix (int) – Index of the antecedent to set

  • value (int) – Value to set at the specified index

Example

>>> rule = RuleSimple([0, 1, 2])
>>> rule[1] = 3  # Change second antecedent to 3
__str__()[source]#

Returns a string representation of the rule.

Returns:

Human-readable string representation of the rule

Return type:

str

Example

>>> rule = RuleSimple([0, 1], consequent=2)
>>> print(rule)  # Rule: antecedents: [0, 1] consequent: 2
__len__()[source]#

Returns the number of antecedents in the rule.

Returns:

Number of antecedents in the rule

Return type:

int

Example

>>> rule = RuleSimple([0, 1, 2])
>>> print(len(rule))  # 3
__eq__(other)[source]#

Returns True if the two rules are equal.

Parameters:

other (RuleSimple) – Another rule to compare with

Returns:

True if rules have identical antecedents and consequent

Return type:

bool

Example

>>> rule1 = RuleSimple([0, 1], consequent=2)
>>> rule2 = RuleSimple([0, 1], consequent=2)
>>> print(rule1 == rule2)  # True
__hash__()[source]#

Returns the hash of the rule.

class ex_fuzzy.rules.RuleBase(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Bases: object

Class optimized to work with multiple rules at the same time. Right now supports only one consequent. (Solution: use one rulebase per consequent to study)

__init__(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Creates a rulebase with the given antecedents, rules and consequent.

Parameters:
  • antecedents (list[fuzzyVariable]) – list of fuzzy sets.

  • rules (list[RuleSimple]) – list of rules.

  • consequent (fuzzyVariable) – fuzzy set.

  • tnorm – t-norm to use in the inference process.

  • fuzzy_modifiers – array with the fuzzy modifiers for each rule. If None, no modifiers are used. (Fuzzy modifiers are modifiers to the antecedent memberships, also known as linguistic hedges). Only exponentiation is supported. (x**a, being a the modifier in the matrix). Defaults to None. They can also be specified in the RuleSimple list of rules.

get_rules()[source]#

Returns the list of rules in the rulebase.

add_rule(new_rule)[source]#

Adds a new rule to the rulebase. :param new_rule: rule to add.

add_rules(new_rules)[source]#

Adds a list of new rules to the rulebase.

Parameters:

new_rules (list[RuleSimple]) – list of rules to add.

remove_rule(ix)[source]#

Removes the rule in the given index. :param ix: index of the rule to remove.

remove_rules(delete_list)[source]#

Removes the rules in the given list of indexes.

Parameters:

delete_list (list[int]) – list of indexes of the rules to remove.

get_rulebase_matrix()[source]#

Returns a matrix with the antecedents values for each rule.

get_scores()[source]#

Returns an array with the dominance score for each rule. (Must been already computed by an evalRule object)

get_weights()[source]#

Returns an array with the weights for each rule. (Different from dominance scores: must been already computed by an optimization algorithm)

delete_rule_duplicates(list_rules)[source]#
compute_antecedents_memberships(x)[source]#

Returns a list of of dictionaries that contains the memberships for each x value to the ith antecedents, nth linguistic variable. x must be a vector (only one sample)

Parameters:

x (array) – vector with the values of the inputs.

Returns:

a list with the antecedent truth values for each one. Each list is comprised of a list with n elements, where n is the number of linguistic variables in each variable.

Return type:

list[dict]

compute_rule_antecedent_memberships(x, scaled=False, antecedents_memberships=None)[source]#

Computes the antecedent truth value of an input array.

Return an array in shape samples x rules (x 2) (last is iv dimension)

Parameters:
  • x (array) – array with the values of the inputs.

  • scaled – if True, the memberships are scaled according to their sums for each sample.

Returns:

array with the memberships of the antecedents for each rule.

Return type:

array

print_rules(return_rules=False, bootstrap_results=True)[source]#

Print the rules from the rule base.

Parameters:

return_rules (bool) – if True, the rules are returned as a string.

abstract inference(x)[source]#

Computes the fuzzy output of the fl inference system.

Return an array in shape samples x 2 (last is iv dimension)

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the memberships of the consequents for each rule.

Return type:

array

abstract forward(x)[source]#

Computes the deffuzified output of the fl inference system.

Return a vector of size (samples, )

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the deffuzified output.

Return type:

array

abstract fuzzy_type()[source]#

Returns the corresponding type of the RuleBase using the enum type in the fuzzy_sets module.

Returns:

the type of fuzzy set used in the RuleBase.

Return type:

FUZZY_SETS

__len__()[source]#

Returns the number of rules in the rule base.

prune_bad_rules(tolerance=0.01)[source]#

Delete the rules from the rule base that do not have a dominance score superior to the threshold or have 0 accuracy in the training set.

Parameters:

tolerance – threshold for the dominance score.

scores()[source]#

Returns the dominance score for each rule.

Returns:

array with the dominance score for each rule.

Return type:

array

__getitem__(item)[source]#

Returns the corresponding rulebase.

Parameters:

item (int) – index of the rule.

Returns:

the corresponding rule.

Return type:

RuleSimple

__setitem__(key, value)[source]#

Set the corresponding rule.

Parameters:
  • key (int) – index of the rule.

  • value (RuleSimple) – new rule.

__iter__()[source]#

Returns an iterator for the rule base.

__str__()[source]#

Returns a string with the rules in the rule base.

__eq__(other)[source]#

Returns True if the two rule bases are equal.

__hash__()[source]#

Returns the hash of the rule base.

__add__(other)[source]#

Adds two rule bases.

n_linguistic_variables()[source]#

Returns the number of linguistic variables in the rule base.

print_rule_bootstrap_results()[source]#

Prints the bootstrap results for each rule.

copy()[source]#

Creates a copy of the RuleBase.

Parameters:

deep – if True, creates a deep copy. If False, creates a shallow copy.

Returns:

a copy of the RuleBase.

class ex_fuzzy.rules.RuleBaseT2(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Bases: RuleBase

Class optimized to work with multiple rules at the same time. Supports only one consequent. (Use one rulebase per consequent to study classification problems. Check MasterRuleBase class for more documentation)

This class supports iv approximation for t2 fs.

__init__(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Constructor of the RuleBaseT2 class.

Parameters:
  • antecedents (list[fuzzyVariable]) – list of fuzzy variables that are the antecedents of the rules.

  • rules (list[RuleSimple]) – list of rules.

  • consequent (fuzzyVariable) – fuzzy variable that is the consequent of the rules.

  • tnorm – t-norm used to compute the fuzzy output.

inference(x)[source]#

Computes the iv output of the t2 inference system.

Return an array in shape samples x 2 (last is iv dimension)

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the memberships of the consequents for each sample.

Return type:

array

forward(x)[source]#

Computes the deffuzified output of the t2 inference system.

Return a vector of size (samples, )

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the deffuzified output for each sample.

Return type:

array

fuzzy_type()[source]#

Returns the correspoing type of the RuleBase using the enum type in the fuzzy_sets module.

Returns:

the corresponding fuzzy set type of the RuleBase.

Return type:

FUZZY_SETS

class ex_fuzzy.rules.RuleBaseGT2(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Bases: RuleBase

Class optimized to work with multiple rules at the same time. Supports only one consequent. (Use one rulebase per consequent to study classification problems. Check MasterRuleBase class for more documentation)

This class supports gt2 fs. (ONLY FOR CLASSIFICATION PROBLEMS)

__init__(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Constructor of the RuleBaseGT2 class.

Parameters:
  • antecedents (list[fuzzyVariable]) – list of fuzzy variables that are the antecedents of the rules.

  • rules (list[RuleSimple]) – list of rules.

  • consequent (fuzzyVariable) – fuzzy variable that is the consequent of the rules.

  • tnorm – t-norm used to compute the fuzzy output.

inference(x)[source]#

Computes the output of the gt2 inference system.

Return an array in shape samples x alpha_cuts

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the memberships of the consequents for each sample.

Return type:

array

forward(x)[source]#

Computes the deffuzified output of the t2 inference system.

Return a vector of size (samples, )

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the deffuzified output for each sample.

Return type:

array

fuzzy_type()[source]#

Returns the correspoing type of the RuleBase using the enum type in the fuzzy_sets module.

Returns:

the corresponding fuzzy set type of the RuleBase.

Return type:

FUZZY_SETS

compute_rule_antecedent_memberships(x, scaled=True, antecedents_memberships=None)[source]#

Computes the membership for the antecedents performing the alpha_cut reduction.

Parameters:
  • x (array) – array with the values of the inputs.

  • scaled – if True, the memberships are scaled to sum 1 in each sample.

  • antecedents_memberships – precomputed antecedent memberships. Not supported for GT2.

Returns:

array with the memberships of the antecedents for each sample.

Return type:

array

alpha_compute_rule_antecedent_memberships(x, scaled=True, antecedents_memberships=None)[source]#

Computes the membership for the antecedents for all the alpha cuts.

Parameters:
  • x (array) – array with the values of the inputs.

  • scaled – if True, the memberships are scaled to sum 1 in each sample.

  • antecedents_memberships – precomputed antecedent memberships. Not supported for GT2.

Returns:

array with the memberships of the antecedents for each sample.

Return type:

array

class ex_fuzzy.rules.RuleBaseT1(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Bases: RuleBase

Class optimized to work with multiple rules at the same time. Supports only one consequent. (Use one rulebase per consequent to study classification problems. Check MasterRuleBase class for more documentation)

This class supports t1 fs.

__init__(antecedents, rules, consequent=None, tnorm=<function prod>)[source]#

Constructor of the RuleBaseT1 class.

Parameters:
  • antecedents (list[fuzzyVariable]) – list of fuzzy variables that are the antecedents of the rules.

  • rules (list[RuleSimple]) – list of rules.

  • consequent (fuzzyVariable) – fuzzy variable that is the consequent of the rules. ONLY on regression problems.

  • tnorm – t-norm used to compute the fuzzy output.

inference(x)[source]#

Computes the output of the t1 inference system.

Return an array in shape samples.

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the output of the inference system for each sample.

Return type:

array

forward(x)[source]#

Same as inference() in the t1 case.

Return a vector of size (samples, )

Parameters:

x (array) – array with the values of the inputs.

Returns:

array with the deffuzified output for each sample.

Return type:

array

fuzzy_type()[source]#

Returns the correspoing type of the RuleBase using the enum type in the fuzzy_sets module.

Returns:

the corresponding fuzzy set type of the RuleBase.

Return type:

FUZZY_SETS

class ex_fuzzy.rules.MasterRuleBase(rule_base, consequent_names=None, ds_mode=0, allow_unknown=False)[source]#

Bases: object

This Class encompasses a list of rule bases where each one corresponds to a different class.

__init__(rule_base, consequent_names=None, ds_mode=0, allow_unknown=False)[source]#

Constructor of the MasterRuleBase class.

Parameters:

rule_base (list[RuleBase]) – list of rule bases.

rename_cons(consequent_names)[source]#

Renames the consequents of the rule base.

add_rule(rule, consequent)[source]#

Adds a rule to the rule base of the given consequent.

Parameters:
  • rule (RuleSimple) – rule to add.

  • consequent (int) – index of the rule base to add the rule.

get_consequents()[source]#

Returns a list with the consequents of each rule base.

Returns:

list with the consequents of each rule base.

Return type:

list[int]

get_consequents_names()[source]#

Returns a list with the names of the consequents.

Returns:

list with the names of the consequents.

Return type:

list[str]

get_rulebase_matrix()[source]#

Returns a list with the rulebases for each antecedent in matrix format.

Returns:

list with the rulebases for each antecedent in matrix format.

Return type:

list[array]

get_scores()[source]#

Returns the dominance score for each rule in all the rulebases.

Returns:

array with the dominance score for each rule in all the rulebases.

Return type:

array

get_weights()[source]#

Returns the weights for each rule in all the rulebases.

Returns:

array with the weights for each rule in all the rulebases.

Return type:

array

compute_firing_strenghts(X, precomputed_truth=None)[source]#

Computes the firing strength of each rule for each sample.

Parameters:
  • X – array with the values of the inputs.

  • precomputed_truth – if not None, the antecedent memberships are already computed. (Used for sped up in genetic algorithms)

Returns:

array with the firing strength of each rule for each sample.

Return type:

array

compute_association_degrees(X, precomputed_truth=None)[source]#

Returns the winning rule for each sample. Takes into account dominance scores if already computed. :param X: array with the values of the inputs. :return: array with the winning rule for each sample.

winning_rule_predict(X, precomputed_truth=None, out_class_names=False)[source]#

Returns the winning rule for each sample. Takes into account dominance scores if already computed.

Parameters:
  • X (array) – array with the values of the inputs.

  • precomputed_truth – if not None, the antecedent memberships are already computed. (Used for sped up in genetic algorithms)

Returns:

array with the winning rule for each sample.

Return type:

array

explainable_predict(X, out_class_names=False, precomputed_truth=None)[source]#

Returns the predicted class for each sample.

Parameters:
  • X (array) – array with the values of the inputs.

  • out_class_names – if True, the output will be the class names instead of the class index.

Returns:

np array samples (x 1) with the predicted class.

Return type:

array

add_rule_base(rule_base)[source]#

Adds a rule base to the list of rule bases.

Parameters:

rule_base (RuleBase) – rule base to add.

print_rules(return_rules=False, bootstrap_results=True)[source]#

Print all the rules for all the consequents.

Parameters:

autoprint – if True, the rules are printed. If False, the rules are returned as a string.

print_rule_bootstrap_results()[source]#

Prints the bootstrap results for each rule.

get_rules()[source]#

Returns a list with all the rules.

Returns:

list with all the rules.

Return type:

list[RuleSimple]

fuzzy_type()[source]#

Returns the correspoing type of the RuleBase using the enum type in the fuzzy_sets module.

Returns:

the corresponding fuzzy set type of the RuleBase.

Return type:

FUZZY_SETS

purge_rules(tolerance=0.001)[source]#

Delete the roles with a dominance score lower than the tolerance.

Parameters:

tolerance – tolerance to delete the rules.

__getitem__(item)[source]#

Returns the corresponding rulebase.

Parameters:

item – index of the rulebase.

Returns:

the corresponding rulebase.

Return type:

RuleBase

__len__()[source]#

Returns the number of rule bases.

__str__()[source]#

Returns a string with the rules for each consequent.

__eq__(_MasterRuleBase__value)[source]#

Returns True if the two rule bases are equal.

Parameters:

__value – object to compare.

Returns:

True if the two rule bases are equal.

Return type:

bool

__call__(X)[source]#

Gives the prediction for each sample (same as winning_rule_predict)

Parameters:

X (array) – array of dims: samples x features.

Returns:

vector of predictions, size: samples,

Return type:

array

predict(X)[source]#

Gives the prediction for each sample (same as winning_rule_predict)

Parameters:

X (array) – array of dims: samples x features.

Returns:

vector of predictions, size: samples,

Return type:

array

get_rulebases()[source]#

Returns a list with all the rules.

Returns:

list

Return type:

list[RuleBase]

n_linguistic_variables()[source]#

Returns the number of linguistic variables in the rule base.

get_antecedents()[source]#

Returns the antecedents of the rule base.

copy(deep=True)[source]#

Creates a copy of the MasterRuleBase.

Parameters:

deep – if True, creates a deep copy. If False, creates a shallow copy.

Returns:

a copy of the MasterRuleBase.

ex_fuzzy.rules.construct_rule_base(rule_matrix, nclasses, consequents, antecedents, rule_weights, class_names=None)[source]#

Constructs a rule base from a matrix of rules.

Parameters:
  • rule_matrix (array) – matrix with the rules.

  • consequents (array) – array with the consequents per rule.

  • antecedents (list[fuzzyVariable]) – list of fuzzy variables.

  • class_names (list) – list with the names of the classes.

ex_fuzzy.rules.list_rules_to_matrix(rule_list)[source]#

Returns a matrix out of the rule list.

Parameters:

rule_list (list[RuleSimple]) – list of rules.

Returns:

matrix with the antecedents of the rules.

Return type:

array

ex_fuzzy.rules.generate_rule_string(rule, antecedents, bootstrap_results=True)[source]#

Generates a string with the rule.

Parameters:
  • rule (RuleSimple) – rule to generate the string.

  • antecedents (list) – list of fuzzy variables.

  • modifiers – array with the modifiers for the antecedents.