MartialTerran commited on
Commit
cfec946
·
verified ·
1 Parent(s): 4521e2d

Create Validate_sudokuCSV_V2.1.py

Browse files
Files changed (1) hide show
  1. Validate_sudokuCSV_V2.1.py +201 -0
Validate_sudokuCSV_V2.1.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Filename: Validate_sudokuCSV_V2.1.py
2
+ #
3
+ # Description:
4
+ # This script validates the 'solutions' column of a sudoku.csv file generated by
5
+ # Generate_sudokuCSV_V2.1.py or a similar script. It mathematically checks if each
6
+ # solved grid adheres to the rules of Sudoku.
7
+ #
8
+ # Key Logic:
9
+ # 1. **Loads Data:** Reads the 'sudoku.csv' file into a pandas DataFrame.
10
+ # 2. **Validates Each Solution:** For every row, it checks the 'solutions' grid to ensure:
11
+ # - Each row (1-9) contains exactly one of each digit from 1 to 9.
12
+ # - Each column (1-9) contains exactly one of each digit from 1 to 9.
13
+ # - Each 3x3 box (1-9) contains exactly one of each digit from 1 to 9.
14
+ # 3. **Reports Findings:** Prints a clear summary of how many grids are valid and invalid.
15
+ # 4. **Handles Invalid Grids (Colab-Friendly):**
16
+ # - If invalid grids are found, it saves their row indices to a file named
17
+ # `invalid_sudoku_indices.txt`.
18
+ # - It then instructs the user on how to clean the master CSV by changing a
19
+ # single configuration flag (`PERFORM_CLEANUP`) and re-running the script.
20
+ # 5. **Performs Cleanup (If Enabled):** If the `PERFORM_CLEANUP` flag is set to True
21
+ # and the index file exists, it will:
22
+ # - Move the invalid rows from 'sudoku.csv' to a new 'invalid_sudokus.csv' file.
23
+ # - Overwrite 'sudoku.csv' with a new, clean version.
24
+
25
+ import pandas as pd
26
+ import numpy as np
27
+ import os
28
+ import sys
29
+
30
+ # ==============================================================================
31
+ # === CONFIGURATION ===
32
+ # ==============================================================================
33
+
34
+ # --- Primary Action ---
35
+ # Set this to True AFTER running the script once and seeing an 'invalid' report.
36
+ # This will trigger the cleanup process on the next run.
37
+ PERFORM_CLEANUP = False
38
+
39
+ # --- File Paths ---
40
+ INPUT_CSV_PATH = 'sudoku.csv'
41
+ INVALID_INDICES_FILE = 'invalid_sudoku_indices.txt'
42
+ INVALID_CSV_EXPORT_PATH = 'invalid_sudokus.csv'
43
+
44
+ # ==============================================================================
45
+ # === VALIDATION LOGIC ===
46
+ # ==============================================================================
47
+
48
+ def validate_solution_grid(grid_1d: np.ndarray) -> bool:
49
+ """
50
+ Mathematically validates a 1D numpy array representing a 9x9 Sudoku solution.
51
+
52
+ Args:
53
+ grid_1d: A numpy array of 81 integers.
54
+
55
+ Returns:
56
+ True if the grid is a valid Sudoku solution, False otherwise.
57
+ """
58
+ if grid_1d.shape[0] != 81 or np.any(grid_1d == 0):
59
+ # Must be a fully filled 81-cell grid
60
+ return False
61
+
62
+ grid = grid_1d.reshape(9, 9)
63
+
64
+ # The set of digits {1, 2, 3, 4, 5, 6, 7, 8, 9}
65
+ required_set = set(range(1, 10))
66
+
67
+ # 1. Check all rows
68
+ for i in range(9):
69
+ if set(grid[i, :]) != required_set:
70
+ return False
71
+
72
+ # 2. Check all columns
73
+ for j in range(9):
74
+ if set(grid[:, j]) != required_set:
75
+ return False
76
+
77
+ # 3. Check all 3x3 boxes
78
+ for box_row_start in range(0, 9, 3):
79
+ for box_col_start in range(0, 9, 3):
80
+ box = grid[box_row_start:box_row_start+3, box_col_start:box_col_start+3]
81
+ if set(box.flatten()) != required_set:
82
+ return False
83
+
84
+ # If all checks pass, the grid is valid
85
+ return True
86
+
87
+ # ==============================================================================
88
+ # === MAIN EXECUTION SCRIPT ===
89
+ # ==============================================================================
90
+
91
+ def run_validation():
92
+ """Main function to run the validation and reporting process."""
93
+ print("--- Sudoku CSV Validator V2.1 ---")
94
+
95
+ if not os.path.exists(INPUT_CSV_PATH):
96
+ print(f"FATAL ERROR: The file '{INPUT_CSV_PATH}' was not found.")
97
+ print("Please make sure you have generated it using 'Generate_sudokuCSV_V2.1.py'.")
98
+ sys.exit(1)
99
+
100
+ print(f"Loading data from '{INPUT_CSV_PATH}'...")
101
+ try:
102
+ df = pd.read_csv(INPUT_CSV_PATH)
103
+ # Ensure columns are treated as strings to preserve leading zeros, then convert to numbers
104
+ df['solutions_str'] = df['solutions'].astype(str).str.zfill(81)
105
+ except Exception as e:
106
+ print(f"Error reading CSV file: {e}")
107
+ sys.exit(1)
108
+
109
+ print("Validating all solution grids...")
110
+ valid_indices = []
111
+ invalid_indices = []
112
+
113
+ for index, row in df.iterrows():
114
+ try:
115
+ # Convert the string of digits into a numpy array of integers
116
+ solution_grid_1d = np.array(list(map(int, row['solutions_str'])))
117
+ if validate_solution_grid(solution_grid_1d):
118
+ valid_indices.append(index)
119
+ else:
120
+ invalid_indices.append(index)
121
+ except (ValueError, TypeError):
122
+ # Handle cases where a row might be malformed
123
+ invalid_indices.append(index)
124
+
125
+ # --- Report Findings ---
126
+ num_valid = len(valid_indices)
127
+ num_invalid = len(invalid_indices)
128
+ total_grids = len(df)
129
+
130
+ print("\n--- VALIDATION REPORT ---")
131
+ print(f"Total grids scanned: {total_grids}")
132
+ print(f" => Valid solutions: {num_valid}")
133
+ print(f" => Invalid solutions: {num_invalid}")
134
+ print("-------------------------\n")
135
+
136
+ if num_invalid > 0:
137
+ print(f"Found {num_invalid} invalid grids. Saving their indices to '{INVALID_INDICES_FILE}'.")
138
+ # Save indices to the text file, one index per line
139
+ with open(INVALID_INDICES_FILE, 'w') as f:
140
+ for index in invalid_indices:
141
+ f.write(f"{index}\n")
142
+
143
+ print("\n*** ACTION REQUIRED ***")
144
+ print(f"To clean your '{INPUT_CSV_PATH}', please follow these steps:")
145
+ print("1. Open this script ('Validate_sudokuCSV_V2.1.py') in the editor.")
146
+ print("2. Change the configuration flag at the top from 'PERFORM_CLEANUP = False' to 'PERFORM_CLEANUP = True'.")
147
+ print("3. Re-run this script.")
148
+ print("This will move the invalid entries to 'invalid_sudokus.csv' and create a clean 'sudoku.csv'.")
149
+ else:
150
+ print("Congratulations! All solution grids in the CSV are valid.")
151
+ # If no invalid grids were found, remove the old index file if it exists
152
+ if os.path.exists(INVALID_INDICES_FILE):
153
+ os.remove(INVALID_INDICES_FILE)
154
+
155
+
156
+ def run_cleanup():
157
+ """Main function to perform the cleanup process."""
158
+ print("--- Sudoku CSV Cleanup Utility ---")
159
+ print(f"PERFORM_CLEANUP is set to True. Attempting to clean '{INPUT_CSV_PATH}'.")
160
+
161
+ if not os.path.exists(INVALID_INDICES_FILE):
162
+ print(f"ERROR: The file '{INVALID_INDICES_FILE}' was not found.")
163
+ print("Please run the script with 'PERFORM_CLEANUP = False' first to generate the list of invalid indices.")
164
+ sys.exit(1)
165
+
166
+ print(f"Loading master data from '{INPUT_CSV_PATH}'...")
167
+ df = pd.read_csv(INPUT_CSV_PATH)
168
+
169
+ print(f"Loading invalid indices from '{INVALID_INDICES_FILE}'...")
170
+ with open(INVALID_INDICES_FILE, 'r') as f:
171
+ invalid_indices = [int(line.strip()) for line in f]
172
+
173
+ print(f"Found {len(invalid_indices)} indices to remove.")
174
+
175
+ # Separate the DataFrame into invalid and valid parts
176
+ df_invalid = df.loc[invalid_indices]
177
+ df_valid = df.drop(invalid_indices)
178
+
179
+ # --- Perform the file operations ---
180
+ # 1. Export invalid puzzles and their solutions
181
+ print(f"Saving {len(df_invalid)} invalid entries to '{INVALID_CSV_EXPORT_PATH}'...")
182
+ df_invalid.to_csv(INVALID_CSV_EXPORT_PATH, index=False)
183
+
184
+ # 2. Overwrite the original file with only the valid data
185
+ print(f"Overwriting '{INPUT_CSV_PATH}' with {len(df_valid)} valid entries...")
186
+ df_valid.to_csv(INPUT_CSV_PATH, index=False)
187
+
188
+ # 3. Clean up the index file
189
+ os.remove(INVALID_INDICES_FILE)
190
+
191
+ print("\n--- Cleanup Complete! ---")
192
+ print(f"Your '{INPUT_CSV_PATH}' is now clean.")
193
+ print(f"The invalid entries have been moved to '{INVALID_CSV_EXPORT_PATH}'.")
194
+ print("Set 'PERFORM_CLEANUP = False' before running validation again.")
195
+
196
+
197
+ if __name__ == '__main__':
198
+ if PERFORM_CLEANUP:
199
+ run_cleanup()
200
+ else:
201
+ run_validation()