Debian Codegraph @

tksheet/sorting.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from collections.abc import Callable, Iterator
4 from datetime import datetime
5 from pathlib import Path
6 from re import split
7 from typing import Any
8
9 # Possible date formats to try for the entire string
10 date_formats = (
11 # Common formats
12 "%d/%m/%Y", # Day/Month/Year
13 "%m/%d/%Y", # Month/Day/Year (US format)
14 "%Y/%m/%d", # Year/Month/Day
15 "%d.%m.%Y", # Day.Month.Year (European format)
16 "%d-%m-%Y", # Day-Month-Year
17 "%m-%d-%Y", # Month-Day-Year
18 "%Y-%m-%d", # Year-Month-Day (ISO format without time)
19 "%d/%m/%y", # Day/Month/2-digit year
20 "%m/%d/%y", # Month/Day/2-digit year
21 "%y/%m/%d", # 2-digit year/Month/Day
22 "%d,%m,%Y", # Day,Month,Year
23 "%m,%d,%Y", # Month,Day,Year
24 "%Y,%m,%d", # Year,Month,Day
25 "%d %m %Y", # Day Month Year (with space)
26 "%m %d %Y", # Month Day Year (with space)
27 "%Y %d %m", # Year Month Day (with space)
28 # With month names
29 "%d %b %Y", # Day Abbreviated Month Year
30 "%b %d, %Y", # Abbreviated Month Day, Year
31 "%d %B %Y", # Day Full Month Name Year
32 "%B %d, %Y", # Full Month Name Day, Year
33 # ISO 8601 with/without time
34 "%Y-%m-%dT%H:%M:%S", # With time
35 "%Y-%m-%d", # Without time
36 # Regional or less common formats
37 # "%Y年%m月%d日", # Japanese-style date
38 "%Y%m%d", # YYYYMMDD format, often used in logs or filenames
39 "%y%m%d", # YYMMDD
40 "%d%m%Y", # DDMMYYYY, sometimes used in Europe
41 # Additional formats
42 "%d/%m/%y %H:%M", # Day/Month/Year Hour:Minute
43 "%m/%d/%y %H:%M", # Month/Day/Year Hour:Minute
44 "%Y-%m-%d %H:%M:%S", # Year-Month-Day Hour:Minute:Second
45 )
46
47
48 def _string_fallback(item: str) -> tuple[int, ...]:
49 """
50 In order to have reasonable file path sorting:
51 - Split by path separators
52 - Determine depth, more separators more depth
53 - Deal with every dir by splitting by digits
54 - Deal with file name by splitting by digits
55 """
56 components = split(r"[/\\]", item)
57 if components[-1]:
58 return (
59 5,
60 len(components),
61 tuple(int(e) if e.isdigit() else e.lower() for comp in components[:-1] for e in split(r"(\d+)", comp) if e),
62 tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", components[-1])),
63 )
64 else:
65 return (
66 5,
67 len(components),
68 tuple(int(e) if e.isdigit() else e.lower() for comp in components[:-1] for e in split(r"(\d+)", comp) if e),
69 (),
70 )
71
72
73 def version_sort_key(item: Any) -> tuple[int, ...]:
74 """
75 A key for natural sorting of various Python types.
76
77 - Won't convert strings to floats
78 - Will sort string version numbers
79
80 0. None
81 1. Empty strings
82 2. bool
83 3. int, float
84 4. datetime (inc. strings that are dates)
85 5. strings (including string file paths and paths as POSIX strings) & unknown objects with __str__
86 6. unknown objects
87 """
88 if isinstance(item, str):
89 if item:
90 for date_format in date_formats:
91 try:
92 return (4, datetime.strptime(item, date_format).timestamp())
93 except ValueError:
94 continue
95 # the same as _string_fallback
96 components = split(r"[/\\]", item)
97 if components[-1]:
98 return (
99 5,
100 len(components),
101 tuple(
102 int(e) if e.isdigit() else e.lower()
103 for comp in components[:-1]
104 for e in split(r"(\d+)", comp)
105 if e
106 ),
107 tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", components[-1])),
108 )
109 else:
110 return (
111 5,
112 len(components),
113 tuple(
114 int(e) if e.isdigit() else e.lower()
115 for comp in components[:-1]
116 for e in split(r"(\d+)", comp)
117 if e
118 ),
119 (),
120 )
121 else:
122 return (1, item)
123
124 elif item is None:
125 return (0,)
126
127 elif isinstance(item, bool):
128 return (2, item)
129
130 elif isinstance(item, (int, float)):
131 return (3, item)
132
133 elif isinstance(item, datetime):
134 return (4, item.timestamp())
135
136 elif isinstance(item, Path):
137 return _string_fallback(item.as_posix())
138
139 else:
140 try:
141 return _string_fallback(f"{item}")
142 except Exception:
143 return (6, item)
144
145
146 def natural_sort_key(item: Any) -> tuple[int, ...]:
147 """
148 A key for natural sorting of various Python types.
149
150 - Won't sort string version numbers
151 - Will convert strings to floats
152 - Will sort strings that are file paths
153
154 0. None
155 1. Empty strings
156 2. bool
157 3. int, float (inc. strings that are numbers)
158 4. datetime (inc. strings that are dates)
159 5. strings (including string file paths and paths as POSIX strings) & unknown objects with __str__
160 6. unknown objects
161 """
162 if isinstance(item, str):
163 if item:
164 for date_format in date_formats:
165 try:
166 return (4, datetime.strptime(item, date_format).timestamp())
167 except ValueError:
168 continue
169
170 try:
171 return (3, float(item))
172 except ValueError:
173 # the same as _string_fallback
174 components = split(r"[/\\]", item)
175 if components[-1]:
176 return (
177 5,
178 len(components),
179 tuple(
180 int(e) if e.isdigit() else e.lower()
181 for comp in components[:-1]
182 for e in split(r"(\d+)", comp)
183 if e
184 ),
185 tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", components[-1])),
186 )
187 else:
188 return (
189 5,
190 len(components),
191 tuple(
192 int(e) if e.isdigit() else e.lower()
193 for comp in components[:-1]
194 for e in split(r"(\d+)", comp)
195 if e
196 ),
197 (),
198 )
199 else:
200 return (1, item)
201
202 elif item is None:
203 return (0,)
204
205 elif isinstance(item, bool):
206 return (2, item)
207
208 elif isinstance(item, (int, float)):
209 return (3, item)
210
211 elif isinstance(item, datetime):
212 return (4, item.timestamp())
213
214 elif isinstance(item, Path):
215 return _string_fallback(item.as_posix())
216
217 else:
218 try:
219 return _string_fallback(f"{item}")
220 except Exception:
221 return (6, item)
222
223
224 def fast_sort_key(item: Any) -> tuple[int, ...]:
225 """
226 A faster key for natural sorting of various Python types.
227
228 - Won't sort strings that are dates very well
229 - Won't convert strings to floats
230 - Won't sort string file paths very well
231 - Will do ok with string version numbers
232
233 0. None
234 1. Empty strings
235 2. bool
236 3. int, float
237 4. datetime
238 5. strings (including paths as POSIX strings) & unknown objects with __str__
239 6. unknown objects
240 """
241 if isinstance(item, str):
242 if item:
243 return (5, tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", item)))
244 else:
245 return (1, item)
246
247 elif item is None:
248 return (0,)
249
250 elif isinstance(item, bool):
251 return (2, item)
252
253 elif isinstance(item, (int, float)):
254 return (3, item)
255
256 elif isinstance(item, datetime):
257 return (4, item.timestamp())
258
259 elif isinstance(item, Path):
260 return _string_fallback(item.as_posix())
261
262 else:
263 try:
264 return _string_fallback(f"{item}")
265 except Exception:
266 return (6, item)
267
268
269 def sort_selection(
270 data: list[list[Any]],
271 reverse: bool = False,
272 key: Callable | None = None,
273 row_wise: bool = False,
274 ) -> list[list[Any]]:
275 if not data or not isinstance(data[0], list):
276 raise ValueError("Data must be a list of lists.")
277
278 if key is None:
279 key = natural_sort_key
280
281 if row_wise:
282 return [sorted(row, key=key, reverse=reverse) for row in data]
283 else:
284 return list(
285 zip(
286 *(
287 sorted(
288 (row[col] for row in data),
289 key=key,
290 reverse=reverse,
291 )
292 for col in range(len(data[0]))
293 )
294 )
295 )
296
297
298 def sort_column(
299 data: list[list[Any]] | list[Any] | Iterator[Any],
300 column: int = 0,
301 reverse: bool = False,
302 key: Callable | None = None,
303 ) -> list[list[Any]] | list[Any]:
304 if not data:
305 return data
306
307 if key is None:
308 key = natural_sort_key
309
310 if isinstance(data, list) and isinstance(data[0], list):
311 return sorted(data, key=lambda row: key(row[column]) if len(row) > column else key(None), reverse=reverse)
312 else:
313 return sorted(data, reverse=reverse, key=key)
314
315
316 def sort_row(
317 data: list[list[Any]] | list[Any] | Iterator[Any],
318 row: int = 0,
319 reverse: bool = False,
320 key: Callable | None = None,
321 ) -> list[list[Any]]:
322 if not data:
323 return data
324
325 if key is None:
326 key = natural_sort_key
327
328 if isinstance(data, list) and isinstance(data[0], list):
329 if 0 <= row < len(data):
330 data[row] = sorted(data[row], key=key, reverse=reverse)
331 return data
332 else:
333 raise IndexError(f"Row index {row} out of range for data with {len(data)} rows.")
334 else:
335 return sorted(data, reverse=reverse, key=key)
336
337
338 def sort_rows_by_column(
339 data: list[list[Any]],
340 column: int = 0,
341 reverse: bool = False,
342 key: Callable | None = None,
343 ) -> tuple[list[tuple[int, list[Any]]], dict[int, int]]:
344 if not data:
345 return data, {}
346
347 # Check if data is a list of lists
348 if not isinstance(data[0], list):
349 raise ValueError("Data must be a list of lists for row sorting.")
350
351 if key is None:
352 key = natural_sort_key
353
354 # Use a generator expression for sorting to avoid creating an intermediate list
355 sorted_indexed_data = sorted(
356 ((i, row) for i, row in enumerate(data)),
357 key=lambda item: key(item[1][column]) if len(item[1]) > column else key(None),
358 reverse=reverse,
359 )
360
361 # Return sorted rows [(old index, row), ...] and create the mapping dictionary
362 return sorted_indexed_data, {old: new for new, (old, _) in enumerate(sorted_indexed_data)}
363
364
365 def sort_columns_by_row(
366 data: list[list[Any]],
367 row: int = 0,
368 reverse: bool = False,
369 key: Callable | None = None,
370 ) -> tuple[list[int], dict[int, int]]:
371 if not data:
372 return data, {}
373
374 # Check if data is a list of lists
375 if not isinstance(data[0], list):
376 raise ValueError("Data must be a list of lists for column sorting.")
377
378 if row >= len(data) or row < 0:
379 raise IndexError(f"Row index {row} out of range for data with {len(data)} rows.")
380
381 if key is None:
382 key = natural_sort_key
383
384 # Get sorting indices based on the elements of the specified row
385 sort_indices = sorted(range(len(data[row])), key=lambda i: key(data[row][i]), reverse=reverse)
386 sort_indices_set = set(sort_indices)
387
388 new_data = []
389 for row_data in data:
390 # Sort the columns based on sort_indices, then append any additional elements from longer rows
391 sorted_part = [row_data[i] for i in sort_indices if i < len(row_data)]
392 unsorted_part = [elem for idx, elem in enumerate(row_data) if idx not in sort_indices_set]
393 new_data.append(sorted_part + unsorted_part)
394
395 return sort_indices, dict(zip(range(len(data[row])), sort_indices))
396
397
398 def sort_tree_rows_by_column(
399 data: list[list[Any]],
400 column: int,
401 index: list[Any],
402 rns: dict[str, int],
403 reverse: bool = False,
404 key: Callable | None = None,
405 ) -> tuple[list[Any], dict[int, int]]:
406 """
407 Sorts tree rows by a specified column in depth-first order, returning sorted nodes and a row mapping.
408
409 Args:
410 data: List of rows, where each row is a list of column values.
411 column: Index of the column to sort by.
412 index: List of nodes, where each node has 'iid', 'parent', and 'children' attributes.
413 rns: Dictionary mapping item IDs (iid) to original row numbers in data.
414 reverse: If True, sort in descending order; otherwise, ascending.
415 key: Optional function to compute sort keys; defaults to natural_sort_key if None.
416
417 Returns:
418 Tuple containing:
419 - List of nodes in sorted order.
420 - Dictionary mapping original row numbers to new row numbers.
421 """
422 if not index or not rns:
423 return [], {}
424
425 if key is None:
426 key = natural_sort_key # Assuming natural_sort_key is defined elsewhere
427
428 # Define the sort_reverse parameter to avoid unnecessary reversals
429 sort_reverse = not reverse
430
431 # Helper function to compute the sorting key for a node
432 def get_key(node):
433 row = data[rns[node.iid]]
434 return key(row[column] if len(row) > column else None)
435
436 # Initialize stack with sorted top-level nodes for efficiency
437 stack = sorted(
438 (node for node in index if node.parent == ""),
439 key=get_key,
440 reverse=sort_reverse,
441 )
442
443 # Initialize output structures
444 sorted_nodes = []
445 mapping = {}
446 new_rn = 0
447
448 # Process nodes iteratively in depth-first order
449 while stack:
450 current = stack.pop() # Pop from the right end
451 sorted_nodes.append(current)
452 mapping[rns[current.iid]] = new_rn
453 new_rn += 1
454 if current.children:
455 # Sort children
456 sorted_children = sorted(
457 (index[rns[ciid]] for ciid in current.children if ciid in rns),
458 key=get_key,
459 reverse=sort_reverse,
460 )
461 # Extend stack with sorted children
462 stack.extend(sorted_children) # Adds to the right end
463
464 return sorted_nodes, mapping
465
466
467 # if __name__ == "__main__":
468 # test_cases = {
469 # "Filenames": ["file10.txt", "file2.txt", "file1.txt"],
470 # "Versions": ["1.10", "1.2", "1.9", "1.21"],
471 # "Mixed": ["z1.doc", "z10.doc", "z2.doc", "z100.doc"],
472 # "Paths": [
473 # "/folder/file.txt",
474 # "/folder/file (1).txt",
475 # "/folder (1)/file.txt",
476 # "/folder (10)/file.txt",
477 # "/dir/subdir/file1.txt",
478 # "/dir/subdir/file10.txt",
479 # "/dir/subdir/file2.txt",
480 # "/dir/file.txt",
481 # "/dir/sub/file123.txt",
482 # "/dir/sub/file12.txt",
483 # # New challenging cases
484 # "/a/file.txt",
485 # "/a/file1.txt",
486 # "/a/b/file.txt",
487 # "/a/b/file1.txt",
488 # "/x/file-v1.2.txt",
489 # "/x/file-v1.10.txt",
490 # # My own new challenging cases
491 # "/a/zzzzz.txt",
492 # "/a/b/a.txt",
493 # ],
494 # "Case": ["Apple", "banana", "Corn", "apple", "Banana", "corn"],
495 # "Leading Zeros": ["001", "010", "009", "100"],
496 # "Complex": ["x-1-y-10", "x-1-y-2", "x-2-y-1", "x-10-y-1"],
497 # "Lengths": ["2 ft 9 in", "2 ft 10 in", "10 ft 1 in", "10 ft 2 in"],
498 # "Floats": [
499 # "1.5",
500 # "1.25",
501 # "1.025",
502 # "10.5",
503 # "-10.2",
504 # "-2.5",
505 # "5.7",
506 # "-1.25",
507 # "0.0",
508 # "1.5e3",
509 # "2.5e2",
510 # "1.23e4",
511 # "1e-2",
512 # "file1.2.txt",
513 # "file1.5.txt",
514 # "file1.10.txt",
515 # ],
516 # "Strings": [
517 # "123abc",
518 # "abc123",
519 # "123abc456",
520 # "abc123def",
521 # ],
522 # }
523
524 # print("FAST SORT KEY:")
525
526 # for name, data in test_cases.items():
527 # sorted1 = sorted(data, key=fast_sort_key)
528 # print(f"\n{name}:")
529 # print(sorted1)
530
531 # print("\nNATURAL SORT KEY:")
532
533 # for name, data in test_cases.items():
534 # sorted1 = sorted(data, key=natural_sort_key)
535 # print(f"\n{name}:")
536 # print(sorted1)
537
538 # print("\nVERSION SORT KEY:")
539
540 # for name, data in test_cases.items():
541 # sorted1 = sorted(data, key=version_sort_key)
542 # print(f"\n{name}:")
543 # print(sorted1)