5 Expert System - VforVitorio/F1_Strat_Manager GitHub Wiki

🧠 Expert System

Rule-based decision engine for race strategy recommendations

# Facts and Data Transformation

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Facts and Data Transformation

Relevant source files

Purpose and Scope

This document covers the core fact definitions and data transformation functions that form the foundation of the F1 Strategy Expert System. These components convert machine learning model outputs, telemetry data, and race information into structured facts that the rule engine can process to generate strategic recommendations.

For information about the specific rule implementations that process these facts, see Degradation Rules, Gap Analysis Rules, and Radio Message Rules. For details about the integrated rule engine that combines all fact types, see Integrated Rule Engine.

Fact Class Hierarchy

The expert system uses six core fact classes to represent different aspects of F1 race state and strategy information. Each fact class inherits from the Experta Fact base class and defines specific fields for structured data representation.

Core Fact Classes Overview

lap_time predicted_lap_time tire_age compound_id position driver_number

degradation_rate previous_rates fuel_adjusted_deg_percent predicted_rates

driver_number gap_ahead gap_behind gap_trends undercut_window

sentiment intent entities timestamp

lap total_laps race_phase track_status

action confidence explanation priority lap_issued

experta.Fact

TelemetryFact

DegradationFact

GapFact

RadioFact

RaceStatusFact

StrategyRecommendation

Field Definitions

Field Definitions

Field Definitions

Field Definitions

Field Definitions

Field Definitions

Sources: scripts/IS_agent/utils/N01_agent_setup.py 14-102

Detailed Fact Definitions

Fact Class Purpose Key Fields Mandatory Fields

TelemetryFact Car performance data lap_time, predicted_lap_time, tire_age, compound_id, position, driver_number None

DegradationFact Tire wear information degradation_rate, predicted_rates, previous_rates, fuel_adjusted_deg_percent None

GapFact Inter-car timing gaps gap_ahead, gap_behind, in_undercut_window, in_drs_window, car_ahead, car_behind driver_number

RadioFact Communication analysis sentiment, intent, entities, timestamp None

RaceStatusFact Race state information lap, total_laps, race_phase, track_status lap, total_laps

StrategyRecommendation System outputs action, confidence, explanation, priority, lap_issued action, confidence, explanation, lap_issued

Sources: scripts/IS_agent/utils/N01_agent_setup.py 14-102

Data Transformation Pipeline

The transformation pipeline converts raw ML model outputs and race data into structured facts through a series of specialized transformation functions. Each transformation function handles a specific data type and ensures proper format conversion and validation.

Transformation Flow Architecture

F1StrategyEngine

Fact Instances

Transformation Functions

ML Model Outputs

tire_degradation_predictions.csv

lap_time_predictions.csv

radio_analysis.json

gap_analysis.csv

transform_tire_predictions()

transform_lap_time_predictions()

transform_radio_analysis()

calculate_gap_consistency()

TelemetryFact

DegradationFact

RadioFact

GapFact

RaceStatusFact

F1StrategyEngine.declare()

Facts Database

Sources: scripts/IS_agent/utils/N01_agent_setup.py 156-542

scripts/IS_agent/N01_agent_setup.ipynb 504-637

Tire Degradation Transformation

The transform_tire_predictions() function processes ML tire degradation model outputs and creates both DegradationFact and TelemetryFact instances. This function handles intelligent data filtering based on current race lap and stint information.

predictions_df driver_number current_lap

Filter by DriverNumber

Filter by current_lap using RaceLap or CurrentTyreAge

Sort by LapsAheadPred

Extract PredictedDegradationRate

DegradationFact degradation_rate predicted_rates

TelemetryFact tire_age compound_id driver_number position

{'degradation': DegradationFact, 'telemetry': TelemetryFact}

Sources: scripts/IS_agent/utils/N01_agent_setup.py 156-271

The function includes sophisticated lap filtering logic:

Uses RaceLap column when available for direct lap matching

Falls back to CurrentTyreAge estimation for stint-based filtering

Implements closest-match algorithm for data selection

Handles edge cases with fallback to most recent data Radio Analysis Transformation

The radio transformation pipeline processes NLP analysis results from team radio communications into structured RadioFact instances.

Fact Creation

NLP Analysis

Input Processing

radio_audio.mp3

text_message

radio_nlp.transcribe_audio()

radio_nlp.analyze_radio_message()

analysis.json {sentiment, intent, entities}

json.load()

RadioFact sentiment intent entities timestamp

F1StrategyEngine

Sources: scripts/IS_agent/utils/N01_agent_setup.py 412-499

Gap Analysis Enhancement

The gap transformation includes consistency tracking to identify persistent strategic opportunities through the calculate_gap_consistency() function.

gaps_df

GapToCarAhead

GapToCarBehind LapNumber

Classify into windows: undercut_window (< 2.0s) overcut_window (2.0-3.5s) defensive_window (< 2.0s) safe_window (> 2.0s)

