Skip to content

Examples

Real-world examples demonstrating FuzzyInfer's capabilities.

Medical Diagnosis System

Fuzzy logic excels at medical reasoning with uncertainty:

from fuzzy_infer import fuzzy

# Create medical knowledge base
diagnosis = fuzzy()

# Patient symptoms (with confidence levels)
diagnosis.facts(
    ("symptom", ["patient1", "fever"], 0.9),
    ("symptom", ["patient1", "cough"], 0.8),
    ("symptom", ["patient1", "fatigue"], 0.7),
    ("symptom", ["patient1", "headache"], 0.6),
    ("test-result", ["patient1", "flu-test", "positive"], 0.85)
)

# Diagnostic rules
diagnosis.rule(
    when=[
        ("symptom", "?p", "fever", degree=">0.7"),
        ("symptom", "?p", "cough", degree=">0.6")
    ],
    then=("possible-condition", "?p", "respiratory-infection", 0.75),
    name="respiratory-check"
)

diagnosis.rule(
    when=[
        ("symptom", "?p", "fever"),
        ("symptom", "?p", "cough"),
        ("symptom", "?p", "fatigue"),
        ("test-result", "?p", "flu-test", "positive")
    ],
    then=("diagnosis", "?p", "influenza", 0.9),
    name="flu-diagnosis"
)

diagnosis.rule(
    when=("diagnosis", "?p", "influenza", degree=">0.8"),
    then=[
        ("recommend", "?p", "antiviral-medication"),
        ("recommend", "?p", "rest"),
        ("recommend", "?p", "fluids")
    ],
    name="flu-treatment"
)

# Run diagnosis
diagnosis.infer()

# Get results
for diag in diagnosis.query("diagnosis", ["patient1"]):
    print(f"Diagnosis: {diag.args[1]} (confidence: {diag.degree:.1%})")

for rec in diagnosis.query("recommend", ["patient1"]):
    print(f"Recommendation: {rec.args[1]}")

Smart Home Automation

Control home devices based on fuzzy conditions:

from fuzzy_infer import FuzzySession
from datetime import datetime

with FuzzySession() as home:
    # Sensor readings
    home.facts(
        ("temperature", ["living-room", 22.5]),
        ("humidity", ["living-room", 0.65]),
        ("light-level", ["living-room", 0.3]),  # 30% brightness
        ("motion", ["living-room", "detected"], 0.9),
        ("time", ["current", datetime.now().hour])
    )

    # Comfort rules
    home.rule(
        when=[
            ("temperature", "?room", "?temp"),
            ("humidity", "?room", "?humid")
        ],
        then=("comfort-level", "?room", degree="1.0 - abs(?temp - 21) / 10 - abs(?humid - 0.5)"),
        name="comfort-calculation"
    )

    # Automation rules
    home.rule(
        when=[
            ("motion", "?room", "detected", degree=">0.8"),
            ("light-level", "?room", "?level"),
            ("time", "current", "?hour")
        ],
        then=("lights", "?room", "on"),
        where=lambda b: b["?level"] < 0.4 and (b["?hour"] < 6 or b["?hour"] > 18),
        name="auto-lights"
    )

    home.rule(
        when=[
            ("temperature", "?room", "?temp"),
            ("comfort-level", "?room", degree="<0.6")
        ],
        then=[
            ("ac", "?room", "on"),
            ("ac-target", "?room", 21)
        ],
        where=lambda b: b["?temp"] > 24,
        name="ac-control"
    )

    # Execute automation
    home.infer()

    # Check actions
    for action in home.query("lights"):
        print(f"Lights in {action.args[0]}: {action.args[1]}")

    for action in home.query("ac"):
        print(f"AC in {action.args[0]}: {action.args[1]}")

Financial Risk Assessment

Evaluate investment risks with fuzzy logic:

from fuzzy_infer import fuzzy

risk_model = fuzzy()

# Market indicators
risk_model.facts(
    ("volatility", ["TECH-STOCK", 0.35]),  # 35% volatility
    ("pe-ratio", ["TECH-STOCK", 45]),
    ("market-cap", ["TECH-STOCK", "large"]),
    ("sector-performance", ["technology", 0.7]),  # 70% positive
    ("economic-indicator", ["gdp-growth", 0.02]),  # 2% growth
    ("economic-indicator", ["inflation", 0.03])   # 3% inflation
)

# Risk assessment rules
risk_model.rule(
    when=("volatility", "?stock", "?v"),
    then=("volatility-risk", "?stock", degree="?v"),
    name="volatility-assessment"
)

risk_model.rule(
    when=("pe-ratio", "?stock", "?pe"),
    then=("valuation-risk", "?stock", degree="min(1.0, ?pe / 50)"),
    where=lambda b: b["?pe"] > 25,
    name="overvaluation-check"
)

risk_model.rule(
    when=[
        ("volatility-risk", "?stock", degree="?vr"),
        ("valuation-risk", "?stock", degree="?pr")
    ],
    then=("overall-risk", "?stock", degree="(?vr + ?pr) / 2"),
    name="risk-aggregation"
)

