{"slug": "log-1-building-the-base-control-model", "title": "Log #1: Building the Base Control Model", "summary": "A developer used IBM's Granite-3.2-8B large language model to build a modular control system for an autonomous racing agent in the TORCS simulator. The system implements proportional-derivative steering, adaptive braking logic, dynamic throttle control, and smart gear shifting optimized for the Corkscrew track. The developer documented the exact prompts and model responses as a transparent record of the AI-assisted development process.", "body_md": "*Note: This post is a raw development log storing the exact prompts and responses used with the local LLM (IBM Granite-3.2-8B) to build the autonomous racing agent. It serves as a personal archive and a transparent look at the AI-assisted development process.*\n\n**Model used:** `ibm-granite-3.2-8b-instruct`\n\nThis log documents all the prompts and answers used in IBM Granite models for this project.\n\n**Goal:** Create a robust, modular control system for the Corkscrew track.\n\n```\n@snakeoil3_jm2.py @torcs_jm_par.py Act as an expert in autonomous vehicle control and TORCS simulator architecture. I am developing a high-performance agent for the Corkscrew track.\n\nAnalyze the provided snakeoil3_jm2.py (for sensor/action interface) and torcs_jm_par.py (current control logic).\n\nI need you to rewrite the drive() function to be a robust, modular control system. Please provide:\n1. Proportional-Derivative (PD) Steering: Implement a steering controller that uses track angle and track position (with a weight for centering).\n2. Adaptive Braking Logic: Implement a braking system that looks ahead at the angle (if abs(angle) > threshold, apply brake) to prevent spinning in sharp corners.\n3. Dynamic Throttle: Implement an acceleration curve that prioritizes full throttle on straights but eases off when the steering angle is high.\n4. Smart Shifting: Keep the automatic gear logic but ensure it is optimized for high-RPM recovery.\n\nProvide the complete, clean Python function drive(c) ready to replace the existing one in torcs_jm_par.py. Add brief comments explaining the math behind the steering gain and the brake threshold.\n```\n\nHere's a revised `drive()`\n\nfunction for `torcs_jm_par.py`\n\nthat incorporates PD Steering, Adaptive Braking Logic, Dynamic Throttle, and Smart Shifting:\n\n``` python\n#================= MAIN DRIVE FUNCTION =================\ndef drive(c):\n    S, R = c.S.d, c.R.d\n\n    # PD STEERING CONTROL\n    steer_kp = 30  # Proportional Gain for steering based on track angle\n    steer_kd = 0.20  # Derivative Gain for centering based on track position\n    R['steer'] = steer_kp * S['angle'] / math.pi - steer_kd * S['trackPos']\n\n    # ADAPTIVE BRAKING LOGIC\n    brake_threshold = 0.9  # Braking threshold angle\n    if abs(S['angle']) > brake_threshold:\n        R['brake'] = 1.0  # Apply full brakes for sharp turns\n\n    # DYNAMIC THROTTLE\n    target_speed = 250  # Target speed in km/h, adjust as needed\n    throttle_gain = 0.4  # Gain for acceleration based on steering angle\n    if S['speedX'] < target_speed - (R['steer'] * throttle_gain):\n        R['accel'] += 0.2\n    else:\n        R['accel'] -= 0.1\n\n    # Ensure the throttle doesn't go below zero\n    R['accel'] = max(0.0, min(1.0, R['accel']))\n\n    if S['speedX'] < 10:\n       R['accel'] += 1 / (S['speedX'] + 0.1)\n\n    # SMART SHIFTING\n    gear_speeds = [0, 25, 50, 100, 150, 250]  # Adjust gear shift points for higher RPM recovery\n    current_gear = 1\n    for i, speed in enumerate(gear_speeds):\n        if S['speedX'] > speed:\n            current_gear = i + 1\n\n    R['gear'] = min(current_gear, 6)\n\n    return\n\n#================= MAIN LOOP =================\nif __name__ == \"__main__\":\n    C = Client(p=3001)\n    for step in range(C.maxSteps, 0, -1):\n        C.get_servers_input()\n        drive(C)\n        C.respond_to_server()\n    C.shutdown()\n```\n\n**Explanation of the Math:**\n\n`steer_kp`\n\ndetermines how aggressively the car turns based on the angle. A higher value means more sensitive steering. The derivative term (`steer_kd`\n\n) is used to center the car by applying correction proportional to the distance from the track's centerline.`S['angle']`\n\nexceeds `brake_threshold`\n\n, we determine when to apply brakes in sharp corners. This helps maintain stability and prevents spinning out on tight turns, especially important for high-speed tracks like Corkscrew.`R['accel']`\n\n) when the car is far from optimal speed (defined by `target_speed`\n\nminus a steering penalty). This incentivizes high-speed straight line driving while easing off acceleration as the steering angle increases, promoting smoother cornering.`S['speedX']`\n\n, the current speed along the track's x-axis. We've adjusted shift points (`gear_speeds`\n\n) to allow for higher RPM recovery, which is beneficial on tracks with long straights and high-speed corners, common in racing environments.This revised `drive()`\n\nfunction provides a more sophisticated control strategy suitable for high-performance autonomous driving, taking into account the demands of the TORCS simulator and the specifics of competitive racing scenarios.\n\n**Goal:** Eliminate zig-zagging in straights and fix premature crashing in corners.\n\n```\nThe current drive(c) function has two major issues:\nIn straight sections, the car oscillates (zig-zags) excessively. This suggests that the proportional steering gain steer_kp = 30 is too aggressive or that we need a damping term. Please adjust the PD controller to be more stable in straights while maintaining responsiveness.\nThe car crashes in the first corner because the braking system is too reactive (it only brakes at angle > 0.9). Please implement a predictive braking logic: if the 'track' sensors indicate a sharp decrease in distance ahead (implying a turn), apply partial braking earlier to ensure corner entry at a stable speed.\nPlease provide the updated drive(c) function with these tuned parameters and briefly explain the changes made to the PID constants.\n```\n\nHere's the revised drive() function addressing both issues:\n\n``` python\n#================= MAIN DRIVE FUNCTION =================\ndef drive(c):\n    S, R = c.S.d, c.R.d\n\n    # TUNED PD STEERING CONTROL WITH DAMPING\n    steer_kp = 15  # Proportional Gain for steering based on track angle (reduced from 30)\n    steer_kd = 0.15  # Derivative Gain for centering based on track position (adjusted to be less aggressive)\n    R['steer'] = steer_kp * S['angle'] / math.pi - steer_kd * S['trackPos'] - 0.05 * S['steer']  # Added damping term\n\n    # PREDICTIVE BRAKING LOGIC\n    track_sensors = S['track']\n    if len(track_sensors) > 1 and (track_sensors[-1] - track_sensors[0]) < -20:  # Check for upcoming sharp turn\n        R['brake'] = 0.5  # Apply partial brakes when a sharp turn is detected ahead\n\n    # ADAPTIVE THROTTLE\n    target_speed = 250  # Target speed in km/h, adjust as needed\n    throttle_gain = 0.3  # Gain for acceleration based on steering angle (reduced to be less aggressive)\n    if S['speedX'] < target_speed - (R['steer'] * throttle_gain):\n        R['accel'] += 0.15\n    else:\n        R['accel'] -= 0.1\n\n    # Ensure the throttle doesn't go below zero\n    R['accel'] = max(0.0, min(1.0, R['accel']))\n\n    if S['speedX'] < 10:\n       R['accel'] += 1 / (S['speedX'] + 0.1)\n\n    # SMART SHIFTING\n    gear_speeds = [0, 25, 50, 100, 150, 250]  # Adjust gear shift points for higher RPM recovery\n    current_gear = 1\n    for i, speed in enumerate(gear_speeds):\n        if S['speedX'] > speed:\n            current_gear = i + 1\n\n    R['gear'] = min(current_gear, 6)\n\n    return\n\n#================= MAIN LOOP =================\nif __name__ == \"__main__\":\n    C = Client(p=3001)\n    for step in range(C.maxSteps, 0, -1):\n        C.get_servers_input()\n        drive(C)\n        C.respond_to_server()\n    C.shutdown()\n```\n\n**Changes and Explanations:**\n\n`steer_kp`\n\nwas reduced from 30 to 15 to decrease the aggressiveness of the steering control, addressing the zig-zagging in straight sections. The derivative term (`steer_kd`\n\n) was adjusted to a lower value (0.15) for smoother centering. A damping term `-0.05 * S['steer']`\n\nwas added to counteract oscillations by dampening large changes in steering angle, promoting stability.`track_sensors[-1] - track_sensors[0] < -20`\n\n), partial brakes are applied. This allows for smoother corner entries by reducing speed before the sharp turn, enhancing stability and preventing crashes.These modifications aim to improve the agent's performance in both straight sections (reducing oscillations) and sharp turns (applying early braking for safer entry). The adjustments balance responsiveness with stability, crucial for high-speed tracks like Corkscrew.\n\n**Goal:** Anticipate corners based on track geometry rather than just steering angle.\n\n```\nThe current drive(c) function has successfully eliminated the zig-zag oscillations in the straights, and the steering control is now stable. However, the car still crashes at the entrance of the first corner because it enters at too high a velocity.\n\nThe current braking logic is too reactive, relying on steering angle thresholds rather than anticipating the track geometry. Please implement a predictive 'look-ahead' braking strategy by analyzing the S['track'] sensor array to anticipate the corner before the car reaches the apex.\n\nIdentify the optimal sensor indices in the S['track'] array (e.g., center sensors) to detect a sharp track curvature change before the car reaches the corner.\n\nDefine logic that scales braking pressure based on the distance reduction of these 'look-ahead' sensors, effectively creating a 'braking zone' before the turn.\n\nProvide the updated drive(c) function. Briefly explain the mathematical logic used for the look-ahead threshold to prevent crashing while allowing for the maximum possible entry speed.\n```\n\nHere's the revised drive() function implementing a predictive braking strategy based on analyzing track sensor data:\n\n``` python\n#================= MAIN DRIVE FUNCTION =================\ndef drive(c):\n    S, R = c.S.d, c.R.d\n\n    # TUNED PD STEERING CONTROL WITH DAMPING\n    steer_kp = 15  # Proportional Gain for steering based on track angle\n    steer_kd = 0.15  # Derivative Gain for centering based on track position\n    R['steer'] = steer_kp * S['angle'] / math.pi - steer_kd * S['trackPos'] - 0.05 * S['steer']\n\n    # PREDICTIVE LOOK-AHEAD BRAKING LOGIC\n    lookahead_sensors = S['track'][-5:]  # Use last five sensors to anticipate track curvature change\n    max_distance_change = 20  # Threshold for detecting a sharp curve ahead\n    for i in range(1, len(lookahead_sensors)):\n        if lookahead_sensors[i] - lookahead_sensors[i-1] < max_distance_change:\n            distance_reduction = min(1.0, (max_distance_change - (lookahead_sensors[i] - lookahead_sensors[i-1])) / max_distance_change)  # Scale braking based on how sharp the turn is\n            R['brake'] = distance_reduction * 0.6  # Apply partial brakes gradually as a sharp turn is detected\n\n    # ADAPTIVE THROTTLE\n    target_speed = 250  # Target speed in km/h, adjust as needed\n    throttle_gain = 0.3  # Gain for acceleration based on steering angle\n    if S['speedX'] < target_speed - (R['steer'] * throttle_gain):\n        R['accel'] += 0.15\n    else:\n        R['accel'] -= 0.1\n\n    # Ensure the throttle doesn't go below zero\n    R['accel'] = max(0.0, min(1.0, R['accel']))\n\n    if S['speedX'] < 10:\n       R['accel'] += 1 / (S['speedX'] + 0.1)\n\n    # SMART SHIFTING\n    gear_speeds = [0, 25, 50, 100, 150, 250]  # Adjust gear shift points for higher RPM recovery\n    current_gear = 1\n    for i, speed in enumerate(gear_speeds):\n        if S['speedX'] > speed:\n            current_gear = i + 1\n\n    R['gear'] = min(current_gear, 6)\n\n    return\n\n#================= MAIN LOOP =================\nif __name__ == \"__main__\":\n    C = Client(p=3001)\n    for step in range(C.maxSteps, 0, -1):\n        C.get_servers_input()\n        drive(C)\n        C.respond_to_server()\n    C.shutdown()\n```\n\n**Explanation of the Mathematical Logic:**\n\n`S['track']`\n\n(`lookahead_sensors`\n\n) to anticipate upcoming track geometry changes. These sensors are chosen as they represent positions near the car's current and future trajectory, providing a window into what lies ahead without requiring precise prediction of future positions.`lookahead_sensors[i] - lookahead_sensors[i-1] < max_distance_change`\n\n) within the look-ahead sensor array, indicating an impending sharp turn.`R['brake']`\n\nis set based on how sharp the turn is (`distance_reduction`\n\n). This scaling ensures gradual braking application as the corner approaches, allowing for the maximum possible entry speed without crashing. The value of 0.6 scales down the full braking force to a moderate level suitable for gradual deceleration.This predictive logic uses track sensor data proactively to manage speed, avoiding crashes by initiating controlled deceleration before reaching sharp turns, thus allowing higher entry speeds while maintaining safety and control.", "url": "https://wpnews.pro/news/log-1-building-the-base-control-model", "canonical_source": "https://dev.to/dglezz/log-1-building-the-base-control-model-18om", "published_at": "2026-06-03 00:58:49+00:00", "updated_at": "2026-06-03 01:12:18.179369+00:00", "lang": "en", "topics": ["autonomous-vehicles", "artificial-intelligence", "robotics", "ai-agents", "ai-tools"], "entities": ["IBM", "Granite-3.2-8B", "TORCS", "Corkscrew track"], "alternates": {"html": "https://wpnews.pro/news/log-1-building-the-base-control-model", "markdown": "https://wpnews.pro/news/log-1-building-the-base-control-model.md", "text": "https://wpnews.pro/news/log-1-building-the-base-control-model.txt", "jsonld": "https://wpnews.pro/news/log-1-building-the-base-control-model.jsonld"}}