Initialize consistency counters: consistent_gap_ahead_laps = 1 consistent_gap_behind_laps = 1

For each driver:

Sort by LapNumber Compare consecutive windows

Update counters:

If same window: increment If different window: reset to 1

Enhanced DataFrame with consistency metrics

transform_gap_data_with_consistency()

GapFact with consistency data

Sources: scripts/IS_agent/utils/N01_agent_setup.py 501-542

scripts/IS_agent/N01_agent_setup.ipynb 951-1082

F1StrategyEngine Integration

The F1StrategyEngine class serves as the central fact management system, inheriting from Experta's KnowledgeEngine and providing specialized methods for F1 strategy processing.

Engine Architecture

Recommendation Retrieval

Fact Declaration Flow

F1StrategyEngine Class

init() rules_fired = []

get_recommendations() Sort by priority & confidence

record_rule_fired() Track rule execution

self.facts Experta fact storage

declare(fact)

Field validation

Type checking

Store in facts database

Filter StrategyRecommendation facts

Sort by (priority, confidence) descending order

Return recommendation list

Rule execution history with timestamps

Sources: scripts/IS_agent/utils/N01_agent_setup.py 104-154

Fact Management Methods

The engine provides specialized methods for fact management:

Method Purpose Return Type get_recommendations() Retrieve sorted strategy recommendations list[dict] record_rule_fired(rule_name) Track rule execution with timestamps None declare(fact) Add fact to engine (inherited from Experta) None

The get_recommendations() method implements a priority-based sorting system where recommendations are ordered by (priority, confidence) in descending order, ensuring the most urgent and confident recommendations appear first.

Sources: scripts/IS_agent/utils/N01_agent_setup.py 113-154

Data Loading and Preprocessing

The system includes specialized loader functions that interface with ML model prediction modules and handle data preprocessing before fact transformation.

ML Model Integration Points

Configuration

Loader Functions

External ML Modules

ML_tyre_pred.ML_utils.N02_model_tire_predictions

ML_tyre_pred.ML_utils.N00_model_lap_prediction

NLP_radio_processing.NLP_utils.N06_model_merging

load_tire_predictions()

load_lap_time_predictions()

process_radio_message()

compound_thresholds {1: 6, 2: 12, 3: 25}

models_path model artifacts

transform_tire_predictions()

transform_lap_time_predictions()

transform_radio_analysis()

Sources: scripts/IS_agent/utils/N01_agent_setup.py 273-410

scripts/IS_agent/utils/N01_agent_setup.py 438-477

Compound Threshold Configuration

The tire prediction loader uses compound-specific thresholds to determine when degradation monitoring should begin:

Compound ID Tire Type Monitoring Start Lap 1 Soft Lap 6 2 Medium Lap 12 3 Hard Lap 25

These thresholds reflect real F1 tire degradation patterns where softer compounds degrade faster and require earlier monitoring.

Sources: scripts/IS_agent/utils/N01_agent_setup.py 290-297

Race Phase Calculation

The system includes utility functions for contextual race analysis, including race phase determination based on completion percentage.

True

False

True

False

current_lap

total_laps

percentage = (current_lap / total_laps) * 100

percentage < 25%

'start'

percentage > 75%

'end'

'mid'

RaceStatusFact.race_phase

Sources: scripts/IS_agent/N01_agent_setup.ipynb 1199-1212

This race phase information enables the rule engine to apply different strategic logic based on race progression, such as more conservative strategies during the start phase and aggressive strategies during the end phase.


# Degradation Rules

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Degradation Rules Relevant source files

This document covers the tire degradation-based rule engine that analyzes tire performance data and generates strategic pit stop recommendations. The F1DegradationRules class implements four core rules that detect high degradation scenarios, stint extension opportunities, early warning signals, and predictive degradation alerts.

For information about gap-based strategic rules, see Gap Analysis Rules. For radio message-driven rules, see Radio Message Rules.

Rule Engine Architecture

The degradation rules system processes tire degradation data and ML predictions to generate strategic recommendations through an Experta-based rule engine.

Output

F1DegradationRules Engine

Fact Base

Data Processing

Input Data

Raw Tire Data

CSV Files

ML Tire Predictions load_tire_predictions()

load_degradation_data()

transform_tire_predictions()

analyze_degradation_rate()

DegradationFact degradation_rate predicted_rates previous_rates

TelemetryFact tire_age position driver_number

RaceStatusFact lap total_laps race_phase

high_degradation_pit_stop @Rule(DegradationFact, TelemetryFact)

stint_extension_recommendation @Rule(DegradationFact, TelemetryFact)

early_degradation_warning @Rule(DegradationFact)

predicted_high_degradation_alert @Rule(DegradationFact, TelemetryFact)

StrategyRecommendation action, confidence explanation, priority

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 253-413

Core Degradation Rules

The F1DegradationRules class implements four strategic rules using the Experta framework with specific degradation thresholds derived from data analysis.

Rule 1: High Degradation Pit Stop

This rule triggers immediate pit stop recommendations when tire degradation reaches critical levels.

