File size: 7,589 Bytes
6f277e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# sudokuCSV_analyzer_v2.py
#
# Description:
# This script analyzes a 'sudoku.csv' file to identify duplicate and symmetric puzzles
# by comparing the FULLY SOLVED grids from the 'solutions' column.
#
# Main Functions:
# 1. Finds and logs pairs of solved grids that are exact duplicates.
# 2. Finds and logs pairs of solved grids that are rotations or mirrors of each other.
# 3. Generates histograms for two similarity metrics based on the solved grids.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm.auto import tqdm
import os

# === HELPER FUNCTIONS =======================================================

def string_to_grid(s: str) -> np.ndarray:
    """Converts an 81-character string to a 9x9 NumPy array."""
    return np.array(list(map(int, s))).reshape((9, 9))

def grid_to_string(g: np.ndarray) -> str:
    """Converts a 9x9 NumPy array back to an 81-character string."""
    return "".join(map(str, g.flatten()))

def get_all_symmetries(grid: np.ndarray) -> set:
    """
    Generates all 8 unique symmetries (rotations and mirrors) for a given grid.
    Returns a set of the grids represented as strings.
    """
    symmetries = set()
    current_grid = grid.copy()
    
    for _ in range(4):  # 4 rotations
        symmetries.add(grid_to_string(current_grid))
        symmetries.add(grid_to_string(np.flipud(current_grid))) # Horizontal mirror
        current_grid = np.rot90(current_grid)
        
    return symmetries

def compare_cell_similarity(grid1: np.ndarray, grid2: np.ndarray) -> int:
    """Counts the number of cells that have the same value in the same position."""
    return np.sum(grid1 == grid2)

def compare_digit_frequency_similarity(grid1: np.ndarray, grid2: np.ndarray) -> int:
    """
    Counts how many digits (1-9) have the same frequency in both grids.
    """
    # Since we are using solved grids, there are no zeros to filter.
    # The logic remains robust if ever used with unsolved puzzles.
    vals1, counts1 = np.unique(grid1, return_counts=True)
    vals2, counts2 = np.unique(grid2, return_counts=True)
    
    freq_map1 = dict(zip(vals1, counts1))
    freq_map2 = dict(zip(vals2, counts2))
    
    similar_freq_count = 0
    for digit in range(1, 10):
        if freq_map1.get(digit, 0) == freq_map2.get(digit, 0):
            similar_freq_count += 1
            
    return similar_freq_count

# === MAIN ANALYSIS FUNCTION =================================================

