Expert System - VforVitorio/F1_Strat_Manager GitHub Wiki
🧠 Expert System
Rule-based decision engine for race strategy recommendations
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.
Strategic Output
F1CompleteStrategyEngine
Fact Base (Working Memory)
Data Transformation Layer
ML Predictions & Data
tire_predictions (DataFrame)
lap_predictions (DataFrame)
gap_data (DataFrame)
radio_json_path (JSON file)
transform_all_facts()
transform_tire_predictions()
transform_lap_time_predictions()
transform_gap_data_with_consistency()
transform_radio_analysis()
TelemetryFact
DegradationFact
GapFact
RadioFact
RaceStatusFact
Rule Evaluation (RETE Algorithm)
_resolve_conflicts()
StrategyRecommendation[] (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
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.
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
Data Processing Utilities
Model Artifacts and Deployment
Development Environment
Gap Analysis Rules
Relevant source files
Purpose and Scope
This document covers the gap analysis rules component of the F1 Strategy Manager's expert system. Gap analysis rules generate strategic recommendations based on time differences between cars during races, focusing on undercut opportunities, defensive strategies, overcut timing, and traffic management. These rules operate on GapFact objects and integrate with other strategy components through the F1CompleteStrategyEngine.
For tire degradation-based strategic decisions, see Degradation Rules. For radio communication-driven rules, see Radio Message Rules. For the complete integrated rule engine, see Integrated Rule Engine.
Gap Rule Engine Architecture
The gap analysis system is built around the F1GapRules class, which inherits from F1StrategyEngine and implements four core strategic rules. The engine processes gap data calculated from FastF1 timing information and generates strategic recommendations with confidence scores and priority levels.
Strategic Output
F1GapRules Engine
Fact Transformation
Gap Calculation
Data Input
FastF1 Race Data
race.laps DataFrame
calculate_all_gaps()
Gap Results DataFrame
calculate_gap_consistency()
transform_gap_data_with_consistency()
GapFact objects
TelemetryFact objects
RaceStatusFact objects
undercut_opportunity()
defensive_pit_stop()
strategic_overcut()
traffic_management()
StrategyRecommendation
Actions: perform_undercut, defensive_pit, perform_overcut, adjust_pit_window
Sources: scripts/IS_agent/N05_gap_rules.ipynb 807-1025
scripts/IS_agent/utils/N05_gap_rules.py 193-301
Strategic Rules Implementation
The F1GapRules class implements four strategic rules using the Experta framework. Each rule uses @Rule decorators with pattern matching conditions and generates StrategyRecommendation objects with specific actions, confidence levels, and explanations.
Rule Conditions and Actions Matrix
Rule Gap Condition Consistency Requirement Lap Window Action Confidence undercut_opportunity gap_ahead < 2.0s ≥3 consecutive laps 6-26, 27-48 perform_undercut 0.85 defensive_pit_stop gap_behind < 2.0s ≥3 consecutive laps 6-26, 27-48 defensive_pit 0.80 strategic_overcut 2.0s < gap_ahead < 3.5s ≥4 consecutive laps 6-26, 27-48 perform_overcut 0.80 traffic_management position > 10 AND gap_to_leader > 30.0s N/A 6-26, 27-48 adjust_pit_window 0.70 Undercut Opportunity Detection
The undercut rule identifies situations where a car has been consistently close to the car ahead, suggesting on-track overtaking difficulty and potential for pit strategy advantage.
Action Generation
Rule Logic
Rule Conditions
gap_ahead < 2.0s
consistent_gap_ahead_laps ≥ 3
lap ∈ [6-26] ∪ [27-48]
MATCH driver_number, gap_ahead, consistent_laps, lap
TEST gap conditions AND consistency AND lap window
action: perform_undercut
confidence: 0.85
priority: 2
explanation: Strong undercut opportunity...
Sources: scripts/IS_agent/N05_gap_rules.ipynb 816-866
scripts/IS_agent/utils/N05_gap_rules.py 194-219
Defensive and Overcut Strategies
The defensive pit stop rule responds to persistent pressure from behind, while the overcut rule identifies opportunities to extend stint length in clean air. Both rules use similar pattern matching but with different gap thresholds and consistency requirements.
Shared Conditions
Overcut Rule Pattern
Defensive Rule Pattern
gap_behind < 2.0s
consistent_gap_behind_laps ≥ 3
defensive_pit
2.0s < gap_ahead < 3.5s
consistent_gap_ahead_laps ≥ 4
perform_overcut
lap ∈ [6-26] ∪ [27-48]
GapFact + RaceStatusFact
Sources: scripts/IS_agent/N05_gap_rules.ipynb 868-970
scripts/IS_agent/utils/N05_gap_rules.py 221-273
Gap Data Processing Pipeline
Gap calculation transforms FastF1 lap timing data into structured gap metrics with consistency tracking. The calculate_all_gaps function processes race data to determine relative positions and time differences between cars at each lap completion.
Gap Calculation Workflow
Output Structure
Relative Gap Metrics
Position Calculation
Input Processing
race.laps DataFrame
Identify driver_column: 'Driver' or 'DriverNumber'
Identify lap_column: 'LapNumber' or 'TyreAge'
For each lap_num in lap_numbers
Calculate leader time: min(Time) for lap
Calculate gap_to_leader for each driver
Sort drivers by gap_to_leader
gap_ahead = current_gap - previous_driver_gap
gap_behind = next_driver_gap - current_gap
in_undercut_window = gap_ahead < 2.5s
in_drs_window = gap_ahead < 1.0s
Gap Results DataFrame
LapNumber, Driver, DriverNumber, Position, GapToLeader, GapToCarAhead, GapToCarBehind, InUndercutWindow, InDRSWindow
Sources: scripts/IS_agent/N05_gap_rules.ipynb 326-470
scripts/IS_agent/utils/N05_gap_rules.py 47-190
Gap Consistency Tracking
The system tracks gap consistency over multiple laps using calculate_gap_consistency, which identifies periods where cars maintain similar relative positions. This enables rules to distinguish between temporary proximity and sustained strategic opportunities.
Consistency Metric Purpose Threshold consistent_gap_ahead_laps Track sustained following distance Used in undercut/overcut rules consistent_gap_behind_laps Track sustained pressure from behind Used in defensive rules undercut_window Quick proximity check gap_ahead < 2.5s drs_window DRS eligibility tracking gap_ahead < 1.0s
Sources: scripts/IS_agent/utils/N01_agent_setup.py
scripts/IS_agent/N05_gap_rules.ipynb 1710-1712
Testing and Validation Framework
The gap rules system includes comprehensive testing infrastructure through the test_gap_rules function, which enables scenario-based validation of rule behavior with controlled gap conditions.
Testing Architecture
Result Analysis
Engine Execution
Fact Creation
Test Input
scenario_name
driver_number
gap_data dict
current_lap
additional_facts
GapFact from gap_data
TelemetryFact with position
RaceStatusFact with lap info
F1GapRules engine
engine.reset()
engine.declare(facts)
engine.run()
engine.get_recommendations()
engine.rules_fired
Test results display
Example Test Scenarios
The testing framework includes predefined scenarios for each rule type:
Undercut scenario
undercut_scenario = { 'gap_ahead': 1.8, # Close to car ahead (< 2.0s) 'consistent_gap_ahead_laps': 4, # Consistently close for 4 laps 'gap_behind': 3.5, # Safe from behind }
Defensive scenario
defensive_scenario = { 'gap_behind': 1.5, # Car close behind (< 2.0s) 'consistent_gap_behind_laps': 3, # Consistently threatened for 3 laps 'gap_ahead': 5.2, # Far from car ahead }
Sources: scripts/IS_agent/N05_gap_rules.ipynb 1051-1172
scripts/IS_agent/utils/N05_gap_rules.py 303-397
Integration with Race Analysis
The analyze_race_gaps function provides the complete pipeline for processing race data and generating strategic recommendations. It implements sophisticated filtering to prevent recommendation spam while maintaining strategic relevance.
Race Analysis Pipeline
Output
Recommendation Generation
Strategic Analysis
Gap Processing
Data Loading
fastf1.get_session()
race.load()
race.laps
calculate_all_gaps()
calculate_gap_consistency()
Map driver metadata
Strategic windows: [6-26], [27-48]
Strategic lap sampling (every 4th lap)
Gap change threshold: 0.4s
F1GapRules.run() per lap
Action limits per driver per window
Add driver/lap metadata
Final recommendations DataFrame
Optional CSV export
Recommendation Filtering Strategy
The system implements intelligent filtering to prevent excessive recommendations while preserving strategic insights:
Filter Type Purpose Implementation
Action Limits Prevent spam Max 3 undercut/defensive/overcut, max 5 traffic per driver per window Gap Change Detection Focus on significant changes Minimum 0.4s gap change between analyzed laps
Strategic Sampling Reduce computational load Analyze every 4th lap plus window boundaries
Lap Windows Focus strategic phases Only analyze laps 6-26 (early) and 27-48 (mid)
Sources: scripts/IS_agent/N05_gap_rules.ipynb 1615-1962
scripts/IS_agent/utils/N05_gap_rules.py 400-619
Data Processing Utilities
Model Artifacts and Deployment
Development Environment
Radio Message Rules
Relevant source files
Purpose and Scope
The Radio Message Rules system processes Formula 1 team radio communications using Natural Language Processing (NLP) to generate strategic recommendations. This system transforms qualitative information from driver and team communications into actionable strategic insights that complement the quantitative data from telemetry and tire degradation analysis.
For tire degradation-based strategic decisions, see Degradation Rules. For gap-based strategic decisions, see Gap Analysis Rules. For the complete integrated strategy engine, see Integrated Rule Engine.
System Architecture
The Radio Message Rules system operates as part of the expert system framework, processing radio communications through a multi-stage pipeline that converts natural language into structured strategic recommendations.
Radio Processing Pipeline
Raw Radio Message
process_radio_message()
NLP Analysis Pipeline
JSON Analysis Output
transform_radio_analysis()
RadioFact Object
F1RadioRules Engine
StrategyRecommendation Objects
Sentiment Analysis
Intent Classification
Named Entity Recognition
JSON Structure
sentiment: negative/neutral/positive
intent: PROBLEM/INFORMATION/WARNING
entities: WEATHER/TECHNICAL_ISSUE/INCIDENT/etc
Radio Message Processing Flow
Sources: scripts/IS_agent/N04_nlp_rules.ipynb 114-123
scripts/IS_agent/utils/N04_nlp_rules.py 128-146
Rule Engine Class Hierarchy
"processes"
"generates"
F1StrategyEngine
+rules_fired: list
+declare(fact)
+run()
+get_recommendations()
+record_rule_fired(rule_name)
F1RadioRules
+grip_issue_response(entities, lap)
+weather_information_adjustment(entities, lap)
+incident_reaction(entities, lap)
RadioFact
+sentiment: str
+intent: str
+entities: dict
+message: str
+timestamp: str
StrategyRecommendation
+action: str
+confidence: float
+explanation: str
+priority: int
+lap_issued: int
Rule Engine Class Structure
Sources: scripts/IS_agent/utils/N04_nlp_rules.py 41-125
scripts/IS_agent/utils/N01_agent_setup.py 1-10
Core Rule Implementations
The F1RadioRules class implements three primary strategic rules that analyze different aspects of radio communications.
Rule 1: Grip Issue Response
This rule detects when drivers report tire or grip-related problems and recommends prioritizing pit stops.
Rule Conditions:
RadioFact(sentiment="negative")
Entities containing 'grip', 'struggle', or TECHNICAL_ISSUE categories Active RaceStatusFact for lap context
Rule Implementation:
@Rule( RadioFact(sentiment="negative"), RadioFact(entities=MATCH.entities), TEST(lambda entities: any('grip' in str(value).lower() for category, values in entities.items() for value in values) or any('struggle' in str(value).lower() for category, values in entities.items() for value in values) or len(entities.get('TECHNICAL_ISSUE', [])) > 0), RaceStatusFact(lap=MATCH.lap) ) def grip_issue_response(self, entities, lap):
Generated Recommendation:
Action: prioritize_pit
Confidence: 0.85
Priority: 2 (Medium-high)
Explanation: Driver reports degradation issues with telemetry confirmation recommendation
Sources: scripts/IS_agent/N04_nlp_rules.ipynb 333-403
scripts/IS_agent/utils/N04_nlp_rules.py 45-75
Rule 2: Weather Information Adjustment
This rule responds to weather-related communications and recommends preparing for tire strategy changes.
Rule Conditions:
Entities containing WEATHER categories or 'wet' in TRACK_CONDITION entities
Active RaceStatusFact for lap context
Rule Implementation:
@Rule( RadioFact(entities=MATCH.entities), TEST(lambda entities: len(entities.get('WEATHER', [])) > 0 or any('wet' in condition.lower() for condition in entities.get('TRACK_CONDITION', []))), RaceStatusFact(lap=MATCH.lap) ) def weather_information_adjustment(self, entities, lap):
Generated Recommendation:
Action: prepare_rain_tires
Confidence: 0.9
Priority: 3 (High)
Explanation: Weather change detection with rain tire preparation strategy
Sources: scripts/IS_agent/N04_nlp_rules.ipynb 405-457
scripts/IS_agent/utils/N04_nlp_rules.py 77-99
Rule 3: Incident Reaction
This rule identifies safety car deployments or yellow flag situations and recommends strategic pit window evaluation.
Rule Conditions:
Entities containing 'safety' in INCIDENT categories or 'yellow' in SITUATION entities
Active RaceStatusFact for lap context
Rule Implementation:
@Rule( RadioFact(entities=MATCH.entities), TEST(lambda entities: any('safety' in incident.lower() for incident in entities.get('INCIDENT', [])) or any('yellow' in situation.lower() for situation in entities.get('SITUATION', []))), RaceStatusFact(lap=MATCH.lap) ) def incident_reaction(self, entities, lap):
Generated Recommendation:
Action: reevaluate_pit_window
Confidence: 0.85
Priority: 3 (High)
Explanation: Race incident detection with strategic pit opportunity identification
Sources: scripts/IS_agent/N04_nlp_rules.ipynb 459-512
scripts/IS_agent/utils/N04_nlp_rules.py 101-125
Data Transformation Pipeline
NLP Analysis to RadioFact Conversion
RadioFact Fields
JSON Structure
NLP JSON Output
transform_radio_analysis()
message: string
analysis.sentiment: string
analysis.intent: string
analysis.entities: dict
RadioFact Object
sentiment
intent
entities
message
timestamp
NLP to RadioFact Transformation
Entity Categories and Strategic Mapping
Entity Category Strategic Relevance Triggering Rules
TECHNICAL_ISSUE Tire/car problems Grip Issue Response
WEATHER Weather changes Weather Information Adjustment
TRACK_CONDITION Track surface changes Weather Information Adjustment
INCIDENT Safety car situations Incident Reaction
SITUATION Race status changes Incident Reaction
PIT_CALL Pit strategy context All rules (contextual)
Sources: scripts/IS_agent/N04_nlp_rules.ipynb 240-266
scripts/IS_agent/utils/N01_agent_setup.py 1-10
Rule Testing and Validation
Test Framework
The system includes comprehensive testing capabilities through the test_radio_rules() function, which processes real radio messages and validates rule activation.
Test Scenarios:
Scenario Message Example Expected Rule Recommendation Action
Grip Issues "I'm struggling with grip, rear feels terrible" grip_issue_response prioritize_pit
Weather Change "Rain starting at turn 4, track getting wet" weather_information_adjustment prepare_rain_tires
Safety Car "Safety car deployed, box box box" incident_reaction reevaluate_pit_window
Testing Results:
Total Rules Tested: 3
Rules Successfully Triggered: 3/3 (100%) All test scenarios generate appropriate strategic recommendations
Sources: scripts/IS_agent/N04_nlp_rules.ipynb 533-630
scripts/IS_agent/N04_nlp_rules.ipynb 877-888
Integration Points
Expert System Integration
The Radio Message Rules integrate with the broader expert system through:
Fact Sharing: RadioFact objects work alongside TelemetryFact, DegradationFact, and RaceStatusFact
Recommendation Synthesis: Generated StrategyRecommendation objects merge with recommendations from other rule engines
Conflict Resolution: Priority levels coordinate with other strategic recommendations
NLP Pipeline Dependencies
The system requires:
NLP_radio_processing.NLP_utils.N06_model_merging module for radio analysis process_radio_message() function for message processing transform_radio_analysis() function for fact conversion
Sources: scripts/IS_agent/utils/N04_nlp_rules.py 31-34
scripts/IS_agent/N04_nlp_rules.ipynb 82-85
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.
📝 This documentation is automatically generated using browser automation.
🕒 Last updated: $(date '+%Y-%m-%d %H:%M:%S UTC')