Rule Action

Rule Conditions

degradation_rate > 0.3 TEST(lambda deg_rate: float(deg_rate) > 0.3)

tire_age > 10 TEST(lambda age: int(age) > 10)

StrategyRecommendation action='pit_stop' confidence=0.8 priority=2

Implementation: The rule uses MATCH and TEST operators to capture degradation rate and tire age values, then evaluates them against thresholds of 0.3 seconds/lap and 10 laps respectively.

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 259-293

Rule 2: Stint Extension Recommendation

This rule identifies opportunities to extend current stints when tires are performing well despite age.

Condition Threshold Purpose degradation_rate < 0.15 s/lap Current performance is good predicted_rates[0] < 0.20 s/lap Future performance remains acceptable tire_age > 12 laps Tires have significant age

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 295-338

Rule 3: Early Degradation Warning

This rule detects rapidly increasing degradation trends over consecutive laps to provide advance warning.

TEST(lambda rates: rates is not None and len(rates) >= 3 and (rates[-1] - rates[-3]) > 0.03)

The rule triggers when degradation rate increases by more than 0.03 seconds/lap over 3 consecutive laps, recommending prepare_pit action with medium priority.

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 340-373

Rule 4: Predicted High Degradation Alert

This rule uses ML model predictions to anticipate future degradation issues before they occur.

predicted_rates[0] > 0.2 Future degradation critical

tire_age > 8 Sufficient tire usage

StrategyRecommendation action='consider_pit' confidence=0.8 priority=2

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 375-412

Data Analysis and Thresholds

The degradation rules are based on empirical analysis of real F1 tire degradation data to establish appropriate thresholds.

Threshold Determination

The analyze_degradation_rate() function processes historical degradation data to establish rule thresholds:

Metric Value Usage

High degradation threshold 0.3 s/lap 75th percentile of positive degradation rates Low degradation threshold 0.15 s/lap 25th percentile of positive degradation rates Rapid increase threshold 0.03 s/lap Change over 3-lap window Predicted threshold 0.2 s/lap Model prediction trigger point

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 145-190

Data Processing Pipeline

Analysis Functions

Data Transformation

Data Loading

tire_degradation_fuel_adjusted.csv

load_degradation_data()

Calculate RaceLap stint_lengths + TyreAge

Calculate previous_rates get_previous_rates(n=3)

Convert integer columns

Position, TyreAge, DriverNumber

analyze_degradation_rate() Calculate percentiles

plot_driver_degradation_profile() Visualize patterns

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 50-133

Testing Infrastructure

The degradation rules system includes comprehensive testing capabilities for validation with real race data.

Single Driver Testing

The test_with_real_data() function validates rules against historical race data:

def test_with_real_data(race_data_path, models_path): # Load race data and generate predictions race_data = pd.read_csv(race_data_path) predictions = load_tire_predictions(race_data, models_path)

# Transform predictions to facts
facts = transform_tire_predictions(predictions, test_driver)

# Initialize and run engine
engine = F1DegradationRules()
engine.declare(facts['degradation'])
engine.declare(facts['telemetry'])
engine.run()

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 421-539

Multi-Driver Testing

The test_multiple_drivers() function enables comparative analysis across multiple drivers:

Function Component Purpose

Driver iteration Test rules across all available drivers

Fact correction Adjust degradation_rate from predicted_rates[0] if needed

Rule tracking Monitor which rules fire for each driver Results storage Collect recommendations and triggered rules

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 548-666

Integration with Expert System

The degradation rules integrate with the complete F1 strategy engine through inheritance and fact sharing.

Integration Points

Degradation System

Base Classes

F1StrategyEngine

Base rule engine functionality

experta.KnowledgeEngine Core rule processing

F1DegradationRules

Inherits from F1StrategyEngine

record_rule_fired() Track activated rules

get_recommendations() Retrieve strategy suggestions

F1CompleteStrategyEngine

Multiple inheritance

Conflict resolution

Priority-based filtering

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 253-257

scripts/IS_agent/utils/N01_agent_setup.py 4-11

Rule Output Format

Each degradation rule generates standardized StrategyRecommendation objects with the following structure:

Field Type Purpose action string Recommended action (pit_stop, extend_stint, prepare_pit, consider_pit) confidence float Rule confidence level (0.7-0.85) explanation string Human-readable justification with specific values priority int Recommendation priority (1-3, higher is more urgent) lap_issued int Lap number when recommendation was generated

Sources: scripts/IS_agent/utils/N02_degradation_time_rules.py 283-289

scripts/IS_agent/utils/N01_agent_setup.py 8


# Integrated Rule Engine

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Integrated Rule Engine Relevant source files

The Integrated Rule Engine is the central component of the F1 Strategy Manager that combines all specialized rule systems into a unified decision-making framework. It integrates separate rule engines for tire degradation, lap time prediction, gap analysis, and radio communication analysis, while providing sophisticated conflict resolution capabilities to ensure consistent and coherent strategy recommendations.

