fps-player-analysis-tool 1.0.0
A comprehensive analysis tool for FPS game demo files with advanced analytics, GPU acceleration, and real-time processing
License: MIT
Requires Python: >=3.8
Keywords: fps, gaming, analysis, machine-learning, data-science, counter-strike, esports, performance, analytics, visualization, streamlit, gpu, real-time, clustering, anomaly-detection

# FPS Player Analysis Tool

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

A comprehensive analysis tool for FPS game demo files (primarily Counter-Strike 2) that provides detailed insights into player performance, strategy, behavior, and team dynamics. This tool processes CSV data from FPS game demos and generates extensive analytics including combat metrics, movement patterns, strategic insights, and player clustering.

## 🚀 Features

### 📊 **Comprehensive Player Analysis**
- **Combat Analysis**: Kills, deaths, headshots, accuracy, ADR, trade effectiveness
- **Economy Analysis**: Money management, equipment values, buy patterns
- **Timing Analysis**: Early/mid/late round performance, kill timing
- **Weapon Analysis**: Usage patterns, weapon switches, time-based analysis
- **Teamwork Analysis**: Trade kills, clutch situations, team economy, round contributions
- **Style Analysis**: Utility usage, grenade patterns, position variability
- **Expedience Analysis**: Weapon type preferences, efficiency ratios
- **Score Analysis**: Composite performance scores, impact ratings, survival rates
- **Position Analysis**: Movement patterns, distance traveled, position heatmaps

### 🔄 **Batch Processing & Aggregation**
- Process multiple datasets simultaneously
- Aggregate player statistics across multiple games
- Generate comparison reports between players and teams
- Per-round, per-player, per-dataset detailed reporting

### 🎯 **Advanced Analytics**
- **Player Clustering**: Group players by playstyle and performance
- **Anomaly Detection**: Identify unusual player behavior patterns
- **Visualization**: Generate heatmaps, radar charts, and performance graphs
- **Real-time Data Collection**: Live game state integration

## 📦 Installation

### **Option A: Install as a Python Library** (recommended)

Install the package with pip. From the project root:

```bash
# Clone the repository
git clone <repository-url>
cd fps-player-analysis-tool

# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install the package in editable/development mode
pip install -e .
```

This installs the `fps-player-analysis-tool` package and makes the `fps-analyzer` and `fps-dashboard` commands available globally.

**Alternative: install from PyPI** (when published):
```bash
pip install fps-player-analysis-tool
```

### **Option B: Development Setup (no library install)**

1. **Clone the repository:**
```bash
git clone <repository-url>
cd project_name
```
2. **Create and activate virtual environment:**
```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# or 

conda create -n myenv python=3.9
```

3. **Install dependencies:**
```bash
pip install -r requirements.txt

# or

conda install --file requirements.txt
```

4. **Set up pre-commit hooks (optional):**
```bash
pre-commit install
```

## 📚 Using as a Python Library

After installing with `pip install -e .`, you can use the package programmatically or via the CLI.

### **Command-line tools**

```bash
# Analyze a single CSV file
fps-analyzer --single-file "G2-vs-Vitality-27052024-dust2.csv" --data-dir ./data

# Batch analyze all CSVs in a directory
fps-analyzer --data-dir "data/VtalityGames PT1" --output-dir analysis_results

# Launch the real-time dashboard
fps-dashboard
```

### **Programmatic usage**

```python
from analysis.new_comprehensive_analyzer import NewComprehensiveAnalyzer
from analysis.batch_analyzer import NewBatchAnalyzer

# Analyze a single demo file
analyzer = NewComprehensiveAnalyzer("path/to/demo.csv")
results = analyzer.analyze_all_players()

# Batch process multiple files
batch = NewBatchAnalyzer(data_dir="data/", output_dir="analysis_results")
results = batch.analyze_multiple_files(max_files=10, max_players=5)
```

## 🛠️ Usage

### **Quick Start - Single File Analysis**

Analyze a single CSV file with all players:
```bash
# If installed as library:
fps-analyzer --single-file "G2-vs-Vitality-27052024-dust2.csv" --data-dir ./data

# Or using the script directly:
python run_new_batch_analysis.py --single-file "G2-vs-Vitality-27052024-dust2.csv"
```

Analyze with player limit:
```bash
python run_new_batch_analysis.py --single-file "G2-vs-Vitality-27052024-dust2.csv" --max-players 5
```

### **Batch Analysis - Multiple Files**

Analyze all CSV files in a directory:
```bash
python analyze_all_new_datasets.py --data-dir "data/VtalityGames PT1"
```

Analyze with filters:
```bash
# Only specific maps
python analyze_all_new_datasets.py --maps dust2 mirage

# Only specific teams
python analyze_all_new_datasets.py --teams vitality g2

# Limit number of files (for testing)
python analyze_all_new_datasets.py --max-files 5

# Limit players per file
python analyze_all_new_datasets.py --max-players 10
```

### **Aggregated Player Analysis**

Generate aggregated statistics across all datasets:
```bash
python analyze_all_new_datasets.py --aggregate-players
```

### **Advanced Analytics**

**Player Clustering:**
```bash
python run_enhanced_clustering.py
```

**Anomaly Detection:**
```bash
python run_enhanced_anomaly_detection.py
```

**Feature Extraction:**
```bash
python extract_enhanced_features.py
```

### **Real-time Data Collection**

Start the game state server:
```bash
python src/scripts/run_server.py
```

Start the data collector:
```bash
python src/scripts/run_collector.py
```

## 📁 Output Structure

The tool generates comprehensive reports in the `analysis_results/` directory:

```
analysis_results/
├── individual_reports/          # Per-file analysis reports
│   ├── G2-vs-Vitality-27052024-dust2_analysis.json
│   └── ...
├── summary_reports/             # Batch analysis summaries
│   ├── batch_analysis_1234567890.json
│   └── summary_report_1234567890.txt
├── comparison_reports/          # Player/team comparisons
├── round_reports/              # Per-round detailed analysis
│   ├── player_76561197999825422_G2-vs-Vitality-27052024-dust2_round_reports.json
│   └── ...
├── player_aggregates/          # Cross-dataset player stats
│   ├── player_76561197999825422_aggregate.json
│   └── ...
└── visualizations/             # Generated charts and graphs
```

## 📊 Analysis Metrics

### **Combat Performance**
- **KDR (Kill/Death Ratio)**: Overall combat effectiveness
- **Headshot Percentage**: Aim precision
- **ADR (Average Damage per Round)**: Consistent impact
- **Trade Success Rate**: Team coordination
- **Reaction Time**: Speed of engagement

### **Economy Management**
- **Average Money per Round**: Financial efficiency
- **Equipment Value**: Investment patterns
- **Buy Round Consistency**: Strategic planning

### **Strategic Insights**
- **Round Timing**: Early/mid/late round performance
- **Utility Usage**: Flash, smoke, grenade efficiency
- **Position Variability**: Adaptability in positioning
- **Clutch Win Rate**: Pressure situation performance

### **Movement & Positioning**
- **Total Distance**: Activity level
- **Position Heatmaps**: Common areas and angles
- **Movement Speed**: Agility and positioning
- **Site Preferences**: Map control patterns

## 🔧 Configuration

### **Data Format Requirements**

The tool expects CSV files with the following structure:

**Required Columns:**
- `timestamp`: Frame timestamp
- `map_name`: Current map name
- `map_round`: Round number
- `round_phase`: Current round phase

**Player Columns (p0 through p9):**
- `pX_steamid`: Player Steam ID
- `pX_name`: Player name
- `pX_team`: Player team (CT/T)
- `pX_hp`: Player health
- `pX_armor`: Player armor
- `pX_kills`: Total kills
- `pX_deaths`: Total deaths
- `pX_pos_x/y/z`: Player position
- `pX_fwd_x/y/z`: Player view direction
- `pX_weapon_name`: Current weapon
- `pX_money`: Player money
- `pX_equip_value`: Equipment value

**Optional Enhanced Columns:**
- `pX_headshot_kills`: Headshot kills
- `pX_assists`: Assists
- `pX_shotsFired`: Shots fired
- `pX_total_hits`: Total hits
- `pX_utility_damage`: Utility damage
- `pX_round_damage`: Round damage
- `pX_enemies_flashed`: Enemies flashed

### **Analysis Parameters**

Key parameters can be adjusted in the analyzer:

```python
# Trade window for trade kill analysis (seconds)
trade_window_seconds = 7

# Clutch threshold (teammates alive to consider clutch)
clutch_threshold = 1

# Maximum reasonable kills per round
max_kills_per_round = 5

# Maximum reasonable damage per round
max_damage_per_round = 500
```

## 🎨 Visualization

The tool generates various visualizations:

