# PDSL Examples Collection
**Version:** 0.1.0
This document contains 25+ comprehensive examples covering all major use cases for PDSL.
## Table of Contents
1. [Basic Examples](#basic-examples)
2. [Medical Diagnosis](#medical-diagnosis)
3. [Weather Prediction](#weather-prediction)
4. [Fault Diagnosis](#fault-diagnosis)
5. [Risk Assessment](#risk-assessment)
6. [Natural Language Understanding](#natural-language-understanding)
7. [Sensor Fusion](#sensor-fusion)
8. [Game AI](#game-ai)
9. [Financial Forecasting](#financial-forecasting)
10. [Advanced Patterns](#advanced-patterns)
## Basic Examples
### Example 1: Coin Flip
Simple probabilistic model:
```pdsl
probabilistic_model CoinFlip {
# Fair coin
0.5 :: heads
0.5 :: tails
query heads
}
```
**Output:** `heads: 0.5`
### Example 2: Biased Die
Annotated disjunction with six outcomes:
```pdsl
probabilistic_model BiasedDie {
# Biased towards 6
0.1 :: roll(1);
0.1 :: roll(2);
0.1 :: roll(3);
0.15 :: roll(4);
0.15 :: roll(5);
0.4 :: roll(6)
query roll(6)
}
```
**Output:** `roll(6): 0.4`
### Example 3: Conditional Probability
Bird flight with exceptions:
```pdsl
probabilistic_model BirdFlight {
# Birds
bird(sparrow)
bird(penguin)
bird(eagle)
penguin(penguin)
# Flight probability
0.95 :: flies(X) :- bird(X), not penguin(X)
0.0 :: flies(X) :- penguin(X)
query flies(sparrow)
query flies(penguin)
query flies(eagle)
}
```
**Output:**
- `flies(sparrow): 0.95`
- `flies(penguin): 0.0`
- `flies(eagle): 0.95`
## Medical Diagnosis
### Example 4: Simple Diagnosis
Fever and disease:
```pdsl
probabilistic_model SimpleDiagnosis {
# Prior: 1% chance of flu
0.01 :: flu
# Likelihood: 90% fever if flu
0.9 :: fever :- flu
# Background fever rate: 5%
0.05 :: fever :- not flu
# Patient has fever
observe fever
# What's P(flu | fever)?
query flu
}
```
**Output:** `flu: 0.154` (Bayes' theorem: 15.4%)
### Example 5: Multi-Disease Diagnosis
Multiple diseases and symptoms:
```pdsl
probabilistic_model MultiDiseaseDiagnosis {
# Priors
0.01 :: disease(flu)
0.001 :: disease(covid)
0.005 :: disease(cold)
0.0001 :: disease(pneumonia)
# Symptoms for flu
0.9 :: symptom(fever) :- disease(flu)
0.8 :: symptom(cough) :- disease(flu)
0.6 :: symptom(fatigue) :- disease(flu)
# Symptoms for covid
0.95 :: symptom(fever) :- disease(covid)
0.85 :: symptom(cough) :- disease(covid)
0.9 :: symptom(fatigue) :- disease(covid)
0.7 :: symptom(loss_of_smell) :- disease(covid)
# Symptoms for cold
0.3 :: symptom(fever) :- disease(cold)
0.9 :: symptom(cough) :- disease(cold)
0.4 :: symptom(fatigue) :- disease(cold)
# Symptoms for pneumonia
0.95 :: symptom(fever) :- disease(pneumonia)
0.95 :: symptom(cough) :- disease(pneumonia)
0.8 :: symptom(fatigue) :- disease(pneumonia)
0.7 :: symptom(chest_pain) :- disease(pneumonia)
# Background symptom rates
0.05 :: symptom(fever)
0.1 :: symptom(cough)
0.15 :: symptom(fatigue)
# Observations
observe symptom(fever)
observe symptom(cough)
observe symptom(fatigue)
# Queries
query disease(flu)
query disease(covid)
query disease(cold)
query disease(pneumonia)
}
```
### Example 6: Disease Progression
Temporal disease model:
```pdsl
probabilistic_model DiseaseProgression {
# Initial infection
0.1 :: infected(day1)
# Progression over time
0.8 :: infected(day2) :- infected(day1)
0.7 :: infected(day3) :- infected(day2)
0.5 :: infected(day4) :- infected(day3)
# Symptoms appear with delay
0.3 :: symptoms(day1) :- infected(day1)
0.7 :: symptoms(day2) :- infected(day2)
0.9 :: symptoms(day3) :- infected(day3)
0.95 :: symptoms(day4) :- infected(day4)
# Observed symptoms on day 3
observe symptoms(day3)
# When did infection start?
query infected(day1)
query infected(day2)
query infected(day3)
}
```
## Weather Prediction
### Example 7: Simple Weather
Rain and clouds:
```pdsl
probabilistic_model SimpleWeather {
# Base probability of rain
0.2 :: rain
# Cloudy depends on rain
0.9 :: cloudy :- rain
0.3 :: cloudy :- not rain
# Observed clouds
observe cloudy
# Chance of rain?
query rain
}
```
### Example 8: Multi-Day Weather
Weather dependencies across days:
```pdsl
probabilistic_model MultiDayWeather {
# Day 1 weather (independent)
0.3 :: rain(day1)
# Day 2 depends on day 1
0.6 :: rain(day2) :- rain(day1)
0.2 :: rain(day2) :- not rain(day1)
# Day 3 depends on day 2
0.7 :: rain(day3) :- rain(day2)
0.15 :: rain(day3) :- not rain(day2)
# Temperature inversely related to rain
0.2 :: cold(D) :- rain(D)
0.6 :: cold(D) :- not rain(D)
# Observations
observe rain(day1)
observe cold(day2)
# Predictions
query rain(day2)
query rain(day3)
query cold(day3)
}
```
### Example 9: Seasonal Weather
Weather patterns by season:
```pdsl
probabilistic_model SeasonalWeather {
# Season facts
season(summer)
# Rain probabilities by season
0.15 :: rain :- season(summer)
0.4 :: rain :- season(spring)
0.5 :: rain :- season(fall)
0.35 :: rain :- season(winter)
# Temperature by season
0.8 :: temp(hot) :- season(summer), not rain
0.4 :: temp(hot) :- season(summer), rain
0.5 :: temp(mild) :- season(spring)
0.5 :: temp(mild) :- season(fall)
0.7 :: temp(cold) :- season(winter)
query rain
query temp(hot)
}
```
## Fault Diagnosis
### Example 10: Computer System Faults
Hardware and software failures:
```pdsl
probabilistic_model ComputerFaults {
# Component reliability
0.95 :: working(cpu)
0.98 :: working(memory)
0.90 :: working(disk)
0.85 :: working(power_supply)
# System boot depends on components
0.99 :: boots :- working(cpu), working(memory), working(power_supply)
0.0 :: boots :- not working(cpu)
0.0 :: boots :- not working(power_supply)
# Slow performance
0.8 :: slow :- not working(disk)
0.7 :: slow :- not working(memory)
0.1 :: slow
# Observations
observe not boots
# Which component failed?
query working(cpu)
query working(memory)
query working(power_supply)
}
```
### Example 11: Network Fault Diagnosis
Network topology failures:
```pdsl
probabilistic_model NetworkFaults {
# Node reliability
0.98 :: up(server1)
0.98 :: up(server2)
0.95 :: up(router1)
0.95 :: up(router2)
0.99 :: up(gateway)
# Connectivity rules
connected(server1, client) :- up(server1), up(router1), up(gateway)
connected(server2, client) :- up(server2), up(router2), up(gateway)
# Service availability (redundant servers)
service_available :- connected(server1, client)
service_available :- connected(server2, client)
# Cascade failures
0.7 :: up(router1) :- not up(gateway)
0.7 :: up(router2) :- not up(gateway)
# Observation: service down
observe not service_available
# Diagnose
query up(server1)
query up(server2)
query up(gateway)
query up(router1)
}
```
### Example 12: Manufacturing Defects
Production line quality control:
```pdsl
probabilistic_model ManufacturingQC {
# Machine states
0.95 :: machine_ok(machine1)
0.93 :: machine_ok(machine2)
0.97 :: machine_ok(machine3)
# Material quality
0.98 :: material_ok
# Product quality depends on machines and materials
0.99 :: product_ok :- machine_ok(machine1), machine_ok(machine2), machine_ok(machine3), material_ok
0.7 :: product_ok :- not machine_ok(machine1), machine_ok(machine2), machine_ok(machine3), material_ok
0.8 :: product_ok :- machine_ok(machine1), not machine_ok(machine2), machine_ok(machine3), material_ok
0.75 :: product_ok :- machine_ok(machine1), machine_ok(machine2), not machine_ok(machine3), material_ok
0.5 :: product_ok :- machine_ok(machine1), machine_ok(machine2), machine_ok(machine3), not material_ok
# Test results
0.98 :: test_pass :- product_ok
0.05 :: test_pass :- not product_ok
# Observed test failure
observe not test_pass
# Root cause?
query machine_ok(machine1)
query machine_ok(machine2)
query machine_ok(machine3)
query material_ok
}
```
## Risk Assessment
### Example 13: Credit Risk
Loan default prediction:
```pdsl
probabilistic_model CreditRisk {
# Applicant characteristics
income(high)
employment(stable)
credit_score(good)
# Default probabilities
0.01 :: defaults :- income(high), credit_score(excellent)
0.03 :: defaults :- income(high), credit_score(good)
0.08 :: defaults :- income(medium), credit_score(good)
0.15 :: defaults :- income(low), credit_score(fair)
0.35 :: defaults :- income(low), credit_score(poor)
# Employment stability effect
0.7 :: defaults :- defaults, not employment(stable)
query defaults
}
```
### Example 14: Cybersecurity Risk
Attack probability assessment:
```pdsl
probabilistic_model CyberSecurityRisk {
# Threat level
0.3 :: threat(high)
0.5 :: threat(medium)
0.2 :: threat(low)
# Vulnerability assessment
0.8 :: vulnerable :- threat(high)
0.4 :: vulnerable :- threat(medium)
0.1 :: vulnerable :- threat(low)
# Security measures
0.95 :: firewall_active
0.90 :: ids_active
0.85 :: patch_updated
# Attack success
0.7 :: attack_success :- vulnerable, not firewall_active
0.5 :: attack_success :- vulnerable, not ids_active
0.4 :: attack_success :- vulnerable, not patch_updated
0.1 :: attack_success :- vulnerable, firewall_active, ids_active, patch_updated
# Data breach
0.8 :: data_breach :- attack_success
# Observations
observe threat(high)
observe firewall_active
# Risk queries
query attack_success
query data_breach
}
```
### Example 15: Investment Risk
Portfolio risk analysis:
```pdsl
probabilistic_model InvestmentRisk {
# Market conditions
0.25 :: market(bull);
0.5 :: market(neutral);
0.25 :: market(bear)
# Stock performance
0.7 :: stock_up(tech) :- market(bull)
0.3 :: stock_up(tech) :- market(neutral)
0.1 :: stock_up(tech) :- market(bear)
0.6 :: stock_up(energy) :- market(bull)
0.4 :: stock_up(energy) :- market(neutral)
0.2 :: stock_up(energy) :- market(bear)
# Portfolio performance
0.8 :: portfolio_gain :- stock_up(tech), stock_up(energy)
0.5 :: portfolio_gain :- stock_up(tech), not stock_up(energy)
0.4 :: portfolio_gain :- not stock_up(tech), stock_up(energy)
0.1 :: portfolio_gain :- not stock_up(tech), not stock_up(energy)
# Observations
observe stock_up(tech)
# Queries
query portfolio_gain
query market(bull)
}
```
## Natural Language Understanding
### Example 16: Word Sense Disambiguation
Disambiguate word meanings:
```pdsl
probabilistic_model WordSenseDisambiguation {
# Context words
context(bank)
context(river)
context(water)
# Word senses
0.6 :: sense(bank, financial)
0.4 :: sense(bank, riverbank)
# Contextual preferences
0.9 :: sense(bank, riverbank) :- context(river)
0.8 :: sense(bank, riverbank) :- context(water)
0.9 :: sense(bank, financial) :- context(money)
0.8 :: sense(bank, financial) :- context(account)
# Observe context
observe context(river)
observe context(water)
# Which sense?
query sense(bank, financial)
query sense(bank, riverbank)
}
```
### Example 17: Sentiment Analysis
Text sentiment classification:
```pdsl
probabilistic_model SentimentAnalysis {
# Word indicators
word(excellent)
word(great)
word(terrible)
# Sentiment probabilities
0.9 :: sentiment(positive) :- word(excellent)
0.85 :: sentiment(positive) :- word(great)
0.1 :: sentiment(positive) :- word(terrible)
0.05 :: sentiment(negative) :- word(excellent)
0.1 :: sentiment(negative) :- word(great)
0.95 :: sentiment(negative) :- word(terrible)
# Default sentiment
0.5 :: sentiment(neutral)
# Observations
observe word(excellent)
observe word(great)
# Classify
query sentiment(positive)
query sentiment(negative)
query sentiment(neutral)
}
```
### Example 18: Intent Classification
Chatbot intent detection:
```pdsl
probabilistic_model IntentClassification {
# Detected keywords
keyword(book)
keyword(flight)
keyword(tomorrow)
# Intent priors
0.3 :: intent(book_flight)
0.25 :: intent(book_hotel)
0.2 :: intent(check_weather)
0.15 :: intent(set_reminder)
0.1 :: intent(other)
# Keyword-intent associations
0.9 :: intent(book_flight) :- keyword(book), keyword(flight)
0.8 :: intent(book_hotel) :- keyword(book), keyword(hotel)
0.85 :: intent(check_weather) :- keyword(weather)
0.8 :: intent(set_reminder) :- keyword(remind), keyword(tomorrow)
# Observations
observe keyword(book)
observe keyword(flight)
observe keyword(tomorrow)
# Classify intent
query intent(book_flight)
query intent(book_hotel)
query intent(set_reminder)
}
```
## Sensor Fusion
### Example 19: Robot Localization
Multiple sensor readings:
```pdsl
probabilistic_model RobotLocalization {
# Possible locations
0.25 :: location(room1);
0.25 :: location(room2);
0.25 :: location(hallway);
0.25 :: location(kitchen)
# GPS reading (noisy)
0.8 :: gps_reading(X) :- location(X)
0.1 :: gps_reading(Y) :- location(X), adjacent(X, Y)
# Vision sensor
0.9 :: sees(table) :- location(kitchen)
0.85 :: sees(bed) :- location(room1)
0.85 :: sees(desk) :- location(room2)
# Adjacency facts
adjacent(room1, hallway)
adjacent(room2, hallway)
adjacent(hallway, kitchen)
# Observations
observe gps_reading(kitchen)
observe sees(table)
# Where is robot?
query location(kitchen)
query location(hallway)
}
```
### Example 20: Multi-Sensor Object Detection
Fusing camera and LIDAR:
```pdsl
probabilistic_model ObjectDetection {
# Object presence
0.1 :: object_present(car)
0.05 :: object_present(pedestrian)
0.02 :: object_present(bicycle)
# Camera detection
0.95 :: camera_detects(X) :- object_present(X)
0.05 :: camera_detects(X) # False positive
# LIDAR detection
0.98 :: lidar_detects(X) :- object_present(X)
0.02 :: lidar_detects(X) # False positive
# Fusion: higher confidence if both agree
0.99 :: confirmed(X) :- camera_detects(X), lidar_detects(X)
# Observations
observe camera_detects(car)
observe lidar_detects(car)
# Query
query object_present(car)
query confirmed(car)
}
```
## Game AI
### Example 21: Enemy Behavior Prediction
Predict opponent actions:
```pdsl
probabilistic_model EnemyBehavior {
# Enemy state
enemy_health(low)
player_distance(close)
# Action probabilities
0.7 :: action(retreat) :- enemy_health(low)
0.2 :: action(attack) :- enemy_health(low)
0.3 :: action(retreat) :- enemy_health(high)
0.6 :: action(attack) :- enemy_health(high)
# Distance modifies behavior
0.8 :: action(attack) :- player_distance(close), enemy_health(high)
0.9 :: action(retreat) :- player_distance(close), enemy_health(low)
# Observations
observe enemy_health(low)
observe player_distance(close)
# Predict
query action(retreat)
query action(attack)
}
```
### Example 22: Loot Drop System
Probabilistic item generation:
```pdsl
probabilistic_model LootDrop {
# Enemy type
enemy(boss)
# Rarity tiers
0.5 :: rarity(common);
0.3 :: rarity(rare);
0.15 :: rarity(epic);
0.05 :: rarity(legendary)
# Boss modifiers
0.3 :: rarity(common) :- enemy(boss)
0.3 :: rarity(rare) :- enemy(boss)
0.25 :: rarity(epic) :- enemy(boss)
0.15 :: rarity(legendary) :- enemy(boss)
# Item types by rarity
0.7 :: item_type(weapon) :- rarity(legendary)
0.3 :: item_type(armor) :- rarity(legendary)
0.5 :: item_type(weapon) :- rarity(epic)
0.5 :: item_type(armor) :- rarity(epic)
# Observations
observe enemy(boss)
# What drops?
query rarity(legendary)
query item_type(weapon)
}
```
### Example 23: Dialogue System
NPC conversation choices:
```pdsl
probabilistic_model DialogueSystem {
# Player reputation
reputation(high)
# NPC mood
0.6 :: mood(friendly)
0.3 :: mood(neutral)
0.1 :: mood(hostile)
# Response probabilities
0.9 :: response(helpful) :- mood(friendly), reputation(high)
0.7 :: response(helpful) :- mood(friendly), reputation(medium)
0.5 :: response(helpful) :- mood(neutral), reputation(high)
0.8 :: response(hostile) :- mood(hostile)
0.3 :: response(hostile) :- mood(neutral), reputation(low)
# Quest offering
0.8 :: offers_quest :- response(helpful)
0.1 :: offers_quest :- response(neutral)
# Observations
observe reputation(high)
observe mood(friendly)
# Queries
query response(helpful)
query offers_quest
}
```
## Financial Forecasting
### Example 24: Stock Price Movement
Short-term price prediction:
```pdsl
probabilistic_model StockPriceMovement {
# Market indicators
0.3 :: indicator(volume_high)
0.25 :: indicator(rsi_overbought)
0.2 :: indicator(macd_bullish)
# Price movement
0.6 :: price(up) :- indicator(macd_bullish), not indicator(rsi_overbought)
0.7 :: price(up) :- indicator(volume_high), indicator(macd_bullish)
0.3 :: price(down) :- indicator(rsi_overbought)
0.4 :: price(down) :- not indicator(volume_high), not indicator(macd_bullish)
# Observations
observe indicator(macd_bullish)
observe indicator(volume_high)
# Forecast
query price(up)
query price(down)
}
```
### Example 25: Economic Recession Prediction
Macro-economic indicators:
```pdsl
probabilistic_model RecessionPrediction {
# Economic indicators
0.15 :: indicator(unemployment_rising)
0.2 :: indicator(yield_curve_inverted)
0.1 :: indicator(gdp_declining)
0.12 :: indicator(consumer_confidence_low)
# Recession probability
0.7 :: recession :- indicator(yield_curve_inverted), indicator(unemployment_rising)
0.8 :: recession :- indicator(gdp_declining), indicator(unemployment_rising)
0.6 :: recession :- indicator(consumer_confidence_low), indicator(gdp_declining)
# Base recession rate
0.05 :: recession
# Observations
observe indicator(yield_curve_inverted)
observe indicator(unemployment_rising)
# Forecast
query recession
}
```
## Advanced Patterns
### Example 26: Parameter Learning
Learn probabilities from data:
```pdsl
probabilistic_model ParameterLearning {
# Unknown probabilities (to be learned)
p1 :: symptom(fever) :- disease(flu)
p2 :: symptom(cough) :- disease(flu)
p3 :: disease(flu)
# Learn from dataset
learn parameters from dataset("medical_records.csv")
# Query with learned parameters
query disease(flu)
}
```
### Example 27: Recursive Probabilistic Model
Transitive relations:
```pdsl
probabilistic_model TransitiveFriendship {
# Base friendships
0.8 :: friends(alice, bob)
0.7 :: friends(bob, carol)
0.6 :: friends(carol, dave)
# Transitive friendship (friends of friends)
0.6 :: connected(X, Y) :- friends(X, Y)
0.4 :: connected(X, Z) :- friends(X, Y), connected(Y, Z)
# Query transitive connection
query connected(alice, dave)
}
```
### Example 28: Temporal Reasoning
Event sequences:
```pdsl
probabilistic_model TemporalEvents {
# Initial event
0.3 :: event(start, t1)
# Event propagation over time
0.8 :: event(progress, t2) :- event(start, t1)
0.7 :: event(progress, t3) :- event(progress, t2)
0.6 :: event(complete, t4) :- event(progress, t3)
# Observations at different times
observe event(start, t1)
observe event(progress, t2)
# Predict future
query event(complete, t4)
}
```
### Example 29: Noisy-OR Model
Multiple independent causes:
```pdsl
probabilistic_model NoisyOR {
# Multiple causes
0.1 :: cause(fire)
0.05 :: cause(earthquake)
0.02 :: cause(power_surge)
# Effect with noisy-OR combination
0.95 :: effect(alarm) :- cause(fire)
0.9 :: effect(alarm) :- cause(earthquake)
0.7 :: effect(alarm) :- cause(power_surge)
# False alarm rate
0.01 :: effect(alarm)
# Observation
observe effect(alarm)
# Diagnose causes
query cause(fire)
query cause(earthquake)
query cause(power_surge)
}
```
### Example 30: Hidden Markov Model
Sequence prediction:
```pdsl
probabilistic_model HiddenMarkov {
# Initial state
0.6 :: state(sunny, t1);
0.4 :: state(rainy, t1)
# Transition probabilities
0.8 :: state(sunny, t2) :- state(sunny, t1)
0.2 :: state(rainy, t2) :- state(sunny, t1)
0.4 :: state(sunny, t2) :- state(rainy, t1)
0.6 :: state(rainy, t2) :- state(rainy, t1)
# Observations (emissions)
0.9 :: observe_sun :- state(sunny, t1)
0.2 :: observe_sun :- state(rainy, t1)
# Observation
observe observe_sun
# Infer hidden state
query state(sunny, t1)
query state(rainy, t2)
}
```
## Usage Tips
### Running Examples
```bash
# Save example to file
echo "..." > example.pdsl
# Run with PDSL interpreter
logic-thinking probabilistic example.pdsl
# Or compile to ProbLog
logic-thinking compile example.pdsl > example.pl
problog example.pl
```
### Modifying Examples
1. **Adjust probabilities** to match your domain
2. **Add observations** to condition on evidence
3. **Add queries** to explore different scenarios
4. **Combine examples** for complex models
### Best Practices
1. **Start simple** - Begin with basic facts and rules
2. **Validate probabilities** - Ensure they sum correctly
3. **Test incrementally** - Add complexity gradually
4. **Document assumptions** - Use comments liberally
5. **Compare outputs** - Verify results make intuitive sense
## Additional Resources
- [Quickstart Guide](PROBABILISTIC_DSL_QUICKSTART.md)
- [Language Specification](PROBABILISTIC_DSL_SPECIFICATION.md)
- [ProbLog Translation](PROBABILISTIC_DSL_PROBLOG_TRANSLATION.md)
---
**These examples demonstrate the full expressive power of PDSL across diverse application domains.**