For information about specific rule systems, see Degradation Rules, Gap Analysis Rules, and Radio Message Rules.

Architecture Overview

The Integrated Rule Engine follows a multiple inheritance pattern where the main F1CompleteStrategyEngine class inherits from all specialized rule engines. This allows the integrated engine to access and utilize rules from all domains while providing enhanced coordination and conflict resolution.

KnowledgeEngine

+reset()

+declare(fact)

+run()

F1StrategyEngine

+get_recommendations()

+record_rule_fired()

F1DegradationRules

+high_degradation_pit_stop()

+stint_extension_recommendation()

+early_degradation_warning()

F1LapTimeRules

+optimal_performance_window()

+performance_cliff_detection()

+post_traffic_recovery()

F1RadioRules

+grip_issue_response()

+weather_information_adjustment()

+incident_reaction()

F1GapRules

+undercut_opportunity()

+defensive_pit_stop()

+strategic_overcut()

F1CompleteStrategyEngine

+active_systems

+get_recommendations()

+_resolve_conflicts()

+record_rule_fired()

Sources:

scripts/IS_agent/N06_rule_merging.ipynb 127-150 scripts/app/app_modules/agent/N06_rule_merging.py 78-101 scripts/IS_agent/utils/N06_rule_merging.py 78-101 Fact Types and Knowledge Representation

The rule engine operates on various fact types that represent different aspects of race strategy. These facts are created from raw data and serve as the input to the rule engine.

Output

Integrated Engine

Rule Engines

Structured Facts

Fact Transformation

Raw Data

FastF1 Telemetry

Tire Degradation Models

Lap Time Predictions

Gap Analysis

Radio Communications

transform_all_facts() Function

TelemetryFact

DegradationFact

GapFact

RadioFact

RaceStatusFact

F1DegradationRules

F1LapTimeRules

F1GapRules

F1RadioRules

F1CompleteStrategyEngine

StrategyRecommendation

Sources:

scripts/app/app_modules/agent/N01_agent_setup.py 14-102 scripts/app/app_modules/agent/N06_rule_merging.py 238-431 scripts/IS_agent/N06_rule_merging.ipynb 513-680

Core Components

F1CompleteStrategyEngine Class

The F1CompleteStrategyEngine class is the central component that inherits from all specialized rule engines and adds conflict resolution capabilities.

Key features:

Multiple Inheritance: Inherits all rules from specialized engines

Active Systems Tracking: Monitors which rule systems have fired rules Enhanced Recommendation Processing: Adds conflict resolution to recommendations

The F1CompleteStrategyEngine class implementation demonstrates multiple inheritance from all specialized rule engines:

class F1CompleteStrategyEngine(F1DegradationRules, F1LapTimeRules, F1RadioRules, F1GapRules): def init(self): super().init() self.active_systems = { 'degradation': False, 'lap_time': False, 'radio': False, 'gap': False }

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 78-101 scripts/IS_agent/utils/N06_rule_merging.py 78-101 scripts/IS_agent/N06_rule_merging.ipynb 127-150 Active Systems Tracking

The integrated engine tracks which specialized rule systems have fired rules. This information is valuable for:

Debugging which parts of the system are active

Providing context for recommendations Understanding the basis for strategic decisions

The record_rule_fired method tracks which rule systems are active based on rule name patterns:

def record_rule_fired(self, rule_name): super().record_rule_fired(rule_name)

# Track which system the rule belongs to
if rule_name.startswith(('high_degradation', 'stint_extension', 'early_degradation')):
    self.active_systems['degradation'] = True
elif rule_name.startswith(('optimal_performance', 'performance_cliff', 'post_traffic')):
    self.active_systems['lap_time'] = True
elif rule_name.startswith(('grip_issue', 'weather_information', 'incident_reaction')):
    self.active_systems['radio'] = True
elif rule_name.startswith(('undercut_opportunity', 'defensive_pit', 'strategic_overcut')):
    self.active_systems['gap'] = True

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 217-235 scripts/IS_agent/utils/N06_rule_merging.py 217-235 scripts/IS_agent/N06_rule_merging.ipynb 263-281 Conflict Resolution Mechanism

A key feature of the integrated engine is its ability to resolve conflicting recommendations. This is critical in F1 strategy where different data sources might suggest contradictory actions.

Conflict Resolution Process

Yes

No

Get All Recommendations

Group by Driver

Multiple Recommendations for Same Driver?

Apply Conflict Resolution

Keep as-is

Identify Conflicting Action Pairs

Determine Best Recommendation per Action

Compare and Select Best Recommendations

Enhance Explanation with Conflict Info

Sort by Priority and Confidence

Return Final Recommendations

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 102-141 scripts/IS_agent/utils/N06_rule_merging.py 102-141 scripts/IS_agent/N06_rule_merging.ipynb 151-189 Conflicting Action Pairs

The engine defines specific pairs of actions that are considered mutually exclusive:

