Core Module API¶
fuzzy_infer.core
¶
Core inference engine for the FuzzyInfer system.
This module contains the main FuzzyInfer class that implements forward-chaining fuzzy inference with proper type hints and modern Python patterns.
FuzzyInfer
¶
Production rule system for fuzzy inference.
This class implements a forward-chaining inference engine with fuzzy logic support, allowing for reasoning with uncertain information and degrees of belief.
Attributes:
-
facts(Dict[Tuple[str, Tuple], Fact]) –Set of facts in the knowledge base
-
rules(List[Rule]) –List of production rules
-
inference_log(List[str]) –Log of inference steps for debugging
-
max_iterations–Maximum iterations for inference loop
Examples:
>>> # Basic usage
>>> inf = FuzzyInfer()
>>> inf.add_fact(Fact('is-zebra', ['sam'], 0.8))
>>> inf.add_rule(RuleBuilder()
... .when('is-zebra', ['?x'])
... .with_degree_greater_than(0.5)
... .then_add('has-stripes', ['?x'])
... .with_degree_multiplied_by(0.9)
... .build())
>>> inf.run()
>>> results = inf.query('has-stripes', ['sam'])
>>> # Fluent API
>>> inf = (FuzzyInfer()
... .add_fact(Fact('is-person', ['alice'], 1.0))
... .add_fact(Fact('is-tall', ['alice'], 0.7))
... .add_rule(tall_person_rule)
... .run())
>>> # Context manager
>>> with FuzzyInfer.session() as inf:
... inf.add_facts(facts)
... inf.add_rules(rules)
... inf.run()
... results = inf.query('target-pred', ['arg'])
Initialize the FuzzyInfer inference engine.
Parameters:
-
max_iterations(int, default:100) –Maximum number of inference iterations
Source code in fuzzy_infer/core.py
session
classmethod
¶
Create a FuzzyInfer session as a context manager.
Yields:
-
FuzzyInfer(FuzzyInfer) –Configured inference engine
Examples:
>>> with FuzzyInfer.session(max_iterations=50) as inf:
... inf.add_facts(facts)
... results = inf.run()
Source code in fuzzy_infer/core.py
add_fact
¶
Add a single fact to the knowledge base.
Parameters:
-
fact(Union[Fact, Dict[str, Any]]) –Fact object or dictionary representation
Returns:
-
FuzzyInfer–Self for method chaining
Examples:
>>> inf.add_fact(Fact('is-person', ['sam'], 1.0))
>>> inf.add_fact({'pred': 'is-tall', 'args': ['sam'], 'deg': 0.8})
Source code in fuzzy_infer/core.py
add_facts
¶
Add multiple facts to the knowledge base.
Parameters:
-
facts(List[Union[Fact, Dict[str, Any]]]) –List of Fact objects or dictionary representations
Returns:
-
FuzzyInfer–Self for method chaining
Source code in fuzzy_infer/core.py
add_rule
¶
Add a single rule to the rule base.
Parameters:
-
rule(Union[Rule, Dict[str, Any]]) –Rule object or dictionary representation
Returns:
-
FuzzyInfer–Self for method chaining
Source code in fuzzy_infer/core.py
add_rules
¶
Add multiple rules to the rule base.
Parameters:
-
rules(List[Union[Rule, Dict[str, Any]]]) –List of Rule objects or dictionary representations
Returns:
-
FuzzyInfer–Self for method chaining
Source code in fuzzy_infer/core.py
run
¶
Execute the forward-chaining inference process.
Parameters:
-
max_iterations(Optional[int], default:None) –Override default max iterations
Returns:
-
FuzzyInfer–Self for method chaining
Raises:
-
InferenceError–If maximum iterations exceeded
Source code in fuzzy_infer/core.py
run_incremental
¶
Execute inference incrementally, yielding results.
Parameters:
-
max_iterations(Optional[int], default:None) –Override default max iterations
Yields:
-
InferenceResult–InferenceResult for each iteration with new facts
Source code in fuzzy_infer/core.py
stream_process
¶
stream_process(
fact_stream: Iterator[Fact],
window_size: int = 100,
max_iterations_per_window: int = 10,
) -> Iterator[Fact]
Process a stream of facts, yielding inferred facts.
Parameters:
-
fact_stream(Iterator[Fact]) –Iterator of input facts
-
window_size(int, default:100) –Number of facts to accumulate before inference
-
max_iterations_per_window(int, default:10) –Max iterations per window
Yields:
-
Fact–Newly inferred facts
Source code in fuzzy_infer/core.py
query
¶
Query the knowledge base for matching facts.
Parameters:
-
predicate(str) –Predicate to search for
-
args(Optional[List[Any]], default:None) –Arguments to match (can contain variables like '?x')
-
min_degree(float, default:0.0) –Minimum degree threshold
Returns:
-
List[Fact]–List of matching facts
Examples:
Source code in fuzzy_infer/core.py
ask
¶
Ask a question and get all matching variable bindings.
Parameters:
-
conditions(List[Union[List, Dict[str, Any]]]) –List of conditions to match
Returns:
-
List[Dict[str, Any]]–List of all satisfying variable bindings
Examples:
>>> # Who is a tall person?
>>> inf.ask([
... {'pred': 'is-person', 'args': ['?x']},
... {'pred': 'is-tall', 'args': ['?x']}
... ])
Source code in fuzzy_infer/core.py
explain
¶
Explain how a fact was derived.
Parameters:
-
fact(Union[Fact, Dict[str, Any]]) –Fact to explain
Returns:
-
List[str]–List of explanation strings
Source code in fuzzy_infer/core.py
clear
¶
get_facts
¶
InferenceResult
dataclass
¶
Result of an inference step.
Overview¶
The fuzzy_infer.core module contains the main inference engine implementing forward-chaining fuzzy logic reasoning.
Quick Reference¶
from fuzzy_infer import FuzzyInfer, Fact, Rule
# Create engine
inf = FuzzyInfer(max_iterations=100)
# Add facts
inf.add_fact(Fact("is-bird", ["tweety"], 0.9))
inf.add_facts([
Fact("has-wings", ["tweety"], 1.0),
Fact("can-fly", ["eagle"], 0.95)
])
# Add rules
inf.add_rule(bird_rule)
inf.add_rules([rule1, rule2, rule3])
# Run inference
result = inf.run()
# Query results
facts = inf.query("can-fly")
tweety = inf.query("can-fly", ["tweety"])
# Context manager
with FuzzyInfer.session() as inf:
inf.add_facts(facts)
inf.run()
Class Methods¶
FuzzyInfer¶
Production rule system for fuzzy inference.
This class implements a forward-chaining inference engine with fuzzy logic support, allowing for reasoning with uncertain information and degrees of belief.
Attributes:
-
facts(Dict[Tuple[str, Tuple], Fact]) –Set of facts in the knowledge base
-
rules(List[Rule]) –List of production rules
-
inference_log(List[str]) –Log of inference steps for debugging
-
max_iterations–Maximum iterations for inference loop
Examples:
>>> # Basic usage
>>> inf = FuzzyInfer()
>>> inf.add_fact(Fact('is-zebra', ['sam'], 0.8))
>>> inf.add_rule(RuleBuilder()
... .when('is-zebra', ['?x'])
... .with_degree_greater_than(0.5)
... .then_add('has-stripes', ['?x'])
... .with_degree_multiplied_by(0.9)
... .build())
>>> inf.run()
>>> results = inf.query('has-stripes', ['sam'])
>>> # Fluent API
>>> inf = (FuzzyInfer()
... .add_fact(Fact('is-person', ['alice'], 1.0))
... .add_fact(Fact('is-tall', ['alice'], 0.7))
... .add_rule(tall_person_rule)
... .run())
>>> # Context manager
>>> with FuzzyInfer.session() as inf:
... inf.add_facts(facts)
... inf.add_rules(rules)
... inf.run()
... results = inf.query('target-pred', ['arg'])
Initialize the FuzzyInfer inference engine.
Parameters:
-
max_iterations(int, default:100) –Maximum number of inference iterations
Source code in fuzzy_infer/core.py
session
classmethod
¶
Create a FuzzyInfer session as a context manager.
Yields:
-
FuzzyInfer(FuzzyInfer) –Configured inference engine
Examples:
>>> with FuzzyInfer.session(max_iterations=50) as inf:
... inf.add_facts(facts)
... results = inf.run()
Source code in fuzzy_infer/core.py
add_fact
¶
Add a single fact to the knowledge base.
Parameters:
-
fact(Union[Fact, Dict[str, Any]]) –Fact object or dictionary representation
Returns:
-
FuzzyInfer–Self for method chaining
Examples:
>>> inf.add_fact(Fact('is-person', ['sam'], 1.0))
>>> inf.add_fact({'pred': 'is-tall', 'args': ['sam'], 'deg': 0.8})
Source code in fuzzy_infer/core.py
add_facts
¶
Add multiple facts to the knowledge base.
Parameters:
-
facts(List[Union[Fact, Dict[str, Any]]]) –List of Fact objects or dictionary representations
Returns:
-
FuzzyInfer–Self for method chaining
Source code in fuzzy_infer/core.py
add_rule
¶
Add a single rule to the rule base.
Parameters:
-
rule(Union[Rule, Dict[str, Any]]) –Rule object or dictionary representation
Returns:
-
FuzzyInfer–Self for method chaining
Source code in fuzzy_infer/core.py
add_rules
¶
Add multiple rules to the rule base.
Parameters:
-
rules(List[Union[Rule, Dict[str, Any]]]) –List of Rule objects or dictionary representations
Returns:
-
FuzzyInfer–Self for method chaining
Source code in fuzzy_infer/core.py
query
¶
Query the knowledge base for matching facts.
Parameters:
-
predicate(str) –Predicate to search for
-
args(Optional[List[Any]], default:None) –Arguments to match (can contain variables like '?x')
-
min_degree(float, default:0.0) –Minimum degree threshold
Returns:
-
List[Fact]–List of matching facts
Examples:
Source code in fuzzy_infer/core.py
run
¶
Execute the forward-chaining inference process.
Parameters:
-
max_iterations(Optional[int], default:None) –Override default max iterations
Returns:
-
FuzzyInfer–Self for method chaining
Raises:
-
InferenceError–If maximum iterations exceeded
Source code in fuzzy_infer/core.py
InferenceResult¶
Result of an inference step.
Examples¶
Basic Usage¶
from fuzzy_infer import FuzzyInfer, Fact, Rule
inf = FuzzyInfer()
# Add facts
inf.add_fact(Fact("is-mammal", ["dog"], 0.95))
inf.add_fact(Fact("has-fur", ["dog"], 1.0))
# Add rule
inf.add_rule(Rule(
name="mammals-warm-blooded",
conditions=[{"pred": "is-mammal", "args": ["?x"]}],
actions=[{"action": "add", "fact": {"pred": "warm-blooded", "args": ["?x"], "deg": 0.99}}]
))
# Run and query
inf.run()
print(inf.query("warm-blooded", ["dog"]))
With Context Manager¶
with FuzzyInfer.session(max_iterations=50) as inf:
inf.add_facts([
Fact("is-bird", ["robin"], 0.9),
Fact("has-wings", ["robin"], 1.0)
])
inf.add_rule(birds_fly_rule)
result = inf.run()
print(f"Completed in {result.iteration} iterations")