## AI Master Prompt: Kalman Filter Visualizer & Learning Platform
**1. PROJECT OVERVIEW:**
This project aims to create a single-page web application (SPA) that demystifies the Kalman Filter for a broad audience, including students, engineers, and data scientists. The core problem addressed is the common difficulty in understanding the Kalman Filter due to overly complex mathematical explanations and a lack of intuitive, real-world examples. Our application will provide an interactive, visual, and simplified learning experience. The primary value proposition is to make the Kalman Filter accessible and practically applicable by offering hands-on simulations, clear explanations, and a focus on intuition over dense mathematics. It will serve as both an educational tool and a sandbox for experimenting with the filter's behavior under various conditions.
**2. TECH STACK:**
- **Frontend Framework:** React (using Vite for fast development setup)
- **Styling:** Tailwind CSS (for rapid UI development and utility-first styling)
- **State Management:** Zustand (lightweight and efficient for managing global and local state)
- **Charting/Visualization:** Chart.js (for plotting simulation data and filter states)
- **Animation Libraries:** Framer Motion (for smooth UI transitions and interactive elements)
- **Math/Utility:** Lodash (for general utility functions)
**3. CORE FEATURES:**
**a. Interactive Radar Simulation:**
* **User Flow:**
1. User selects a predefined scenario (e.g., 'Constant Velocity Target', 'Accelerating Target', 'Maneuvering Target').
2. User can adjust key parameters: initial state (position, velocity), process noise covariance (Q), measurement noise covariance (R), simulation duration, and target maneuver frequency/magnitude.
3. User clicks 'Run Simulation'.
4. The application simulates the true target trajectory and noisy measurements.
5. The Kalman Filter algorithm runs in real-time (or step-by-step) to estimate the target's state.
6. The simulation visuals update dynamically: showing the true path, noisy measurements, and the filter's estimated path.
7. Post-simulation analysis: Displaying metrics like Root Mean Square Error (RMSE) of the estimate, tracking success/failure indicators.
* **Details:** The simulation should visually represent a 2D radar screen. The target's true path, the noisy measurements (often shown as crosses or dots), and the Kalman filter's estimated path (a smoothed line) are plotted. Uncertainty ellipses can optionally be visualized to show the filter's confidence.
**b. Simplified Kalman Filter Explanation:**
* **User Flow:**
1. User navigates to the 'Learn' section.
2. Content is presented in digestible modules: Introduction, State Estimation, Prediction Step, Update Step, Noise & Covariance, Example Walkthrough.
3. Each module uses analogies, simple language, and minimal equations. Key equations are highlighted and explained contextually within the simulation.
4. Interactive elements within the explanation: Hovering over terms reveals definitions; clicking buttons shows intermediate calculation steps for a simple example.
* **Details:** Focus on the intuition behind the prediction (where do we think it will be?) and update (how do we correct our guess with new measurements?) steps. Use analogies like guessing a friend's location based on past knowledge and then adjusting the guess when you hear a sound from their direction.
**c. Scenario Library & Parameter Tuning:**
* **User Flow:**
1. User accesses the 'Scenarios' page.
2. A list of pre-built scenarios is displayed with difficulty ratings.
3. User selects a scenario, which loads the default parameters into the simulation interface.
4. User modifies parameters (Q, R, initial state, etc.) and observes the impact on the filter's performance via the simulation and RMSE metrics.
* **Details:** Include scenarios demonstrating filter divergence (e.g., incorrect Q/R tuning), convergence speed, and tracking of different motion models.
**d. Results & Analysis Dashboard:**
* **User Flow:**
1. After running a simulation, the user is presented with a summary screen.
2. Key charts are displayed: True Path vs. Estimated Path, Measurement vs. Estimated State, Error over Time.
3. Quantitative metrics are shown: Final RMSE, Average RMSE, Maximum Error, Number of Missed Detections (if applicable).
4. Option to download simulation data (e.g., as CSV).
* **Details:** Charts should be interactive, allowing zooming and panning. Clear labels and legends are crucial.
**4. UI/UX DESIGN:**
- **Layout:** A clean, modern, single-page application layout. A primary navigation sidebar (or top bar) for 'Learn', 'Simulate', 'Scenarios', 'Docs'. The main content area dynamically changes based on the selected section.
- **Simulation View:** A prominent canvas area for the visual simulation. Control panels for parameters are clearly organized to the side or below the canvas. Real-time updates are smooth and non-blocking.
- **Learning View:** Text-heavy content broken down into readable sections with clear headings, subheadings, and interspersed visuals/interactive elements. Code blocks are well-formatted and syntax-highlighted.
- **Color Palette:** A professional and calm palette. Primary: A deep blue or dark grey for backgrounds. Secondary: A vibrant accent color (e.g., electric blue, teal, or orange) for interactive elements, highlights, and data series. Neutral tones (light greys, whites) for text and cards. Ensure high contrast for readability.
- **Typography:** Use a clean, sans-serif font family (e.g., Inter, Poppins, or Roboto) for optimal readability on screens. Maintain a clear typographic hierarchy (H1, H2, body text, captions).
- **Responsive Design:** Mobile-first approach. The layout must adapt gracefully to different screen sizes. On smaller screens, controls might collapse into drawers or accordions. Charting libraries should be responsive. Ensure touch-friendly interactions.
- **Interactions:** Subtle animations on button clicks, form submissions, and route transitions. Loading indicators (spinners, skeleton screens) for asynchronous operations. Hover effects on interactive elements.
**5. DATA MODEL:**
- **State Management (Zustand Store):**
```javascript
// Simulation State
simulationState: {
scenario: 'Constant Velocity Target' | 'Accelerating Target' | ...,
parameters: { /* Q, R, initial state, duration, etc. */ },
isSimulating: boolean,
step: number,
trueTrajectory: Array<{x, y, vx, vy}>,
measurements: Array<{x, y}>,
estimatedStates: Array<{x, y, vx, vy}>,
uncertaintyEllipses: Array<{x, y, radius}>, // Optional
rmseHistory: Array<{step, rmse}>,
status: 'idle' | 'running' | 'finished' | 'error'
}
// Learning State
learningState: {
currentModule: string,
completedModules: string[]
}
// UI State
uiState: {
sidebarOpen: boolean,
activeTab: string
}
```
- **Mock Data Format (for Scenarios & Simulation Results):**
```json
// Scenario Configuration
{
"id": "constant_velocity_1",
"name": "Constant Velocity Target",
"description": "A target moving at a steady speed and direction.",
"difficulty": "Easy",
"defaultParameters": {
"initialState": {"x": 50, "y": 50, "vx": 10, "vy": 5},
"Q": {"val": 0.1}, // Simplified scalar for demonstration
"R": {"val": 5}, // Simplified scalar for demonstration
"duration": 100,
"dt": 1.0
}
}
// Simulation Step Data
{
"step": 10,
"trueState": {"x": 150.5, "y": 102.1, "vx": 10, "vy": 5},
"measurement": {"x": 155.2, "y": 100.8},
"estimatedState": {"x": 148.9, "y": 103.5, "vx": 9.8, "vy": 5.1},
"covariance": {"xx": 1.2, "yy": 1.1, "xy": -0.1}, // Example covariance matrix elements
"rmse": 2.5
}
```
**6. COMPONENT BREAKDOWN:**
- **`App.js`**: Main application component. Sets up routing (using React Router), global layout, and initializes the Zustand store.
- **`Navigation.js`**: Sidebar or top navigation menu. Contains links to different sections. Manages `uiState.sidebarOpen` and `uiState.activeTab`.
- **`LearnPage.js`**: Displays educational content. Fetches module data. Contains `ModuleViewer.js`.
- **`ModuleViewer.js`**: Renders a specific learning module. Handles interactive elements and explanations.
- **`ConceptCard.js`**: Reusable component for displaying definitions or key concepts.
- **`EquationDisplay.js`**: Renders mathematical equations using a library like MathJax or KaTeX, with explanations.
- **`SimulatePage.js`**: Main simulation interface. Contains `SimulationCanvas.js`, `ParameterControls.js`, and `ResultsDisplay.js`.
- **`SimulationCanvas.js`**: Renders the 2D simulation using Chart.js or a canvas API. Updates dynamically based on `simulationState`.
- **`Target.js`**: Component/logic for drawing the target (true path, estimated path, measurement points).
- **`AxisLabels.js`**: Displays coordinate axes and labels.
- **`ParameterControls.js`**: Form component for adjusting Q, R, initial state, duration, etc. Updates `simulationState.parameters`. Uses input components like `NumberInput.js`.
- **`NumberInput.js`**: Generic input field for numbers with labels and potentially increment/decrement buttons.
- **`SimulationControls.js`**: Buttons for 'Run', 'Pause', 'Step', 'Reset'. Manages `simulationState.isSimulating`, `simulationState.step`, `simulationState.status`.
- **`ResultsDisplay.js`**: Shows post-simulation metrics and charts. Uses `ChartComponent.js`.
- **`ChartComponent.js`**: Wrapper for Chart.js to render various plots (trajectory, error, covariance).
- **`ScenariosPage.js`**: Lists available scenarios. Allows selection and loading into the simulation.
- **`ScenarioCard.js`**: Displays a single scenario's name, description, and difficulty. Handles selection.
- **`Footer.js`**: Contains copyright information and links.
- **`LoadingSpinner.js`**: Displays a loading animation.
- **`ErrorMessage.js`**: Displays error messages to the user.
**7. ANIMATIONS & INTERACTIONS:**
- **Transitions:** Smooth fades and slides for page transitions (using Framer Motion). Subtle scale/color changes on hover for buttons and interactive elements.
- **Simulation Updates:** Smooth animation of the target moving across the canvas. Measurements appearing dynamically. Estimated state line drawing smoothly.
- **Loading States:** Use `LoadingSpinner.js` when fetching data or running intensive simulations. Skeleton screens can be used for content loading.
- **Micro-interactions:** Button click feedback (slight scale change). Input field focus highlights. Successful action confirmations (e.g., a subtle checkmark animation).
- **Uncertainty Ellipses (Optional):** If implemented, these should animate smoothly as they change size and orientation based on the covariance matrix.
**8. EDGE CASES:**
- **Empty States:** The simulation canvas should display a placeholder message when no simulation has run. The 'Learn' section should handle cases where content fails to load.
- **Error Handling:** Network errors during data fetching. Simulation runtime errors (e.g., division by zero in calculations). Display clear, user-friendly error messages using `ErrorMessage.js`. Log errors to the console for debugging.
- **Validation:** Input parameters in `ParameterControls.js` must be validated (e.g., R and Q should generally be positive, duration must be a positive integer). Provide inline validation feedback.
- **Accessibility (a11y):** Use semantic HTML5 elements. Ensure sufficient color contrast. All interactive elements should be keyboard navigable and have appropriate ARIA attributes. Chart data should be accessible (e.g., via tooltips or a data table).
- **Performance:** Optimize simulation rendering. Consider using `requestAnimationFrame` for smooth animations. Debounce or throttle intensive operations if necessary. Ensure efficient state updates with Zustand.
- **Algorithm Edge Cases:** Handle scenarios where the filter might diverge (e.g., due to very high noise or incorrect model assumptions). Provide warnings or visual cues.
**9. SAMPLE DATA:**
```json
// Sample Scenarios (as shown in Data Model)
[
{
"id": "constant_velocity_1",
"name": "Constant Velocity Target",
"description": "A target moving at a steady speed and direction.",
"difficulty": "Easy",
"defaultParameters": {"initialState": {"x": 50, "y": 50, "vx": 10, "vy": 5}, "Q": {"val": 0.1}, "R": {"val": 5}, "duration": 100, "dt": 1.0}
},
{
"id": "accelerating_target_1",
"name": "Simple Accelerating Target",
"description": "Target accelerates in a straight line.",
"difficulty": "Medium",
"defaultParameters": {"initialState": {"x": 0, "y": 0, "vx": 5, "vy": 5}, "Q": {"val": 0.5}, "R": {"val": 10}, "duration": 100, "dt": 1.0}
},
{
"id": "maneuvering_target_1",
"name": "Sudden Turn Target",
"description": "Target moves with constant velocity then makes a sharp turn.",
"difficulty": "Hard",
"defaultParameters": {"initialState": {"x": 100, "y": 100, "vx": -10, "vy": 0}, "Q": {"val": 2.0}, "R": {"val": 15}, "duration": 100, "dt": 1.0}
}
]
// Sample Simulation Results (first few steps for 'constant_velocity_1')
[
{"step": 0, "trueState": {"x": 50, "y": 50, "vx": 10, "vy": 5}, "measurement": {"x": 52.1, "y": 48.5}, "estimatedState": {"x": 50.1, "y": 49.5, "vx": 10.1, "vy": 4.9}, "rmse": 2.3},
{"step": 1, "trueState": {"x": 60, "y": 55, "vx": 10, "vy": 5}, "measurement": {"x": 58.3, "y": 56.2}, "estimatedState": {"x": 60.5, "y": 55.2, "vx": 9.9, "vy": 5.0}, "rmse": 1.8},
{"step": 2, "trueState": {"x": 70, "y": 60, "vx": 10, "vy": 5}, "measurement": {"x": 71.5, "y": 61.0}, "estimatedState": {"x": 70.2, "y": 60.1, "vx": 10.0, "vy": 5.1}, "rmse": 1.5}
// ... more steps
]
```
**10. DEPLOYMENT NOTES:**
- **Build Tool:** Vite is recommended for its speed. Run `npm run build` (or `yarn build`) to generate optimized static assets.
- **Environment Variables:** Use `.env` files for configuration (e.g., API endpoints if any are added later, though not needed for MVP). Vite uses `VITE_` prefix for environment variables exposed to the client.
- **Hosting:** Deploy the static build to any modern static hosting provider (e.g., Vercel, Netlify, GitHub Pages, AWS S3/CloudFront).
- **Performance Optimizations:** Code splitting (Vite handles this well). Lazy loading components, especially the `SimulationCanvas` and potentially heavy charting components. Memoization (React.memo, useMemo, Zustand selectors) to prevent unnecessary re-renders.
- **HTTPS:** Ensure the hosting environment serves the application over HTTPS.
- **Error Reporting:** Integrate a client-side error reporting service (e.g., Sentry, LogRocket) for production builds to capture and diagnose issues.