Action Pair Conflict Reason extend_stint + pit_stop Cannot extend stint and pit at the same time extend_stint + prioritize_pit Cannot extend stint and prioritize pitting extend_stint + defensive_pit Cannot extend stint and make a defensive pit extend_stint + consider_pit Cannot extend stint and consider pitting prepare_pit + pit_stop No need to prepare if immediate pit is recommended prepare_pit + prioritize_pit No need to prepare if prioritized pit is recommended perform_undercut + perform_overcut Cannot do undercut and overcut simultaneously

When conflicting recommendations are detected, the engine selects the one with higher priority and confidence.

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 164-178 scripts/IS_agent/utils/N06_rule_merging.py 164-178 scripts/IS_agent/N06_rule_merging.ipynb 212-226 Fact Transformation Pipeline

The integrated engine requires properly formatted facts. The transform_all_facts function serves as a comprehensive pipeline for converting raw data into facts.

Output Facts

Fact Validation

Transformation Functions

Input Data Sources

tire_predictions

lap_predictions

gap_data

radio_json_path

current_lap & total_laps

transform_tire_predictions()

transform_lap_time_predictions()

transform_gap_data_with_consistency()

transform_radio_analysis()

calculate_race_phase()

Handle null values

Type conversions

Default values

TelemetryFact

DegradationFact

GapFact

RadioFact

RaceStatusFact

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 238-431 scripts/IS_agent/utils/N06_rule_merging.py 238-431 scripts/IS_agent/N06_rule_merging.ipynb 513-680 Complete Strategy Analysis Pipeline

The analyze_strategy function provides an end-to-end pipeline for F1 strategy analysis. It integrates all components of the system:

Data Loading: Loads data from various sources

Fact Transformation: Converts data into facts for the rule engine

Rule Execution: Runs the integrated rule engine

Recommendation Generation: Produces prioritized strategy recommendations

Result Processing

Rule Engine

Fact Transformation

Data Loading

Race Telemetry

Tire Prediction Models

Lap Time Prediction Model

Gap Data

Radio Messages

transform_all_facts()

Initialize F1CompleteStrategyEngine

Declare Facts

Run Engine

Get Recommendations

Priority Sorting

Conflict Resolution

Explanation Enhancement

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 522-639 scripts/IS_agent/utils/N06_rule_merging.py 522-639 scripts/IS_agent/N06_rule_merging.ipynb 1054-1191 Example Usage

The Integrated Rule Engine can be used through the analyze_strategy function, which provides a complete pipeline from raw data to strategy recommendations:

