Python script to display a histogram of csTimer speedcube results

3 x 3 rubiks cube

Category :

,

Page Language Swicher

Introduction

I have created a Python script that displays a histogram of the speed cube results recorded by csTimer.

This blog regularly posts the results of Speed Cube (a game of aligning hexahedrons of different colors separated by 9 squares).I use the site csTimer to keep track of the disassembly procedure and the time it takes to complete the puzzle.

The csTimer site allows you to output the recorded results as a txt file (contents in JSON format).I try to back up to my PC after recording the daily cube alignment times in order to look back on past results and to be prepared for unintended deletion of data.

Since this backed-up data is raw data, we have not been able to utilize it very well.In cooperation with gemini, we have created a Python script that displays a histogram of speed cube solve times.

Environment in which the operation was checked

We have confirmed that the Python Script presented here works in the following environments

  • Windows11 Pro 24H2 : Build 26100.3037
  • WSL2 & WSLg : Ver.2.3.26.0
  • Ubuntu (WSL2) : 22.04.5 LTS
  • Python (Ubuntu) : Ver.3.10.12
  • python3-venv (Ubuntu) : 3.10.6
  • python3L-tk (Ubuntu) : 3.10.8
  • Japanese Font : IPAGothic
  • Simplified Chinese Font : Microsoft YaHei

Below is a description of how to create the operating environment and the scripts.

Create Windows11 WSL2 Ubuntu environment

First, create a WSL2 Ubuntu environment on Windows11.This time, we used Ubuntu 22.04 LTS environment since it was already available.

I will omit the method of creating a new WSL2 Ubuntu environment, as you will find various information on it when you search for it.For Japanese, please refer to the article in note.

Please confirm that Python works with WSL2 in this state.

Bash
$ python3 -V
Python 3.10.12
Bash

Install python3-venv and python3-tk for later use.If they are already installed, you will see the following

Bash
$ LANG=C sudo apt install python3-venv python3-tk
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3-tk is already the newest version (3.10.8-1~22.04).
python3-venv is already the newest version (3.10.6-1~22.04.1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Bash

Creating a Python Virtual Environment

When using Python, it is a good idea to create a virtual environment and work within it.You can work in a virtual environment without contaminating the original environment, and if you no longer need it, you can simply delete the entire directory.

This time, we will create a virtual environment with python3-venv and enter the virtual environment.

Bash
$ mkdir cstimer_histgram_en
$ cd cstimer_histgram_en
$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv) $
Bash

Install the necessary Python libraries with pip.

Bash
$ pip install pandas matplotlib
Bash

In the previous section, python3-tk was installed to display graphs drawn with matplotlib on the Windows11 side using WSLg.

Python Script to display a histogram of csTimer’s JSON

Save the following Python script in the appropriate directory.Name it cstimer_histgram_en.py.

Python
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import json
import argparse
import pytz
import datetime

def calculate_and_plot(session_data, session_name):
    """
    Calculates the average value and displays a histogram for the given session data.

    Args:
        session_data: The session data (list)
        session_name: The name of the session (string)
    """

    # If session_name is "properties", return without doing anything
    if session_name == "properties":
        return

    # Extract solve times
    tz = pytz.timezone('Asia/Tokyo')
    solve_times = []
    timestamps = []
    for item in session_data:
        if len(item) > 0 and isinstance(item[0], list) and len(item[0]) > 1:
            solve_time = item[0][1] / 1000
            timestamp = datetime.datetime.fromtimestamp(item[3], tz=tz)
        else:
            solve_time = None
            timestamp = None
            #print(f"Warning: Unexpected data format in session {session_name}, item: {item}")
        solve_times.append(solve_time)
        timestamps.append(timestamp)

    # Calculate the average value
    valid_solve_times = [t for t in solve_times if t is not None]
    if valid_solve_times:
        average_time = sum(valid_solve_times) / len(valid_solve_times)
        average_time = round(average_time,3)
        start_datetime = timestamps[0].strftime("%Y/%m/%d %H:%M")
        end_datetime = timestamps[-1].strftime("%Y/%m/%d %H:%M")
        print(f"{session_name} : Average Solve Time : {average_time} : Start Date and Time : {start_datetime} : End Date and Time : {end_datetime}")

        # Display the histogram
        plt.hist(valid_solve_times, bins=20)
        plt.title(f"Histogram of Solve Times for Session {session_name}")
        plt.xlabel("Solve Time")
        plt.ylabel("Frequency")
        plt.show()
        #plt.savefig(f"time_distribution_{session_name}.png")
        plt.clf()  # Clear the graph area
    else:
        print(f"No valid data exists for session {session_name}.")

