MartialTerran commited on
Commit
6f277e5
·
verified ·
1 Parent(s): 8aa79db

Create sudokuCSV_analyzer_v2.py

Browse files
Files changed (1) hide show
  1. sudokuCSV_analyzer_v2.py +197 -0
sudokuCSV_analyzer_v2.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sudokuCSV_analyzer_v2.py
2
+ #
3
+ # Description:
4
+ # This script analyzes a 'sudoku.csv' file to identify duplicate and symmetric puzzles
5
+ # by comparing the FULLY SOLVED grids from the 'solutions' column.
6
+ #
7
+ # Main Functions:
8
+ # 1. Finds and logs pairs of solved grids that are exact duplicates.
9
+ # 2. Finds and logs pairs of solved grids that are rotations or mirrors of each other.
10
+ # 3. Generates histograms for two similarity metrics based on the solved grids.
11
+
12
+ import pandas as pd
13
+ import numpy as np
14
+ import matplotlib.pyplot as plt
15
+ import seaborn as sns
16
+ from tqdm.auto import tqdm
17
+ import os
18
+
19
+ # === HELPER FUNCTIONS =======================================================
20
+
21
+ def string_to_grid(s: str) -> np.ndarray:
22
+ """Converts an 81-character string to a 9x9 NumPy array."""
23
+ return np.array(list(map(int, s))).reshape((9, 9))
24
+
25
+ def grid_to_string(g: np.ndarray) -> str:
26
+ """Converts a 9x9 NumPy array back to an 81-character string."""
27
+ return "".join(map(str, g.flatten()))
28
+
29
+ def get_all_symmetries(grid: np.ndarray) -> set:
30
+ """
31
+ Generates all 8 unique symmetries (rotations and mirrors) for a given grid.
32
+ Returns a set of the grids represented as strings.
33
+ """
34
+ symmetries = set()
35
+ current_grid = grid.copy()
36
+
37
+ for _ in range(4): # 4 rotations
38
+ symmetries.add(grid_to_string(current_grid))
39
+ symmetries.add(grid_to_string(np.flipud(current_grid))) # Horizontal mirror
40
+ current_grid = np.rot90(current_grid)
41
+
42
+ return symmetries
43
+
44
+ def compare_cell_similarity(grid1: np.ndarray, grid2: np.ndarray) -> int:
45
+ """Counts the number of cells that have the same value in the same position."""
46
+ return np.sum(grid1 == grid2)
47
+
48
+ def compare_digit_frequency_similarity(grid1: np.ndarray, grid2: np.ndarray) -> int:
49
+ """
50
+ Counts how many digits (1-9) have the same frequency in both grids.
51
+ """
52
+ # Since we are using solved grids, there are no zeros to filter.
53
+ # The logic remains robust if ever used with unsolved puzzles.
54
+ vals1, counts1 = np.unique(grid1, return_counts=True)
55
+ vals2, counts2 = np.unique(grid2, return_counts=True)
56
+
57
+ freq_map1 = dict(zip(vals1, counts1))
58
+ freq_map2 = dict(zip(vals2, counts2))
59
+
60
+ similar_freq_count = 0
61
+ for digit in range(1, 10):
62
+ if freq_map1.get(digit, 0) == freq_map2.get(digit, 0):
63
+ similar_freq_count += 1
64
+
65
+ return similar_freq_count
66
+
67
+ # === MAIN ANALYSIS FUNCTION =================================================
68
+
69
+ def analyze_solved_grids(
70
+ csv_path: str = 'sudoku.csv',
71
+ start_index: int = 0,
72
+ end_index: int = 600,
73
+ min_diff_cells_for_log: int = 4
74
+ ):
75
+ """
76
+ Main function to drive the analysis of the solved sudoku grids.
77
+ """
78
+ print("--- Sudoku Solved Grid Analyzer ---")
79
+
80
+ # 1. Load Data
81
+ if not os.path.exists(csv_path):
82
+ print(f"ERROR: The file '{csv_path}' was not found.")
83
+ print("Please ensure the sudoku data file is in the same directory.")
84
+ return
85
+
86
+ print(f"Loading data from '{csv_path}'...")
87
+ df = pd.read_csv(csv_path)
88
+
89
+ if 'solutions' not in df.columns:
90
+ print("ERROR: The CSV file must contain a 'solutions' column with fully solved grids.")
91
+ return
92
+
93
+ # Ensure the range is valid
94
+ if end_index > len(df):
95
+ print(f"Warning: end_index ({end_index}) is greater than number of puzzles ({len(df)}). Adjusting to max.")
96
+ end_index = len(df)
97
+ if start_index >= end_index:
98
+ print("Error: start_index must be less than end_index.")
99
+ return
100
+
101
+ # *** KEY CHANGE IS HERE: Use the 'solutions' column ***
102
+ print("Analyzing the 'solutions' column (fully solved grids).")
103
+ puzzle_solutions = df['solutions'].iloc[start_index:end_index].tolist()
104
+ grids = [string_to_grid(p) for p in puzzle_solutions]
105
+ num_grids = len(grids)
106
+ print(f"Analysis will be performed on {num_grids} solved grids (indices {start_index} to {end_index-1}).")
107
+
108
+ # 2. Prepare data structures for results
109
+ exact_duplicates = []
110
+ symmetry_pairs = []
111
+ cell_similarity_counts = []
112
+ digit_freq_similarity_counts = []
113
+
114
+ print("\nStarting pairwise comparison... This may take a while.")
115
+
116
+ # 3. Perform pairwise comparison
117
+ for i in tqdm(range(num_grids), desc="Analyzing Solved Grids"):
118
+ grid_i = grids[i]
119
+ symmetries_of_i = get_all_symmetries(grid_i)
120
+
121
+ for j in range(i + 1, num_grids):
122
+ grid_j = grids[j]
123
+
124
+ if np.array_equal(grid_i, grid_j):
125
+ exact_duplicates.append({'index_1': start_index + i, 'index_2': start_index + j})
126
+ continue
127
+
128
+ if grid_to_string(grid_j) in symmetries_of_i:
129
+ symmetry_pairs.append({'index_1': start_index + i, 'index_2': start_index + j})
130
+
131
+ num_same_cells = compare_cell_similarity(grid_i, grid_j)
132
+
133
+ if (81 - num_same_cells) >= min_diff_cells_for_log:
134
+ cell_similarity_counts.append(num_same_cells)
135
+ digit_freq_similarity_counts.append(compare_digit_frequency_similarity(grid_i, grid_j))
136
+
137
+ print("\nAnalysis complete. Saving results...")
138
+
139
+ # 4. Save results to CSV files
140
+ if exact_duplicates:
141
+ duplicates_df = pd.DataFrame(exact_duplicates)
142
+ duplicates_df.to_csv('solved_exact_duplicates.csv', index=False)
143
+ print(f"Found {len(duplicates_df)} exact duplicate pairs. Logged to 'solved_exact_duplicates.csv'.")
144
+ else:
145
+ print("No exact duplicates found in the specified range.")
146
+
147
+ if symmetry_pairs:
148
+ symmetry_df = pd.DataFrame(symmetry_pairs)
149
+ symmetry_df.to_csv('solved_possible_symmetry_pairs.csv', index=False)
150
+ print(f"Found {len(symmetry_df)} potential symmetry pairs. Logged to 'solved_possible_symmetry_pairs.csv'.")
151
+ else:
152
+ print("No symmetry pairs found in the specified range.")
153
+
154
+ # 5. Generate and save histograms
155
+ sns.set_style("darkgrid")
156
+
157
+ # Histogram 1: Cell Similarity
158
+ plt.figure(figsize=(12, 6))
159
+ sns.histplot(cell_similarity_counts, bins=81, kde=False)
160
+ plt.title(f'Distribution of Cell Similarity on Solved Grids ({num_grids} Grids)', fontsize=16)
161
+ plt.xlabel('Number of Identical Cells in Same Position (out of 81)', fontsize=12)
162
+ plt.ylabel('Frequency (Number of Pairs)', fontsize=12)
163
+ plt.xlim(0, 81)
164
+ plt.tight_layout()
165
+ plt.savefig('solved_cell_similarity_histogram.png')
166
+ plt.close()
167
+ print("Saved 'solved_cell_similarity_histogram.png'.")
168
+
169
+ # Histogram 2: Digit Frequency Similarity
170
+ plt.figure(figsize=(12, 6))
171
+ sns.histplot(digit_freq_similarity_counts, bins=10, discrete=True, kde=False)
172
+ plt.title(f'Distribution of Digit Frequency Similarity on Solved Grids ({num_grids} Grids)', fontsize=16)
173
+ plt.xlabel('Number of Digits (1-9) with Same Frequency in Both Grids', fontsize=12)
174
+ plt.ylabel('Frequency (Number of Pairs)', fontsize=12)
175
+ plt.xticks(range(10))
176
+ plt.tight_layout()
177
+ plt.savefig('solved_digit_frequency_similarity_histogram.png')
178
+ plt.close()
179
+ print("Saved 'solved_digit_frequency_similarity_histogram.png'.")
180
+
181
+ print("\n--- Analysis Finished ---")
182
+
183
+
184
+ if __name__ == '__main__':
185
+ # --- Configuration ---
186
+ DATA_FILE_PATH = 'sudoku.csv'
187
+ START_PUZZLE_INDEX = 0
188
+ END_PUZZLE_INDEX = 600
189
+ MIN_DIFFERENT_CELLS = 4
190
+
191
+ # --- Execution ---
192
+ analyze_solved_grids(
193
+ csv_path=DATA_FILE_PATH,
194
+ start_index=START_PUZZLE_INDEX,
195
+ end_index=END_PUZZLE_INDEX,
196
+ min_diff_cells_for_log=MIN_DIFFERENT_CELLS
197
+ )