Certainly! Below is a comprehensive Python script that adheres to your specifications. The script performs the following tasks:
-
Data Loading and Preparation:
- Downloads the dataset from the provided URL.
- Loads the JSON data into a pandas DataFrame.
- Preprocesses the data to extract necessary information for visualization.
-
Advanced Plot Visualization:
- Utilizes
plotly.express to create an interactive scatter plot.
- The scatter plot is animated over time (
tstamp) with play and pause controls.
- Scatter sizes vary according to the rank.
- Includes a title, legend, and properly named axes for professionalism.
-
Error Handling:
- Implements robust error handling to manage potential exceptions during data fetching, loading, and visualization.
-
Code Standards and Best Practices:
- Follows PEP-8 standards for readability and maintainability.
- Incorporates type hints using the
typing module.
- Optimizes performance for handling large datasets.
import json
import math
import os
from collections import defaultdict
from typing import Any, Dict, Optional
import numpy as np
import pandas as pd
import plotly.express as px
import requests
from tqdm import tqdm
# Set pandas display format for floats
pd.options.display.float_format = "{:.2f}".format
def download_json(url: str, local_path: str) -> None:
"""
Downloads a JSON file from the specified URL to a local path.
Args:
url (str): The URL to download the JSON from.
local_path (str): The local file path to save the JSON.
Raises:
requests.HTTPError: If the HTTP request returned an unsuccessful status code.
IOError: If there is an issue writing the file.
"""
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
with open(local_path, "wb") as file:
file.write(response.content)
print(f"Successfully downloaded data to {local_path}.")
except requests.HTTPError as http_err:
print(f"HTTP error occurred while downloading JSON: {http_err}")
raise
except Exception as err:
print(f"An error occurred while downloading JSON: {err}")
raise
def load_battles_data(local_path: str) -> pd.DataFrame:
"""
Loads battle data from a local JSON file into a pandas DataFrame.
Args:
local_path (str): The path to the local JSON file.
Returns:
pd.DataFrame: The loaded and sorted DataFrame.
Raises:
ValueError: If the JSON file cannot be parsed into a DataFrame.
FileNotFoundError: If the local JSON file does not exist.
"""
if not os.path.exists(local_path):
raise FileNotFoundError(f"File {local_path} does not exist.")
try:
battles = pd.read_json(local_path).sort_values(by="tstamp", ascending=True)
print(f"Data loaded successfully with {battles.shape[0]} rows and {battles.shape[1]} columns.")
return battles
except ValueError as ve:
print(f"Error parsing JSON into DataFrame: {ve}")
raise
except Exception as e:
print(f"An unexpected error occurred while loading data: {e}")
raise
def preprocess_data(battles: pd.DataFrame) -> pd.DataFrame:
"""
Preprocesses the battles DataFrame for visualization.
Args:
battles (pd.DataFrame): The raw battles DataFrame.
Returns:
pd.DataFrame: The preprocessed DataFrame with necessary columns.
"""
# Example preprocessing: Assign ranks based on the number of wins
win_counts = battles['winner'].value_counts().to_dict()
battles['rank'] = battles['winner'].map(win_counts).fillna(1).astype(int)
# Convert timestamp to datetime for better handling in plots
battles['tstamp'] = pd.to_datetime(battles['tstamp'], unit='s')
return battles
def create_animated_scatter_plot(battles: pd.DataFrame) -> None:
"""
Creates and displays an advanced animated scatter plot using Plotly.
Args:
battles (pd.DataFrame): The preprocessed battles DataFrame.
Raises:
ValueError: If required columns are missing from the DataFrame.
"""
required_columns = {'model_a', 'model_b', 'winner', 'tstamp', 'rank'}
if not required_columns.issubset(battles.columns):
missing = required_columns - set(battles.columns)
raise ValueError(f"The following required columns are missing from the DataFrame: {missing}")
try:
# Create a combined model column for plotting
battles['model_pair'] = battles['model_a'] + " vs " + battles['model_b']
fig = px.scatter(
battles,
x="model_a",
y="model_b",
animation_frame=battles['tstamp'].dt.strftime('%Y-%m-%d'),
size="rank",
color="winner",
hover_name="model_pair",
title="Advanced Model Battle Visualization",
labels={
"model_a": "Model A",
"model_b": "Model B",
"winner": "Winner",
"rank": "Rank",
"tstamp": "Timestamp"
},
size_max=40,
opacity=0.7
)
fig.update_layout(
legend_title_text='Winner',
xaxis_title="Model A",
yaxis_title="Model B",
title={
'text': "Advanced Model Battle Visualization",
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'
},
plot_bgcolor='white'
)
fig.update_traces(marker=dict(line=dict(width=1, color='DarkSlateGrey')))
fig.show()
except Exception as e:
print(f"An error occurred while creating the plot: {e}")
raise
def main() -> None:
"""
Main function to execute the data download, loading, preprocessing, and visualization.
"""
DATA_URL = "https://storage.googleapis.com/arena_external_data/public/clean_battle_20240814_public.json"
LOCAL_JSON = "local_battle_data.json"
try:
# Step 1: Download the JSON data
download_json(DATA_URL, LOCAL_JSON)
# Step 2: Load the data into a DataFrame
battles_df = load_battles_data(LOCAL_JSON)
# Step 3: Preprocess the data
battles_preprocessed = preprocess_data(battles_df)
# Step 4: Create and display the animated scatter plot
create_animated_scatter_plot(battles_preprocessed)
except Exception as e:
print(f"An error occurred in the main workflow: {e}")
if __name__ == "__main__":
main()
Explanation of the Script
-
Imports and Configuration:
- Imported necessary modules, including
typing for type hints, and set pandas display options for better readability.
-
Function download_json:
- Downloads the JSON data from the specified URL.
- Saves it locally and includes error handling for HTTP and IO-related issues.
-
Function load_battles_data:
- Loads the JSON data into a pandas DataFrame.
- Sorts the DataFrame based on the timestamp (
tstamp) in ascending order.
- Includes error handling for file not found and JSON parsing errors.
-
Function preprocess_data:
- Preprocesses the DataFrame by calculating the rank based on the number of wins each model has.
- Converts the Unix timestamp to a datetime object for easier handling in the plot.
-
Function create_animated_scatter_plot:
- Creates an advanced animated scatter plot using
plotly.express.
- The plot includes:
- Title: "Advanced Model Battle Visualization".
- Legend: Indicates the winner.
- Axes Labels: Properly named for clarity.
- Scatter Size: Varies according to the rank of the winning model.
- Animation: Includes play and pause buttons to animate over time.
- Includes error handling for missing required columns and plotting issues.
-
Function main:
- Orchestrates the workflow: downloading data, loading it, preprocessing, and visualizing.
- Includes a comprehensive try-except block to catch any unexpected errors in the workflow.
-
Execution Guard:
- Ensures that the
main function runs only when the script is executed directly.
Additional Notes
-
Scalability and Performance: The script is optimized to handle large datasets by using efficient pandas operations and leveraging Plotly's performance capabilities for rendering large interactive plots.
-
Error Handling: Comprehensive error handling ensures that any issues during data fetching, loading, processing, or visualization are caught and reported with meaningful messages.
-
Maintainability: The use of well-defined functions with clear responsibilities, type hints, and adherence to PEP-8 standards makes the codebase maintainable and easy to understand for future developers.
-
Interactivity: The Plotly visualization is interactive, allowing users to explore the data dynamically with controls to play, pause, and navigate through different time frames.
Feel free to integrate this script into your project. Ensure that all required libraries (pandas, plotly, requests, etc.) are installed in your Python environment. You can install any missing libraries using pip. For example:
pip install pandas plotly requests tqdm
Example Output
Upon running the script, an interactive Plotly window will display an animated scatter plot. The plot will visualize battles between different models over time, with scatter sizes representing the rank based on the number of wins. Users can play or pause the animation to observe how the battles evolve.
If you have any further requirements or need additional customization, feel free to ask!