# rcParams settings
plt.rcParams['font.family'] = 'IPAGothic'  # Font name to use
plt.rcParams['font.size'] = 16

# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("json_file", help="Path to the JSON file")
parser.add_argument("-s","--session_name", help="Session name to aggregate")
parser.add_argument("-a","--all", help="Execute for all sessions", action='store_true')
args = parser.parse_args()

# Load the JSON file
with open(args.json_file, 'r') as f:
    data = json.load(f)

# Execute processing for each session
if args.all == False:
    if args.session_name in data:  # Aggregate only the specified session if session is specified
        session_data = data[args.session_name]
        calculate_and_plot(session_data, args.session_name)
    else:
        print(f"Session: {args.session_name} not found.")

# Aggregate all sessions
if args.all:
    for session_name, session_data in data.items():
        calculate_and_plot(session_data, session_name)
cstimer_histgram_en.py

It is easy to start notepad.exe in the appropriate directory in WSL2.Create an empty file in WSL2 as follows, open the file with notepad.exe, copy, paste and save the above script.

Bash
(.venv) $ echo "" > cstimer_histgram_en.py
(.venv) $ notepad.exe cstimer_histgram_en.py
Bash

The reason for creating an empty file is to adapt the newline code to Linux.

Execution example

Prepare the txt file recorded by csTimer in the same directory as the Python script.

Run cstimer_histgram_en.py with ‘-h’ to see how to use it.

Bash
(.venv) $ python cstimer_histgram_en.py -h
usage: cstimer_histgram_en.py [-h] [-s SESSION_NAME] [-a] json_file

positional arguments:
  json_file             Path to the JSON file

options:
  -h, --help            show this help message and exit
  -s SESSION_NAME, --session_name SESSION_NAME
                        Session name to aggregate
  -a, --all             Execute for all sessions
Bash

This is the result of executing with a txt file and session specified.

Bash
$ python cstimer_histgram_en.py cstimer_20250126_235844.txt -s session1
session1 : Average Solve Time : 52.324 : Start Date and Time : 2024/07/21 21:29 : End Date and Time : 2024/08/27 20:21
Bash
Display histogram in window
Display histogram in window

The terminal displays the average solve time, start date and time, and end date and time for the session.A new window will open and a histogram will be displayed.

Closing the histogram window terminates the Python script on the terminal.

If ‘-a’ is specified instead of the option ‘-s’, the average solv time and histogram will be displayed for each of all sessions.If the on-screen display of the graph is depressing, uncomment line 51 and uncomment line 52 of the Python script to save it as a PNG file.

Record histograms in PNG
Record histograms in PNG

Musubi

I had no documentation on the structure of the csTimer JSON file, so I asked gemini to help me analyze the data and generate a Python script to summarize it.I also asked gemini to generate a Python script to summarize the data.

It is efficient to work with the generated AI to create programs, since improvement plans are also generated by simply copying and pasting the error messages.

Here’s what we plan to do:

  • Calculate ao5 and ao12
  • Calculation of averages and histograms for a specified period across sessions
  • Creating trend graphs
  • Add GUI

We hope to work on the area.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *