active
library
fuzzy-infer
Unix-composable fuzzy logic inference with elegant Pythonic API
Resources & Distribution
Source Code
Package Registries
1
Stars
FuzzyInfer: A Production-Ready Fuzzy Logic Inference System
FuzzyInfer is a production-ready Python package for fuzzy logic inference using forward-chaining production rules. It extends classical rule-based systems by incorporating degrees of belief, enabling sophisticated reasoning under uncertainty.
๐ Features
- Fuzzy Logic Integration: Handle uncertainty with degrees of belief (0.0 to 1.0)
- Forward-Chaining Inference: Automatic derivation of new facts from rules
- Interactive CLI/REPL: Powerful command-line interface with file system navigation
- Knowledge Base Merging: 5 intelligent merge strategies with conflict detection
- Multiple Serialization Formats: JSON and YAML support
- Comprehensive API: Fluent interface and builder patterns
- Production Ready: 91.71% test coverage, type hints, error handling
๐ฆ Installation
From PyPI (when published)
pip install fuzzy-infer
From Source
git clone https://github.com/queelius/fuzzy-infer.git
cd fuzzy-infer
pip install -e .
# With CLI support
pip install -e ".[cli]"
# For development
pip install -e ".[dev]"
๐ฏ Quick Start
Basic Usage
from fuzzy_infer import FuzzyInfer, Fact, Rule
# Create inference engine
inf = FuzzyInfer()
# Add facts with degrees of belief
inf.add_fact(Fact("is-bird", ["tweety"], 0.9))
inf.add_fact(Fact("has-wings", ["tweety"], 1.0))
# Add rules
rule = Rule(
name="birds-fly",
conditions=[{"pred": "is-bird", "args": ["?x"]}],
actions=[{"action": "add", "fact": {"pred": "can-fly", "args": ["?x"], "deg": 0.8}}]
)
inf.add_rule(rule)
# Run inference
inf.run()
# Query results
results = inf.query("can-fly", ["tweety"])
print(results) # [Fact(predicate='can-fly', args=['tweety'], degree=0.72)]
Interactive CLI
# Start interactive session
fuzzy-infer interactive
# In the REPL:
> load examples/knowledge_bases/animal_classification.json
> run
> query is-mammal
> help
๐ง Core Concepts
Facts (Beliefs)
Facts represent knowledge with uncertainty:
Fact("is-tall", ["john"], 0.8) # John is tall with 80% certainty
Fact("temperature", ["room", "hot"], 0.6) # Room temperature is hot with 60% certainty
Rules
Rules define relationships and inference patterns:
{
"name": "mammals-give-milk",
"conditions": [
{"pred": "is-mammal", "args": ["?x"], "deg": "?d", "deg-pred": [">", "?d", 0.7]}
],
"actions": [
{"action": "add", "fact": {"pred": "gives-milk", "args": ["?x"], "deg": ["*", "?d", 0.9]}}
]
}
Degree Operations
- Fuzzy OR: Maximum degree for duplicate facts
- Fuzzy AND: Minimum degree across conditions
- Arithmetic:
["*", 0.8, "?d"],["+", "?d1", "?d2"],["min", "?d1", "?d2"]
๐ง Advanced Features
Knowledge Base Merging
Merge multiple knowledge bases with intelligent conflict resolution:
from fuzzy_infer.merge import KnowledgeBaseMerger, MergeStrategy
merger = KnowledgeBaseMerger(threshold=0.5)
# Smart merge with conflict detection
merged = merger.merge(kb1, kb2, MergeStrategy.SMART, auto_resolve=True)
# Get conflict report
print(merger.get_conflict_report())
Available Strategies:
UNION: Combine all facts/rules (default)OVERRIDE: Second KB takes precedenceCOMPLEMENT: Only add new itemsWEIGHTED: Weighted average of degreesSMART: Intelligent conflict detection and resolution
Fluent API
result = (
FuzzyInfer()
.add_fact(Fact("has-hair", ["dog"], 1.0))
.add_rule(mammal_rule)
.run()
.query("is-mammal")
)
Rule Builder DSL
from fuzzy_infer.models import RuleBuilder
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()
)
๐ฅ๏ธ CLI Commands
The interactive REPL provides powerful commands:
Facts & Rules
fact <predicate> <args...> [degree]- Add a factfacts- List all factsquery <predicate> [args...]- Query factsrule <json>- Add rule in JSON formatrules- List all rules
Inference
run- Execute forward-chaining inferenceclear- Clear all facts and rules
File Operations
load <file>- Load knowledge base (JSON/YAML)save <file>- Save current knowledge basemerge <file> [strategy]- Merge another KB
File System Navigation
pwd- Show current directorycd <path>- Change directoryls [path]- List directory contents
Session
history- Show command history (with arrow key support)help- Show available commandsexit- Exit the session
๐ Examples
Animal Classification
# Load comprehensive animal knowledge base
inf = FuzzyInferSerializer.load_from_file("examples/animal_classification.json")
inf.run()
# Query all mammals
mammals = inf.query("is-mammal") # Returns 8 animals
# Query specific animal
inf.query("is-mammal", ["lion"]) # Returns fact with degree 1.0
Weather Prediction
# Fuzzy weather reasoning
inf.add_fact(Fact("cloud-cover", ["today"], 0.8))
inf.add_fact(Fact("humidity", ["today"], 0.7))
# Rule: High clouds + humidity โ rain
rule = Rule(
conditions=[
{"pred": "cloud-cover", "args": ["?day"], "deg": "?c", "deg-pred": [">", "?c", 0.6]},
{"pred": "humidity", "args": ["?day"], "deg": "?h", "deg-pred": [">", "?h", 0.6]}
],
actions=[
{"action": "add", "fact": {"pred": "will-rain", "args": ["?day"],
"deg": ["*", ["min", "?c", "?h"], 0.9]}}
]
)
Medical Diagnosis
# Symptom-based diagnosis with uncertainty
inf.add_fact(Fact("has-symptom", ["patient1", "fever"], 0.9))
inf.add_fact(Fact("has-symptom", ["patient1", "cough"], 0.7))
# Rules infer possible conditions with confidence levels
๐๏ธ Architecture
Project Structure
fuzzy-infer/
โโโ fuzzy_infer/
โ โโโ __init__.py # Package exports
โ โโโ core.py # Main inference engine
โ โโโ models.py # Fact, Rule, Condition classes
โ โโโ fuzzy_ops.py # Fuzzy logic operations
โ โโโ merge.py # KB merging strategies
โ โโโ serialization.py # JSON/YAML I/O
โ โโโ cli.py # Interactive CLI/REPL
โ โโโ exceptions.py # Custom exceptions
โโโ examples/
โ โโโ knowledge_bases/ # Example KBs (animals, weather, medical)
โ โโโ *.py # Usage examples
โโโ tests/ # Comprehensive test suite
โโโ pyproject.toml # Modern Python packaging
Key Design Decisions
- Multiple Result Support: Fixed inference engine properly returns ALL matching facts
- Fuzzy OR Semantics: Duplicate facts automatically use maximum degree
- Conflict Resolution: Smart merging detects and resolves semantic conflicts
- Priority-Based Rules: Rules execute in priority order
- Pattern Variables: Support for
?xstyle variables in rules - Extensible Operations: Custom degree calculations and constraints
๐งช Testing
# Run tests
pytest
# With coverage
pytest --cov=fuzzy_infer --cov-report=html
# Run specific test
pytest tests/test_core.py::test_fuzzy_or
# Current coverage: 91.71%
๐ Documentation
- API Reference - Complete API documentation
- Tutorial - Step-by-step guide
- Examples - Working code examples
- Knowledge Bases - Sample KBs
๐ค Contributing
Contributions welcome! Please read CONTRIBUTING.md first.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see LICENSE file.
๐ Acknowledgments
- Inspired by CLIPS, Jess, and Drools rule engines
- Fuzzy logic principles from Zadeh’s fuzzy set theory
- Built with modern Python best practices
๐ฎ Contact
- GitHub: @queelius
- Issues: GitHub Issues
๐ง Roadmap
- Backward chaining support
- Explanation system for inference chains
- Web UI for knowledge base visualization
- REST API server mode
- Performance optimizations (Rete-like algorithm)
- LLM integration for rule generation
- More fuzzy operations (hedges, custom membership functions)
FuzzyInfer - Reasoning with Uncertainty