Models API¶
fuzzy_infer.models
¶
Data models for the FuzzyInfer system.
This module provides dataclasses for Facts, Rules, Conditions, and Actions with validation and pythonic interfaces.
Fact
dataclass
¶
Represents a fuzzy fact in the knowledge base.
Attributes:
-
predicate(str) –The predicate name (e.g., 'is-zebra')
-
args(List[Union[str, Any]]) –List of arguments for the predicate
-
degree(float) –Degree of membership (0.0 to 1.0)
Examples:
to_dict
¶
from_dict
classmethod
¶
Create a Fact from dictionary representation.
Source code in fuzzy_infer/models.py
matches_pattern
¶
matches_pattern(
pattern: Fact, bindings: Optional[Dict[str, Any]] = None
) -> Tuple[bool, Dict[str, Any]]
Check if this fact matches a pattern with variables.
Parameters:
-
pattern(Fact) –Pattern fact potentially containing variables (e.g., '?x')
-
bindings(Optional[Dict[str, Any]], default:None) –Existing variable bindings
Returns:
-
Tuple[bool, Dict[str, Any]]–Tuple of (matches: bool, updated_bindings: dict)
Source code in fuzzy_infer/models.py
Condition
dataclass
¶
Condition(
predicate: Optional[str] = None,
args: List[Union[str, Any]] = list(),
degree_var: Optional[str] = None,
degree_constraint: Optional[List[Any]] = None,
negated: bool = False,
or_conditions: Optional[List[Condition]] = None,
and_conditions: Optional[List[Condition]] = None,
)
Represents a condition in a rule.
Attributes:
-
predicate(Optional[str]) –The predicate to match
-
args(List[Union[str, Any]]) –Arguments (can contain variables like '?x')
-
degree_var(Optional[str]) –Variable to bind the degree to
-
degree_constraint(Optional[List[Any]]) –Optional constraint on degree (e.g., ['>', '?d', 0.5])
-
negated(bool) –Whether this is a negated condition
-
or_conditions(Optional[List[Condition]]) –List of OR'ed conditions
-
and_conditions(Optional[List[Condition]]) –List of AND'ed conditions
from_dict
classmethod
¶
Create a Condition from dictionary representation.
Source code in fuzzy_infer/models.py
to_dict
¶
Convert to dictionary representation.
Source code in fuzzy_infer/models.py
Action
dataclass
¶
Represents an action to take when a rule fires.
Attributes:
-
action_type(str) –Type of action ('add', 'remove', 'modify')
-
fact(Dict[str, Any]) –Fact to add/remove/modify
Rule
dataclass
¶
Rule(
conditions: List[Condition],
actions: List[Action],
name: Optional[str] = None,
priority: int = 0,
)
Represents a production rule with conditions and actions.
Attributes:
-
conditions(List[Condition]) –List of conditions that must be satisfied
-
actions(List[Action]) –List of actions to execute when conditions are met
-
name(Optional[str]) –Optional name for the rule
-
priority(int) –Priority for rule execution (higher = earlier)
to_dict
¶
Convert rule to dictionary representation.
Source code in fuzzy_infer/models.py
from_dict
classmethod
¶
Create a Rule from dictionary representation.
Source code in fuzzy_infer/models.py
RuleBuilder
¶
Builder pattern for constructing complex rules.
Example
rule = (RuleBuilder() ... .when('is-zebra', ['?x']) ... .with_degree_greater_than(0.5) ... .then_add('has-stripes', ['?x']) ... .with_degree_multiplied_by(0.9) ... .build())
Initialize the builder.
Source code in fuzzy_infer/models.py
when
¶
Add a condition to the rule.
when_not
¶
Add a negated condition to the rule.
Source code in fuzzy_infer/models.py
with_degree_greater_than
¶
Add a degree constraint to the current condition.
Source code in fuzzy_infer/models.py
with_degree_less_than
¶
Add a degree constraint to the current condition.
Source code in fuzzy_infer/models.py
then_add
¶
Add an action to add a fact.
Source code in fuzzy_infer/models.py
then_remove
¶
Add an action to remove a fact.
Source code in fuzzy_infer/models.py
with_degree_multiplied_by
¶
Modify the degree of the current action's fact.
Source code in fuzzy_infer/models.py
named
¶
with_priority
¶
Overview¶
The fuzzy_infer.models module provides data classes for representing facts, rules, conditions, and actions in the fuzzy inference system.
Classes¶
Fact¶
Represents a fuzzy fact in the knowledge base.
Attributes:
-
predicate(str) –The predicate name (e.g., 'is-zebra')
-
args(List[Union[str, Any]]) –List of arguments for the predicate
-
degree(float) –Degree of membership (0.0 to 1.0)
Examples:
__post_init__
¶
Validate the fact after initialization.
Source code in fuzzy_infer/models.py
to_dict
¶
from_dict
classmethod
¶
Create a Fact from dictionary representation.
Source code in fuzzy_infer/models.py
matches_pattern
¶
matches_pattern(
pattern: Fact, bindings: Optional[Dict[str, Any]] = None
) -> Tuple[bool, Dict[str, Any]]
Check if this fact matches a pattern with variables.
Parameters:
-
pattern(Fact) –Pattern fact potentially containing variables (e.g., '?x')
-
bindings(Optional[Dict[str, Any]], default:None) –Existing variable bindings
Returns:
-
Tuple[bool, Dict[str, Any]]–Tuple of (matches: bool, updated_bindings: dict)
Source code in fuzzy_infer/models.py
__hash__
¶
__eq__
¶
Check equality based on predicate and arguments (not degree).
Examples¶
from fuzzy_infer import Fact
# Create facts
fact1 = Fact("is-bird", ["tweety"], 0.9)
fact2 = Fact("temperature", ["room-1", "hot"], 0.75)
fact3 = Fact("is-tall", ["john"]) # degree defaults to 1.0
# Convert to/from dict
fact_dict = fact1.to_dict()
# {'pred': 'is-bird', 'args': ['tweety'], 'deg': 0.9}
new_fact = Fact.from_dict(fact_dict)
# Pattern matching
pattern = Fact("is-bird", ["?x"], 1.0)
matches, bindings = fact1.matches_pattern(pattern)
# matches=True, bindings={'?x': 'tweety'}
Rule¶
Represents a production rule with conditions and actions.
Attributes:
-
conditions(List[Condition]) –List of conditions that must be satisfied
-
actions(List[Action]) –List of actions to execute when conditions are met
-
name(Optional[str]) –Optional name for the rule
-
priority(int) –Priority for rule execution (higher = earlier)
__post_init__
¶
Validate the rule.
to_dict
¶
Convert rule to dictionary representation.
Source code in fuzzy_infer/models.py
from_dict
classmethod
¶
Create a Rule from dictionary representation.
Source code in fuzzy_infer/models.py
Examples¶
from fuzzy_infer import Rule
# Simple rule
rule = Rule(
name="birds-fly",
conditions=[
{"pred": "is-bird", "args": ["?x"]}
],
actions=[
{"action": "add", "fact": {"pred": "can-fly", "args": ["?x"], "deg": 0.9}}
]
)
# Rule with degree constraints
rule = Rule(
name="confident-classification",
conditions=[
{"pred": "is-mammal", "args": ["?x"], "deg": "?d", "deg-pred": [">", "?d", 0.7]}
],
actions=[
{"action": "add", "fact": {"pred": "warm-blooded", "args": ["?x"], "deg": "?d"}}
]
)
# Rule with priority
rule = Rule(
name="exception-rule",
priority=100,
conditions=[{"pred": "is-penguin", "args": ["?x"]}],
actions=[{"action": "add", "fact": {"pred": "can-fly", "args": ["?x"], "deg": 0.1}}]
)
# Convert to/from dict
rule_dict = rule.to_dict()
new_rule = Rule.from_dict(rule_dict)
Condition¶
Represents a condition in a rule.
Attributes:
-
predicate(Optional[str]) –The predicate to match
-
args(List[Union[str, Any]]) –Arguments (can contain variables like '?x')
-
degree_var(Optional[str]) –Variable to bind the degree to
-
degree_constraint(Optional[List[Any]]) –Optional constraint on degree (e.g., ['>', '?d', 0.5])
-
negated(bool) –Whether this is a negated condition
-
or_conditions(Optional[List[Condition]]) –List of OR'ed conditions
-
and_conditions(Optional[List[Condition]]) –List of AND'ed conditions
degree_constraint
class-attribute
instance-attribute
¶
and_conditions
class-attribute
instance-attribute
¶
__post_init__
¶
from_dict
classmethod
¶
Create a Condition from dictionary representation.
Source code in fuzzy_infer/models.py
to_dict
¶
Convert to dictionary representation.
Source code in fuzzy_infer/models.py
Examples¶
from fuzzy_infer.models import Condition
# Simple condition
cond = Condition(
predicate="is-bird",
args=["?x"]
)
# Condition with degree variable
cond = Condition(
predicate="is-mammal",
args=["?x"],
degree_var="?d"
)
# Condition with degree constraint
cond = Condition(
predicate="confidence",
args=["?x"],
degree_var="?d",
degree_constraint=[">", "?d", 0.8]
)
# Negated condition
cond = Condition(
predicate="is-cold",
args=["?room"],
negated=True
)
# Convert to dict
cond_dict = cond.to_dict()
Action¶
Represents an action to take when a rule fires.
Attributes:
-
action_type(str) –Type of action ('add', 'remove', 'modify')
-
fact(Dict[str, Any]) –Fact to add/remove/modify
Examples¶
from fuzzy_infer.models import Action
# Add action
action = Action(
action="add",
fact={"pred": "can-fly", "args": ["?x"], "deg": 0.9}
)
# Add with computed degree
action = Action(
action="add",
fact={"pred": "result", "args": ["?x"], "deg": ["*", "?d", 0.85]}
)
# Modify action
action = Action(
action="modify",
fact={"pred": "confidence", "args": ["?x"], "deg": ["*", "?d", 1.1]}
)
# Retract action
action = Action(
action="retract",
predicate="temporary",
args=["?x"]
)
# Convert to dict
action_dict = action.to_dict()
new_action = Action.from_dict(action_dict)
RuleBuilder¶
Builder pattern for constructing complex rules.
Example
rule = (RuleBuilder() ... .when('is-zebra', ['?x']) ... .with_degree_greater_than(0.5) ... .then_add('has-stripes', ['?x']) ... .with_degree_multiplied_by(0.9) ... .build())
Initialize the builder.
Source code in fuzzy_infer/models.py
when
¶
Add a condition to the rule.
when_not
¶
Add a negated condition to the rule.
Source code in fuzzy_infer/models.py
with_degree_greater_than
¶
Add a degree constraint to the current condition.
Source code in fuzzy_infer/models.py
with_degree_less_than
¶
Add a degree constraint to the current condition.
Source code in fuzzy_infer/models.py
then_add
¶
Add an action to add a fact.
Source code in fuzzy_infer/models.py
then_remove
¶
Add an action to remove a fact.
Source code in fuzzy_infer/models.py
with_degree_multiplied_by
¶
Modify the degree of the current action's fact.
Source code in fuzzy_infer/models.py
named
¶
with_priority
¶
Examples¶
from fuzzy_infer.models import RuleBuilder
# Fluent rule construction
rule = (
RuleBuilder("carnivore-rule")
.when("eats-meat", ["?x"])
.when("has-teeth", ["?x"], min_degree=0.5)
.then_add("is-carnivore", ["?x"], degree=0.9)
.with_priority(10)
.build()
)
# Multiple conditions
rule = (
RuleBuilder("flying-bird")
.when("is-bird", ["?x"], degree_var="?d1")
.when("has-wings", ["?x"], degree_var="?d2")
.then_add("can-fly", ["?x"], degree=["*", ["min", "?d1", "?d2"], 0.9])
.build()
)
# Multiple actions
rule = (
RuleBuilder("complex-inference")
.when("input", ["?x"])
.then_add("output1", ["?x"], degree=0.8)
.then_add("output2", ["?x"], degree=0.9)
.then_modify("confidence", ["?x"], degree=["*", "?d", 1.2])
.build()
)
Type Hints¶
from typing import Dict, List, Any, Optional
from fuzzy_infer.models import Fact, Rule, Condition, Action
# Fact type hints
def process_fact(fact: Fact) -> None: ...
# Rule type hints
def add_rules(rules: List[Rule]) -> None: ...
# Condition type hints
def check_condition(cond: Condition, bindings: Dict[str, Any]) -> bool: ...
# Action type hints
def execute_action(action: Action, bindings: Dict[str, Any]) -> Optional[Fact]: ...
JSON Serialization¶
All models support JSON serialization:
import json
from fuzzy_infer import Fact, Rule
# Fact
fact = Fact("is-bird", ["tweety"], 0.9)
json_str = json.dumps(fact.to_dict())
# '{"pred": "is-bird", "args": ["tweety"], "deg": 0.9}'
loaded_fact = Fact.from_dict(json.loads(json_str))
# Rule
rule = Rule(
name="test-rule",
conditions=[{"pred": "is-bird", "args": ["?x"]}],
actions=[{"action": "add", "fact": {"pred": "can-fly", "args": ["?x"]}}]
)
json_str = json.dumps(rule.to_dict())
loaded_rule = Rule.from_dict(json.loads(json_str))