recommendations = analyze_strategy( driver_number=44, # Lewis Hamilton race_data_path="data/race_telemetry.csv", models_path="models/tire_models/", lap_model_path="models/lap_model.pkl", gap_data_path="data/gap_data.csv", radio_message="Box this lap, we're switching to plan B", current_lap=25, total_laps=66 )

The function also supports comprehensive analysis across all drivers using analyze_all_drivers_with_real_radios, which processes real radio communications from the 2023 Spanish GP and generates recommendations at strategic points throughout the race.

The output is a list of prioritized strategy recommendations that have been processed through the conflict resolution mechanism:

Recommendation 1: Action: pit_stop Confidence: 0.85 Priority: 3 Explanation: Tire performance cliff detected. Model predicts 0.75s slowdown...

Recommendation 2: Action: defensive_pit Confidence: 0.80 Priority: 2 Explanation: Defensive pit stop strongly recommended in mid stint...

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 522-639 scripts/IS_agent/utils/N06_rule_merging.py 910-1350 scripts/IS_agent/N06_rule_merging.ipynb 1054-1191 Integration with UI and Data Processing

The Integrated Rule Engine supports comprehensive data processing workflows, including real radio extraction and analysis:

Output Processing

Rule Engine Integration

Data Processing Pipeline

Data Sources

OpenF1 API

FastF1 Cache

Race Telemetry CSV

ML Model Artifacts

extract_spain_gp_radios()

process_spain_gp_radios()

map_radios_to_laps()

load_all_data()

transform_all_facts()

F1CompleteStrategyEngine

analyze_all_drivers_with_real_radios()

Conflict Resolution

CSV Results Export

Strategy Recommendations

The engine processes real radio communications from the 2023 Spanish GP, mapping them to specific race laps and generating contextual strategy recommendations. The analyze_all_drivers_with_real_radios function demonstrates end-to-end processing from raw data extraction to final recommendations.

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 642-1366 scripts/IS_agent/utils/N06_rule_merging.py 642-1366 scripts/IS_agent/N06_rule_merging.ipynb 937-1350 Best Practices for Extending the Rule Engine

Maintaining Rule System Separation: Keep specialized rules in their respective classes to maintain modularity.

Naming Convention for Rules: Use consistent prefixes for rule names (e.g., high_degradation_*) to ensure proper rule system tracking.

Consistent Recommendation Structure: All recommendations should include action, confidence, explanation, and priority for proper conflict resolution.

Updating Conflict Pairs: When adding new action types, update the conflicting_pairs list in _resolve_conflicts to define their relationships with existing actions.

Fact Validation: Always validate facts before declaring them to the engine to avoid schema validation errors.

Sources:

scripts/app/app_modules/agent/N06_rule_merging.py 143-215 scripts/IS_agent/utils/N06_rule_merging.py 143-215 scripts/IS_agent/N06_rule_merging.ipynb 191-281 Conclusion

The Integrated Rule Engine is the cornerstone of the F1 Strategy Manager, providing a unified framework for evaluating diverse sources of race information and generating coherent strategy recommendations. By combining specialized rule systems with sophisticated conflict resolution, it enables comprehensive strategy analysis that considers tire degradation, lap times, gaps between cars, and radio communications. The modular architecture allows for easy extension with new rule systems while maintaining a consistent recommendation framework.


# Expert System

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Expert System Relevant source files

The Expert System is an Experta-based rule engine that processes machine learning predictions and race data to generate strategic recommendations for Formula 1 racing. Built on the RETE algorithm, it combines tire degradation analysis, lap time predictions, gap analysis, and NLP-processed radio communications into coherent strategy advice.

The system implements a declarative programming paradigm where F1 strategy knowledge is encoded as production rules that pattern-match against a dynamic fact base. This approach provides explainable AI decisions that can integrate diverse data sources while maintaining clear reasoning chains.

For detailed implementations, see Facts and Data Transformation, Degradation Rules, Gap Analysis Rules, Radio Message Rules, and Integrated Rule Engine.

System Architecture

The Expert System follows a modular inheritance hierarchy built on Experta's KnowledgeEngine. The F1CompleteStrategyEngine class inherits from multiple specialized rule engines, combining domain-specific rules into a unified decision-making system.

Class Hierarchy and Multiple Inheritance

Sources:

scripts/IS_agent/N06_rule_merging.ipynb 127-282 scripts/IS_agent/utils/N06_rule_merging.py 78-235 Data Processing Pipeline

The Expert System processes ML predictions and race data through a structured pipeline that transforms raw data into fact objects, applies rules, and resolves conflicts to generate prioritized recommendations.

📊 Interactive System Diagram
View the complete system architecture diagram at DeepWiki for detailed visualization.

[] (Sorted by priority)

Sources:

scripts/IS_agent/N06_rule_merging.ipynb 514-679 scripts/IS_agent/utils/N06_rule_merging.py 238-431 scripts/IS_agent/utils/N01_agent_setup.py 156-636 Knowledge Base Facts

The Expert System operates on typed fact objects that represent different aspects of race state. Each fact class inherits from Experta's Fact base class and defines fields using the Field() constructor with type validation.

Fact Class Description Primary Fields

TelemetryFact Car performance metrics lap_time, predicted_lap_time, tire_age, compound_id, position, driver_number

DegradationFact Tire degradation analysis degradation_rate, predicted_rates, fuel_adjusted_deg_percent

GapFact Inter-car gap analysis gap_ahead, gap_behind, in_undercut_window, consistent_gap_ahead_laps

RadioFact NLP-processed team radio sentiment, intent, entities

RaceStatusFact Current race context lap, total_laps, race_phase, track_status

StrategyRecommendation System output action, confidence, explanation, priority, lap_issued

Fact Schema Definition

The fact objects serve as the working memory for the RETE algorithm, with rules pattern-matching against fact attributes to determine applicable strategic actions.

Sources:

scripts/IS_agent/N01_agent_setup.ipynb 252-417 scripts/IS_agent/utils/N01_agent_setup.py 14-101 scripts/app/app_modules/agent/N01_agent_setup.py 14-101 Specialized Rule Engines

The Expert System is implemented as four domain-specific rule engines that inherit from F1StrategyEngine. Each engine focuses on a specific aspect of F1 strategy and contains rules decorated with Experta's @Rule decorator.

Rule Engine Overview

Data Inputs

F1GapRules

F1RadioRules

F1LapTimeRules

F1DegradationRules

Tire Degradation Rules • high_degradation_pit_stop • stint_extension_recommendation • early_degradation_warning

Performance Rules • optimal_performance_window • performance_cliff_detection • post_traffic_recovery

NLP-driven Rules • grip_issue_response • weather_information_adjustment • incident_reaction

Strategic Gap Rules • undercut_opportunity • defensive_pit_stop • strategic_overcut

DegradationFact

TelemetryFact

TelemetryFact

RaceStatusFact

RadioFact

RaceStatusFact

GapFact

RaceStatusFact

StrategyRecommendation

Each rule engine operates independently but can be combined in the F1CompleteStrategyEngine for comprehensive strategy analysis. The engines use pattern matching against fact attributes to determine when rules should fire and generate StrategyRecommendation facts.

Rule System Architecture

Engine Class Input Facts Strategic Focus Key Actions

F1DegradationRules DegradationFact, TelemetryFact Tire management pit_stop, extend_stint, prepare_pit

F1LapTimeRules TelemetryFact, RaceStatusFact Performance optimization push_strategy, recovery_push

F1RadioRules RadioFact, RaceStatusFact Communication-driven decisions prioritize_pit, prepare_rain_tires

F1GapRules GapFact, RaceStatusFact Positional strategy perform_undercut, defensive_pit, perform_overcut

Sources:

scripts/IS_agent/N06_rule_merging.ipynb 64-75 scripts/IS_agent/utils/N06_rule_merging.py 37-48 scripts/IS_agent/N02_degradation_time_rules.ipynb 14-30 F1CompleteStrategyEngine Integration

The F1CompleteStrategyEngine uses Python's multiple inheritance to combine all specialized rule engines into a unified strategy system. This design allows all domain-specific rules to be evaluated simultaneously while providing conflict resolution for contradictory recommendations.

Multiple Inheritance Structure

Output Generation

Input Processing

Integration Layer

Specialized Rule Engines

F1DegradationRules

F1LapTimeRules

F1RadioRules

F1GapRules

F1CompleteStrategyEngine

Multiple Inheritance

active_systems: dict {'degradation': bool, 'lap_time': bool, 'radio': bool, 'gap': bool}

_resolve_conflicts() Priority-based selection

transform_all_facts() Data to Facts conversion

engine.declare(fact) Working memory population

get_recommendations() Sorted by priority

StrategyRecommendation[]

Conflict-resolved

Active System Tracking

The integrated engine maintains state about which rule systems have fired during execution:

From F1CompleteStrategyEngine.init()

self.active_systems = { 'degradation': False, 'lap_time': False, 'radio': False, 'gap': False }

This tracking is updated in the record_rule_fired() method based on rule name prefixes, enabling analysis of which strategic domains are most influential for a given race situation.

Sources:

scripts/IS_agent/N06_rule_merging.ipynb 127-282 scripts/IS_agent/utils/N06_rule_merging.py 78-235 scripts/app/app_modules/agent/N06_rule_merging.py 78-235 Conflict Resolution System

The F1CompleteStrategyEngine implements a sophisticated conflict resolution mechanism in the _resolve_conflicts() method. When multiple rules fire contradictory recommendations for the same driver, the system uses priority and confidence values to select optimal strategies.

Conflict Resolution Algorithm

Output Enhancement

Resolution Logic

Predefined Conflicts

Conflict Detection

get_recommendations() All fired rules

Group by driver_number

Check conflicting_pairs[] action incompatibilities

extend_stint vs pit_stop

prepare_pit vs pit_stop

perform_undercut vs perform_overcut

Compare priority values

Compare confidence values

max(priority, confidence)

Add to excluded_recommendations

Append conflict resolution note

Sort by (priority, confidence)

Conflict-resolved recommendations

Conflict Pairs Definition

The system defines logical conflicts between strategy actions:

conflicting_pairs = [ ('extend_stint', 'pit_stop'), ('extend_stint', 'prioritize_pit'), ('extend_stint', 'defensive_pit'), ('extend_stint', 'consider_pit'), ('prepare_pit', 'pit_stop'), ('prepare_pit', 'prioritize_pit'), ('perform_undercut', 'perform_overcut') ]

This ensures that the system never recommends contradictory actions like extending a stint while simultaneously calling for a pit stop.

Sources:

scripts/IS_agent/N06_rule_merging.ipynb 143-215 scripts/IS_agent/utils/N06_rule_merging.py 143-215 Strategy Analysis Pipeline

The Expert System provides an end-to-end analysis pipeline through the analyze_strategy() function, which orchestrates data loading, transformation, rule execution, and recommendation generation.

Complete Analysis Workflow "_resolve_conflicts()" "Rule Engines" "F1CompleteStrategyEngine" "transform_all_facts()" "load_all_data()" "analyze_strategy()" "_resolve_conflicts()" "Rule Engines" "F1CompleteStrategyEngine" "transform_all_facts()" "load_all_data()" "analyze_strategy()" Load race data, models, radio data dict Convert to facts transform_tire_predictions() transform_lap_time_predictions() transform_gap_data_with_consistency() transform_radio_analysis() facts dict engine.reset() declare(fact) for each fact engine.run()

Evaluate all rules (RETE)

Pattern matching StrategyRecommendation facts get_recommendations() _resolve_conflicts()

Resolved recommendations

Sorted recommendations Data Source Integration

The load_all_data() function handles multiple data sources:

Data Source Function Output Type

Tire predictions load_tire_predictions() DataFrame with degradation rates

Lap time predictions predict_lap_times() DataFrame with future lap times

Gap analysis CSV or calculated DataFrame with inter-car gaps Radio messages process_radio_message() JSON path to NLP analysis

Each data source is optional, allowing the system to operate with partial information when some data sources are unavailable.

Sources:

scripts/IS_agent/utils/N06_rule_merging.py 522-639 scripts/IS_agent/utils/N06_rule_merging.py 434-519 Strategic Actions and Output Format

The Expert System generates StrategyRecommendation facts with standardized action types, confidence levels, and explanations. The recommendations are prioritized and sorted to present the most critical strategic decisions first.

Recommendation Structure

Each StrategyRecommendation contains:

Field Type Description action str Specific strategic action to take confidence float System confidence in recommendation (0.0-1.0) explanation str Human-readable justification for the action priority int Urgency level (higher = more urgent) lap_issued int Race lap when recommendation was generated Standard Strategic Actions

The system generates recommendations with these action types:

Strategic Actions

Pit Stop Actions

Stint Management

Positional Strategy Weather & Conditions pit_stop prioritize_pit defensive_pit prepare_pit consider_pit extend_stint push_strategy recovery_push perform_undercut perform_overcut defensive_position prepare_rain_tires adjust_for_weather incident_response

The get_recommendations() method returns recommendations sorted by (priority, confidence) in descending order, ensuring the most critical and confident recommendations appear first in the output.

Sources:

scripts/IS_agent/N01_agent_setup.ipynb 407-417 scripts/IS_agent/utils/N01_agent_setup.py 88-101 scripts/IS_agent/utils/N01_agent_setup.py 113-133 Implementation Architecture

The Expert System is implemented in a modular structure that separates concerns and enables independent development of rule domains. The codebase follows a clear separation between notebook prototypes and production modules.

File Organization

Application Integration

Specialized Rule Modules

Core Implementation

utils/N01_agent_setup.py Fact classes & base engine

utils/N06_rule_merging.py F1CompleteStrategyEngine

utils/N02_degradation_time_rules.py F1DegradationRules

utils/N03_lap_time_rules.py F1LapTimeRules

utils/N04_nlp_rules.py F1RadioRules

utils/N05_gap_rules.py F1GapRules

app_modules/agent/ Streamlit integration

IS_agent/*.ipynb Development prototypes

Integration Points

The Expert System integrates with other components through well-defined interfaces:

ML Models: Consumes predictions via transform functions

NLP Pipeline: Processes radio analysis JSON files

Streamlit Dashboard: Provides strategic recommendations to UI

Data Processing: Uses utility functions for gap analysis and consistency calculations

The modular design allows each rule system to be developed, tested, and maintained independently while providing a unified interface through the F1CompleteStrategyEngine.

Sources:

scripts/IS_agent/utils/N06_rule_merging.py 1-11 scripts/app/app_modules/agent/N06_rule_merging.py 1-11 scripts/IS_agent/N01_agent_setup.ipynb 1-20 RETE Algorithm and Experta Foundation

The Expert System is built on Experta, a Python implementation of the RETE algorithm designed for production rule systems. RETE provides efficient pattern matching by building a discrimination network that avoids re-evaluating all rules when facts change.

RETE Algorithm Benefits

RETE Algorithm

Facts

Discrimination Network

Pre-compiled patterns

Incremental Updates

Only affected nodes

Efficient Matching

Traditional Rule Evaluation

Facts

Evaluate All Rules

O(n × m)

Find Matches

Execution Cycle

The Experta engine follows a standard recognize-act cycle:

Match: Identify rules whose conditions match current facts

Conflict Resolution: Select which rule to fire when multiple match

Act: Execute the selected rule's action (declare new facts)

Repeat: Continue until no more rules can fire

This cycle enables the Expert System to reason incrementally, building up strategic knowledge as new facts are declared and rules fire in response to changing race conditions.

Declarative Rule Definition

Rules are defined declaratively using Experta's @Rule decorator with pattern matching syntax:

@Rule( DegradationFact(degradation_rate=MATCH.degradation_rate), TelemetryFact(tire_age=MATCH.tire_age), TEST(lambda degradation_rate, tire_age: degradation_rate > 0.15 and tire_age > 10) ) def high_degradation_pit_stop(self, degradation_rate, tire_age): # Rule action: declare StrategyRecommendation

This approach allows F1 strategy knowledge to be expressed naturally while leveraging RETE's efficient execution.

Sources:

scripts/IS_agent/N01_agent_setup.ipynb 58-91 scripts/IS_agent/N01_agent_setup.ipynb 120-131 scripts/IS_agent/N02_degradation_time_rules.ipynb 10-30 Benefits of the Expert System Approach

The Expert System offers several advantages for F1 strategy management:

Explainability: Rules provide clear explanations for recommendations

Integration of Diverse Inputs: Combines numerical data with natural language information

Domain Knowledge Encoding: Captures F1 strategic expertise in explicit rules

Conflict Management: Resolves contradictory advice through principled prioritization Modularity: Specialized rule systems can be developed and maintained independently

These characteristics make the Expert System an ideal complement to the machine learning models, combining data-driven predictions with expert knowledge.

Sources:

scripts/IS_agent/N01_agent_setup.ipynb 120-131


📝 This documentation is automatically generated using browser automation.
🕒 Last updated: $(date '+%Y-%m-%d %H:%M:%S UTC') 📊 Auto-organized from 4 content files