def analyze_solved_grids(
    csv_path: str = 'sudoku.csv',
    start_index: int = 0,
    end_index: int = 600,
    min_diff_cells_for_log: int = 4
):
    """
    Main function to drive the analysis of the solved sudoku grids.
    """
    print("--- Sudoku Solved Grid Analyzer ---")

    # 1. Load Data
    if not os.path.exists(csv_path):
        print(f"ERROR: The file '{csv_path}' was not found.")
        print("Please ensure the sudoku data file is in the same directory.")
        return

    print(f"Loading data from '{csv_path}'...")
    df = pd.read_csv(csv_path)
    
    if 'solutions' not in df.columns:
        print("ERROR: The CSV file must contain a 'solutions' column with fully solved grids.")
        return
        
    # Ensure the range is valid
    if end_index > len(df):
        print(f"Warning: end_index ({end_index}) is greater than number of puzzles ({len(df)}). Adjusting to max.")
        end_index = len(df)
    if start_index >= end_index:
        print("Error: start_index must be less than end_index.")
        return

    # *** KEY CHANGE IS HERE: Use the 'solutions' column ***
    print("Analyzing the 'solutions' column (fully solved grids).")
    puzzle_solutions = df['solutions'].iloc[start_index:end_index].tolist()
    grids = [string_to_grid(p) for p in puzzle_solutions]
    num_grids = len(grids)
    print(f"Analysis will be performed on {num_grids} solved grids (indices {start_index} to {end_index-1}).")

    # 2. Prepare data structures for results
    exact_duplicates = []
    symmetry_pairs = []
    cell_similarity_counts = []
    digit_freq_similarity_counts = []

    print("\nStarting pairwise comparison... This may take a while.")
    
    # 3. Perform pairwise comparison
    for i in tqdm(range(num_grids), desc="Analyzing Solved Grids"):
        grid_i = grids[i]
        symmetries_of_i = get_all_symmetries(grid_i)
        
        for j in range(i + 1, num_grids):
            grid_j = grids[j]
            
            if np.array_equal(grid_i, grid_j):
                exact_duplicates.append({'index_1': start_index + i, 'index_2': start_index + j})
                continue
            
            if grid_to_string(grid_j) in symmetries_of_i:
                symmetry_pairs.append({'index_1': start_index + i, 'index_2': start_index + j})
                
            num_same_cells = compare_cell_similarity(grid_i, grid_j)
            
            if (81 - num_same_cells) >= min_diff_cells_for_log:
                 cell_similarity_counts.append(num_same_cells)
                 digit_freq_similarity_counts.append(compare_digit_frequency_similarity(grid_i, grid_j))

    print("\nAnalysis complete. Saving results...")

    # 4. Save results to CSV files
    if exact_duplicates:
        duplicates_df = pd.DataFrame(exact_duplicates)
        duplicates_df.to_csv('solved_exact_duplicates.csv', index=False)
        print(f"Found {len(duplicates_df)} exact duplicate pairs. Logged to 'solved_exact_duplicates.csv'.")
    else:
        print("No exact duplicates found in the specified range.")

    if symmetry_pairs:
        symmetry_df = pd.DataFrame(symmetry_pairs)
        symmetry_df.to_csv('solved_possible_symmetry_pairs.csv', index=False)
        print(f"Found {len(symmetry_df)} potential symmetry pairs. Logged to 'solved_possible_symmetry_pairs.csv'.")
    else:
        print("No symmetry pairs found in the specified range.")
        
    # 5. Generate and save histograms
    sns.set_style("darkgrid")

    # Histogram 1: Cell Similarity
    plt.figure(figsize=(12, 6))
    sns.histplot(cell_similarity_counts, bins=81, kde=False)
    plt.title(f'Distribution of Cell Similarity on Solved Grids ({num_grids} Grids)', fontsize=16)
    plt.xlabel('Number of Identical Cells in Same Position (out of 81)', fontsize=12)
    plt.ylabel('Frequency (Number of Pairs)', fontsize=12)
    plt.xlim(0, 81)
    plt.tight_layout()
    plt.savefig('solved_cell_similarity_histogram.png')
    plt.close()
    print("Saved 'solved_cell_similarity_histogram.png'.")

    # Histogram 2: Digit Frequency Similarity
    plt.figure(figsize=(12, 6))
    sns.histplot(digit_freq_similarity_counts, bins=10, discrete=True, kde=False)
    plt.title(f'Distribution of Digit Frequency Similarity on Solved Grids ({num_grids} Grids)', fontsize=16)
    plt.xlabel('Number of Digits (1-9) with Same Frequency in Both Grids', fontsize=12)
    plt.ylabel('Frequency (Number of Pairs)', fontsize=12)
    plt.xticks(range(10))
    plt.tight_layout()
    plt.savefig('solved_digit_frequency_similarity_histogram.png')
    plt.close()
    print("Saved 'solved_digit_frequency_similarity_histogram.png'.")
    
    print("\n--- Analysis Finished ---")


if __name__ == '__main__':
    # --- Configuration ---
    DATA_FILE_PATH = 'sudoku.csv'
    START_PUZZLE_INDEX = 0
    END_PUZZLE_INDEX = 600
    MIN_DIFFERENT_CELLS = 4
    
    # --- Execution ---
    analyze_solved_grids(
        csv_path=DATA_FILE_PATH,
        start_index=START_PUZZLE_INDEX,
        end_index=END_PUZZLE_INDEX,
        min_diff_cells_for_log=MIN_DIFFERENT_CELLS
    )