risk_model.rule(
    when=("overall-risk", "?stock", degree="?risk"),
    then=("recommendation", "?stock", "buy", degree="1.0 - ?risk"),
    where=lambda b: b["?risk"] < 0.4,
    name="buy-recommendation"
)

risk_model.rule(
    when=("overall-risk", "?stock", degree="?risk"),
    then=("recommendation", "?stock", "sell", degree="?risk"),
    where=lambda b: b["?risk"] > 0.7,
    name="sell-recommendation"
)

risk_model.rule(
    when=("overall-risk", "?stock", degree="?risk"),
    then=("recommendation", "?stock", "hold"),
    where=lambda b: 0.4 <= b["?risk"] <= 0.7,
    name="hold-recommendation"
)

# Run analysis
risk_model.infer()

# Get recommendations
for rec in risk_model.query("recommendation"):
    stock, action = rec.args[0], rec.args[1]
    print(f"{stock}: {action.upper()} (confidence: {rec.degree:.1%})")

Natural Language Understanding

Process fuzzy language concepts:

from fuzzy_infer import fuzzy

# Language understanding system
nlu = fuzzy()

# Text analysis results
nlu.facts(
    ("sentiment", ["review1", "positive"], 0.7),
    ("sentiment", ["review1", "negative"], 0.2),
    ("keyword", ["review1", "excellent"], 0.9),
    ("keyword", ["review1", "but"], 0.8),
    ("keyword", ["review1", "expensive"], 0.85),
    ("length", ["review1", 150]),  # words
    ("rating", ["review1", 4])  # out of 5
)

# Interpretation rules
nlu.rule(
    when=[
        ("sentiment", "?text", "positive", degree="?pos"),
        ("sentiment", "?text", "negative", degree="?neg")
    ],
    then=("sentiment-score", "?text", degree="?pos - ?neg"),
    name="sentiment-calculation"
)

nlu.rule(
    when=[
        ("keyword", "?text", "excellent"),
        ("keyword", "?text", "expensive")
    ],
    then=("mixed-feelings", "?text", 0.8),
    name="mixed-sentiment"
)

nlu.rule(
    when=[
        ("sentiment-score", "?text", degree="?score"),
        ("rating", "?text", "?rating")
    ],
    then=("consistency", "?text", degree="1.0 - abs(?score - (?rating - 3) / 2)"),
    name="rating-consistency"
)

nlu.rule(
    when=[
        ("mixed-feelings", "?text"),
        ("consistency", "?text", degree=">0.7")
    ],
    then=("review-type", "?text", "balanced-critique"),
    name="review-classification"
)

# Analyze
nlu.infer()

for result in nlu.query("review-type"):
    print(f"Review {result.args[0]}: {result.args[1]}")

Robot Navigation

Fuzzy control for robot movement:

from fuzzy_infer import fuzzy
import math

# Robot navigation system
robot = fuzzy()

# Sensor data (distances in meters)
robot.facts(
    ("distance", ["front", 2.5]),
    ("distance", ["left", 1.2]),
    ("distance", ["right", 3.0]),
    ("distance", ["back", 4.0]),
    ("target", ["angle", 45]),  # degrees
    ("target", ["distance", 5.0]),
    ("speed", ["current", 1.0])  # m/s
)

# Obstacle avoidance
robot.rule(
    when=("distance", "front", "?d"),
    then=("obstacle", "front", degree="max(0, 1.0 - ?d / 3.0)"),
    where=lambda b: b["?d"] < 3.0,
    name="front-obstacle"
)

robot.rule(
    when=("distance", "?dir", "?d"),
    then=("obstacle", "?dir", degree="max(0, 1.0 - ?d / 2.0)"),
    where=lambda b: b["?dir"] in ["left", "right"] and b["?d"] < 2.0,
    name="side-obstacle"
)

# Navigation decisions
robot.rule(
    when=[
        ("obstacle", "front", degree=">0.5"),
        ("obstacle", "left", degree="?left"),
        ("obstacle", "right", degree="?right")
    ],
    then=("turn", "right" if "?left > ?right" else "left", degree="0.8"),
    name="avoid-turn"
)

robot.rule(
    when=[
        ("target", "angle", "?angle"),
        ("obstacle", "front", degree="<0.3")
    ],
    then=("turn", "right" if "?angle > 0" else "left", degree="abs(?angle) / 180"),
    name="target-turn"
)

robot.rule(
    when=("obstacle", "front", degree="?obs"),
    then=("speed", "adjust", degree="1.0 - ?obs"),
    name="speed-control"
)

# Execute navigation
robot.infer()

# Get commands
for cmd in robot.query("turn"):
    print(f"Turn {cmd.args[0]} (strength: {cmd.degree:.1%})")

for cmd in robot.query("speed", ["adjust"]):
    print(f"Speed adjustment: {cmd.degree:.1%} of max")

Weather Prediction

Fuzzy weather forecasting:

from fuzzy_infer import fuzzy

weather = fuzzy()

# Meteorological data
weather.facts(
    ("pressure", ["current", 1013]),  # hPa
    ("pressure", ["trend", -2.5]),  # hPa/hour
    ("humidity", ["current", 0.75]),
    ("temperature", ["current", 22]),
    ("wind-speed", ["current", 15]),  # km/h
    ("cloud-cover", ["current", 0.6])
)

# Weather patterns
weather.rule(
    when=[
        ("pressure", "trend", "?trend"),
        ("humidity", "current", "?humid")
    ],
    then=("rain-probability", degree="min(1.0, max(0, -?trend * 0.2 + ?humid))"),
    where=lambda b: b["?trend"] < 0 and b["?humid"] > 0.6,
    name="rain-prediction"
)

weather.rule(
    when=[
        ("cloud-cover", "current", "?cover"),
        ("humidity", "current", "?humid")
    ],
    then=("conditions", "cloudy", degree="?cover"),
    name="cloud-conditions"
)

weather.rule(
    when=[
        ("rain-probability", degree="?rain"),
        ("wind-speed", "current", "?wind")
    ],
    then=("storm-probability", degree="?rain * min(1.0, ?wind / 30)"),
    where=lambda b: b["?wind"] > 20,
    name="storm-prediction"
)

# Forecast
weather.infer()

for forecast in weather.query("rain-probability"):
    print(f"Rain probability: {forecast.degree:.1%}")

for forecast in weather.query("storm-probability"):
    print(f"Storm probability: {forecast.degree:.1%}")

Game AI Decision Making

NPC behavior using fuzzy logic:

from fuzzy_infer import FuzzySession

with FuzzySession() as npc:
    # Game state
    npc.facts(
        ("health", ["player", 0.3]),  # 30% health
        ("health", ["npc", 0.8]),
        ("distance", ["player", "npc", 5.0]),  # meters
        ("weapon", ["player", "sword"]),
        ("weapon", ["npc", "bow"]),
        ("stamina", ["npc", 0.6]),
        ("cover", ["available", True], 0.7)
    )

    # Threat assessment
    npc.rule(
        when=[
            ("health", "player", "?ph"),
            ("health", "npc", "?nh")
        ],
        then=("threat-level", degree="?ph / ?nh"),
        name="threat-calculation"
    )

    # Combat decisions
    npc.rule(
        when=[
            ("threat-level", degree=">0.5"),
            ("distance", "player", "npc", "?d"),
            ("weapon", "npc", "bow")
        ],
        then=("action", "attack-ranged", degree="1.0 - ?d / 20"),
        where=lambda b: b["?d"] > 3,
        name="ranged-attack"
    )

    npc.rule(
        when=[
            ("health", "npc", "?h"),
            ("cover", "available", True)
        ],
        then=("action", "take-cover", degree="1.0 - ?h"),
        where=lambda b: b["?h"] < 0.5,
        name="defensive-action"
    )

    npc.rule(
        when=[
            ("threat-level", degree="<0.3"),
            ("stamina", "npc", "?s")
        ],
        then=("action", "pursue", degree="?s"),
        name="aggressive-action"
    )

    # Execute AI
    npc.infer()

    # Get best action
    actions = npc.query("action").sorted_by_degree()
    if actions:
        best = actions[0]
        print(f"NPC decides to: {best.args[0]} (confidence: {best.degree:.1%})")

Supply Chain Optimization

Fuzzy inventory management:

from fuzzy_infer import fuzzy

supply_chain = fuzzy()

# Inventory data
supply_chain.facts(
    ("stock-level", ["product-A", 0.25]),  # 25% of capacity
    ("demand-trend", ["product-A", 0.8]),  # High demand
    ("lead-time", ["product-A", 7]),  # days
    ("supplier-reliability", ["supplier-1", 0.9]),
    ("cost", ["product-A", "holding", 10]),  # per unit per day
    ("cost", ["product-A", "shortage", 50])  # per unit
)

# Inventory rules
supply_chain.rule(
    when=[
        ("stock-level", "?product", "?level"),
        ("demand-trend", "?product", "?demand")
    ],
    then=("reorder-urgency", "?product", degree="?demand * (1.0 - ?level)"),
    name="urgency-calculation"
)

supply_chain.rule(
    when=[
        ("reorder-urgency", "?product", degree=">0.7"),
        ("lead-time", "?product", "?days")
    ],
    then=("order-quantity", "?product", "large", degree="min(1.0, 0.7 + ?days * 0.03)"),
    name="large-order"
)

supply_chain.rule(
    when=[
        ("reorder-urgency", "?product", degree="?urgency"),
        ("supplier-reliability", "?supplier", "?reliability")
    ],
    then=("select-supplier", "?product", "?supplier", degree="?urgency * ?reliability"),
    where=lambda b: b["?urgency"] > 0.5,
    name="supplier-selection"
)

# Optimize
supply_chain.infer()

for order in supply_chain.query("order-quantity"):
    product, size = order.args[0], order.args[1]
    print(f"Order {size} quantity of {product} (confidence: {order.degree:.1%})")

for supplier in supply_chain.query("select-supplier"):
    product, supp = supplier.args[0], supplier.args[1]
    print(f"Use {supp} for {product} (score: {supplier.degree:.2f})")

Next Steps