- **Combat Radar Charts**: Multi-dimensional combat metrics
- **Position Heatmaps**: Player movement and death locations
- **Utility Usage Charts**: Grenade and utility patterns
- **Economy Comparisons**: Team and player economy analysis
- **Timing Analysis**: Round phase performance
- **Clustering Visualizations**: Player group analysis

## 🔍 Advanced Features

### **Per-Round Analysis**
Each player's performance is analyzed round-by-round, providing:
- Combat statistics per round
- Economy management per round
- Weapon usage patterns per round
- Teamwork metrics per round
- Style and expedience per round

### **Player Clustering**
Players are automatically grouped based on:
- Combat performance patterns
- Strategic preferences

## 🚀 GPU Acceleration

### **Server Deployment for GPU Processing**

For large-scale analysis, deploy to a GPU-enabled server:

#### **1. Server Requirements**
- **GPU**: NVIDIA GPU with 8GB+ VRAM (RTX 3080, A100, etc.)
- **RAM**: 32GB+ system memory
- **Storage**: SSD for fast data access
- **CUDA**: CUDA 11.x or 12.x toolkit

#### **2. Installation on Server**
```bash
# Clone the repository
git clone <repo_url>
cd project_name

# Create and activate virtual environment
python -m venv gpu_venv
source gpu_venv/bin/activate  # On Windows: venv\Scripts\activate

# Install GPU dependencies
pip install -r requirements_gpu.txt

# Verify GPU availability
python -c "import cupy as cp; print(f'GPU Memory: {cp.cuda.runtime.memGetInfo()[0] / 1e9:.1f}GB')"
```

#### **3. GPU-Accelerated Analysis**
```bash
# Process all files with GPU acceleration
python run_gpu_batch_analysis.py --data-dir data --output-dir gpu_results

# Optimize for your GPU
python run_gpu_batch_analysis.py --max-workers 4 --gpu-memory-limit 80%

# Monitor GPU usage
nvidia-smi -l 1
```

#### **4. Performance Benefits**
- **10-50x faster** DataFrame operations with cuDF
- **Parallel processing** of multiple files
- **GPU memory optimization** for large datasets
- **Automatic fallback** to CPU if GPU unavailable

#### **5. Memory Management**
```bash
# For large datasets, limit GPU memory usage
export CUDA_VISIBLE_DEVICES=0
export CUDA_MEMORY_FRACTION=0.8

# Process in batches
python run_gpu_batch_analysis.py --max-workers 2 --gpu-memory-limit 70%
```
- Movement styles
- Economy management
- Utility usage patterns

### **Anomaly Detection**
Identifies unusual player behavior using:
- Local Outlier Factor (LOF)
- Isolation Forest
- Performance deviation analysis
- Statistical outlier detection

## 🚨 Troubleshooting

### **Common Issues**

1. **"No files found"**: Check your data directory path and file patterns
2. **"Player not found"**: Verify Steam IDs are in the correct format
3. **"Memory error"**: Use `--max-files` or `--max-players` to limit processing
4. **"Column not found"**: Ensure your CSV has the required column structure

### **Performance Tips**

- Use `--max-files` for testing with large datasets
- Use `--max-players` to limit analysis scope
- Process files in smaller batches for memory-constrained systems
- Use `--dry-run` to preview what will be analyzed

## 📈 Example Output

### **Player Report Structure**
```json
{
  "player_info": {
    "steamid": "76561197999825422",
    "name": "nexa",
    "team": "TERRORIST",
    "total_rounds": 19,
    "total_frames": 167809
  },
  "combat_stats": {
    "total_kills": 13,
    "total_deaths": 15,
    "kdr": 0.87,
    "headshot_percentage": 46.2,
    "accuracy": 17.5,
    "adr": 69.2
  },
  "economy_stats": {
    "total_money": 8200,
    "avg_money_per_round": 432
  },
  "timing_analysis": {
    "early_kills": 0,
    "mid_kills": 2,
    "late_kills": 11,
    "avg_kills_per_round": 0.68
  }
}
```

## 🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests or create issues for bugs and feature requests.

### **Development Setup**
```bash
# Install development dependencies
pip install -r requirements.txt
pre-commit install

# Run tests
python -m pytest tests/

# Run linting
pre-commit run --all-files
```

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

The MIT License is a permissive license that allows others to:
- Use your code commercially
- Modify the code
- Distribute the code
- Use it privately
- Sublicense it

The only requirement is that the license and copyright notice be included in all copies or substantial portions of the software.

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

---

**For questions or support, please open an issue on GitHub.**