sort_routines.html


001| '''Common Sort Routines.
001| [https://en.wikipedia.org/wiki/Sorting_algorithm]
001| 
001| Sort Functions:
001|     bubble          [https://en.wikipedia.org/wiki/Bubble_sort]
001|     shaker          ["]
001|     insertion       [https://en.wikipedia.org/wiki/Insertion_sort]
001|     selection       [https://en.wikipedia.org/wiki/Selection_sort]
001|     merge           [https://en.wikipedia.org/wiki/Merge_sort]
001|     heapsort        [https://en.wikipedia.org/wiki/Heapsort]
001|     quicksort       [https://en.wikipedia.org/wiki/Quicksort]
001|     shellsort       [https://en.wikipedia.org/wiki/Shellsort]
001| 
001| Functions:
001|     do_sort_routine (title, sort_function, fname,fpath, *args)
001| 
001| Commands:
001|     bubble      do_bubble_sort
001|     shaker      do_shaker_sort
001|     insert      do_insertion_sort
001|     select      do_selection_sort
001|     merge       do_merge_sort
001|     heap        do_heap_sort
001|     qsort       do_quick_sort
001|     shell       do_shell_sort
001| 
001|     all         do_all
001|     pngs        do_animation
001| 
001| TODO: animation (end with long bogosort; captions "this is it")
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from math import floor
007| from time import perf_counter_ns
008| from random import random, choice
009| from itertools import count as RowNum
010| from PIL import Image, ImageDraw, ImageFont
011| from logger import logger,info,debug,trace, LogFilenameTimestamp
012| from goodies import KWARG
013| from files import linefile, tabfile
014| from canvas import Canvas
015| ####################################################################################################
016| BasePath = r'C:\CJS\prj\Python\blog\hcc\source\sorts'
017| DataPath = path.join(BasePath, 'dat')
018| ImgsPath = path.join(BasePath, 'img')
019| AnimPath = path.join(BasePath, 'ani')
020| Log = logger('sorts')
021| 
022| CMND = ''
023| ARGS = {
024|     #'n': '100',
025|     #'lo': '0',
026|     #'hi': '+1',
027|     #'cap': '1',
028|     #'fpath': BasePath, #'fname': 'insertionsort.tab',
029|     #'opath': BasePath, #'oname': 'insertionsort.tab',
030|     #'dpath': BasePath, #'dname': 'sortset.list',
031|     #'apath': ImgsPath,
032| }
033| 
034| ##------------------------------------------------------------------------------------------------##
035| DefaultCount = int(1000)
036| DefaultHiVal =  float(100)
037| DefaultLoVal =  float(0)
038| 
039| RandNum = lambda m,n: (m+(random()*n))
040| 
041| 
042| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
043| class TestSet (list):
044|     '''Test Set class. Autoloads set of numbers for sort routine.'''
045| 
046|     def __init__ (self, filename):
047|         super().__init__()
048|         self.filename = filename
049| 
050|         # Load test set...
051|         fo = linefile(self.filename)
052|         fo.load()
053|         for num in fo:
054|             self.append(float(num))
055| 
056| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
057| class FrameCapture (list):
058|     '''Frame Capture class. For buffering animation frame data.'''
059| 
060|     def __repr__ (self):
061|         siz = len(self)
062|         return f'FrameCapture<{siz} item{"" if siz==1 else "s"}'
063| 
064|     def add (self, ix, jx, xs):
065|         t = (ix, jx, list(xs))
066|         self.append(t)
067| 
068|     def save (self, filename):
069|         if len(self) == 0:
070|             return
071|         n_xs = len(self[0][2])
072|         fo = tabfile(filename)
073|         fo.hdrs = ['ix','jx'] + [f'x{n}' for n in range(n_xs)]
074|         for ix,jx,xs in self:
075|             fo.data.append([ix, jx]+xs)
076|         fo.save()
077| 
078| 
079| ##================================================================================================##
080| def bubble (xs, capture=False):
081|     '''BUBBLE SORT.'''
082|     cap = FrameCapture()
083| 
084|     def sort_pass ():
085|         # Assume list is sorted...
086|         flag = False
087| 
088|         # Iterate over list (skipping last element)...
089|         for ix in range(len(xs)-1):
090| 
091|             # If next element is less than current element...
092|             if xs[ix+1] < xs[ix]:
093| 
094|                 # Swap current and next elements...
095|                 tmp = xs[ix]
096|                 xs[ix] = xs[ix+1]
097|                 xs[ix+1] = tmp
098| 
099|                 # Flag that we did a swap...
100|                 flag = True
101| 
102|                 if capture: cap.add(ix, ix+1, xs)
103| 
104|         # Return True if we made a swap, else False...
105|         return flag
106| 
107|     if capture: cap.add(-1, -1, xs)
108| 
109|     # Do sort passes until list is sorted...
110|     n_passes = 0
111|     while sort_pass():
112|         n_passes += 1
113|     Log.debug(f'passes: {n_passes}')
114| 
115|     if capture: cap.add(len(xs), len(xs), xs)
116| 
117|     # Return list...
118|     return (xs, cap)
119| 
120| ##================================================================================================##
121| def shaker (xs, capture=False):
122|     '''SHAKER SORT.'''
123|     cap = FrameCapture()
124| 
125|     def sort_pass ():
126|         # Assume list is sorted...
127|         flag = False
128| 
129|         # Iterate forwards over list (skipping last element)...
130|         for ix in range(len(xs)-1):
131|             # If next element is less than current element...
132|             if xs[ix+1] < xs[ix]:
133|                 tmp = xs[ix]
134|                 xs[ix] = xs[ix+1]
135|                 xs[ix+1] = tmp
136|                 flag = True
137| 
138|                 if capture: cap.add(ix, ix+1, xs)
139| 
140|         # Iterate backwards over list (skipping first element)...
141|         for ix in range(len(xs)-1, 1, -1):
142|             # If next element is less than current element...
143|             if xs[ix] < xs[ix-1]:
144|                 tmp = xs[ix]
145|                 xs[ix] = xs[ix-1]
146|                 xs[ix-1] = tmp
147|                 flag = True
148| 
149|                 if capture: cap.add(ix, ix-1, xs)
150| 
151|         # Return True if we made a swap, else False...
152|         return flag
153| 
154|     if capture: cap.add(-1, -1, xs)
155| 
156|     # Do sort passes until list is sorted...
157|     n_passes = 0
158|     while sort_pass():
159|         n_passes += 1
160|     Log.debug(f'passes: {n_passes}')
161| 
162|     if capture: cap.add(len(xs), len(xs), xs)
163| 
164|     # Return list...
165|     return (xs, cap)
166| 
167| ##================================================================================================##
168| def insertion (xs, capture=False):
169|     '''INSERTION SORT.'''
170|     cap = FrameCapture()
171|     if capture: cap.add(-1, -1, xs)
172| 
173|     # Iterate over list (skipping element 0)...
174|     for ix in range(1, len(xs)):
175| 
176|         # Iterate from here back to list start...
177|         jx = ix
178| 
179|         # If lower element is greater than curr element...
180|         while (0 < jx) and (xs[jx] < xs[jx-1]):
181|             if capture: cap.add(ix, jx, xs)
182| 
183|             # Swap lower and current elements...
184|             tmp = xs[jx-1]
185|             xs[jx-1] = xs[jx]
186|             xs[jx] = tmp
187| 
188|             # Next lower element...
189|             jx -= 1
190| 
191|     if capture: cap.add(len(xs), len(xs), xs)
192| 
193|     # Return list...
194|     return (xs, cap)
195| 
196| ##================================================================================================##
197| def selection (xs, capture=False):
198|     '''SELECTION SORT.'''
199|     cap = FrameCapture()
200|     if capture: cap.add(-1, -1, xs)
201| 
202|     # Iterate over list (skipping element 0)...
203|     for ix in range(len(xs)):
204| 
205|         # Assume current item is the minimum item...
206|         mx = ix
207| 
208|         # Test against remaining items to find smallest...
209|         for jx in range(ix+1, len(xs)):
210| 
211|             if xs[jx] < xs[mx]:
212|                 # Found a smaller item...
213|                 mx = jx
214| 
215|         # If our assumption was wrong...
216|         if mx != ix:
217|             # Swap minimum with current item...
218|             tmp = xs[ix]
219|             xs[ix] = xs[mx]
220|             xs[mx] = tmp
221| 
222|             if capture: cap.add(ix, mx, xs)
223| 
224|     if capture: cap.add(len(xs), len(xs), xs)
225| 
226|     # Return list...
227|     return (xs, cap)
228| 
229| ##================================================================================================##
230| def merge (xs, capture=False):
231|     '''MERGE SORT.'''
232|     cap = FrameCapture()
233| 
234|     def merge_combine(left, right):
235|         # Combine two sorted lists...
236|         buff = []
237|         lx = 0
238|         rx = 0
239| 
240|         # While both lists have elements...
241|         while (lx < len(left)) and (rx < len(right)):
242| 
243|             # If left <= right...
244|             if left[lx] <= right[rx]:
245|                 # Buffer the left item...
246|                 buff.append(left[lx])
247|                 # And remove it...
248|                 lx += 1
249|             else:
250|                 # Else right < left, so buffer right item...
251|                 buff.append(right[rx])
252|                 # And remove it...
253|                 rx += 1
254| 
255|         # At least one lists is empty, so put any remainder in the buffer...
256|         # (Possibly both lists are empty at this point.)
257|         buff.extend(left[lx:])
258|         buff.extend(right[rx:])
259| 
260|         # Return the buffer contents...
261|         return buff
262| 
263|     def merge_sort (xs):
264|         Log.trace(f'merge({len(xs)} item{"" if len(xs)==1 else "s"})')
265| 
266|         # If list is empty or has one element, it's already sorted...
267|         if len(xs) <= 1:
268|             return xs
269| 
270|         # Pick the list's midpoint...
271|         mid = len(xs) // 2
272| 
273|         # Return the sorted combination of the two halves...
274|         # NOTE THE DOUBLE RECURSION!
275|         return merge_combine(merge_sort(xs[:mid]), merge_sort(xs[mid:]))
276| 
277|     if capture: cap.add(-1, -1, xs)
278| 
279|     xs = merge_sort(xs)
280| 
281|     if capture: cap.add(len(xs), len(xs), xs)
282| 
283|     # Return list...
284|     return (xs, cap)
285| 
286| ##================================================================================================##
287| def heapsort (xs, capture=False):
288|     '''HEAP SORT.'''
289|     cap = FrameCapture()
290|     if capture: cap.add(-1, -1, xs)
291| 
292|     iLeftChild = lambda n: (2*n)+1
293|     iRightChild = lambda n: (2*n)+2
294|     iParent = lambda n: floor((n-1) / 2)
295| 
296|     # Repair heap whose root element is at index 'start',
297|     # assuming the heaps rooted at its children are valid.
298|     def siftDown(xs, root, end):
299|         '''After sifting down the root, all elements are in heap order.'''
300| 
301|         # Loop while root has at least one child...
302|         while iLeftChild(root) < end:
303| 
304|             # Left child of root...
305|             child = iLeftChild(root)
306| 
307|             # If there is a right child and it is greater...
308|             if (child+1 < end) and (xs[child] < xs[child+1]):
309|                 child += 1
310| 
311|             if xs[root] < xs[child]:
312|                 # Swap root and child...
313|                 tmp = xs[root]
314|                 xs[root] = xs[child]
315|                 xs[child] = tmp
316| 
317|                 if capture: cap.add(root, child, xs)
318| 
319|                 root = child
320|                 # repeat to continue sifting down the child now...
321| 
322|             else:
323|                 # The root holds the largest element. Since we may
324|                 # assume the heaps rooted at the children are valid,
325|                 # this means that we are done.
326|                 return
327| 
328|     def heapify(xs):
329|         ''' Put elements in heap order, in-place.'''
330|         # Find parent of last element...
331|         start = iParent(len(xs)-1) + 1
332|         # (start = first leaf node)
333| 
334|         while 0 < start:
335|             # Look at next previous element...
336|             start -= 1
337| 
338|             # Sift the indexed node down to the proper place such that
339|             # all nodes below start are in heap order...
340|             siftDown(xs, start, len(xs))
341| 
342| 
343|     # Build the heap so that largest value is at the root...
344|     heapify(xs)
345| 
346|     # The following loop maintains the invariants that xs[0:end-1]
347|     # is a heap, and every element xs[end:count-1] beyond end is
348|     # greater than everything before it, i.e. xs[end:count-1] is in sorted order.
349| 
350|     end = len(xs)
351| 
352|     while 1 < end:
353|         # Heap size less one...
354|         end -= 1
355| 
356|         # xs[0] is the root and largest value.
357|         # The swap moves it in front of the sorted elements.
358|         tmp = xs[end]
359|         xs[end] = xs[0]
360|         xs[0] = tmp
361| 
362|         # The swap ruined the heap property, so restore it...
363|         siftDown(xs, 0, end)
364| 
365|     if capture: cap.add(len(xs), len(xs), xs)
366| 
367|     # Return list...
368|     return (xs, cap)
369| 
370| ##================================================================================================##
371| def quicksort (xs, capture=False):
372|     '''QUICK SORT routine. (Yes, it really is this simple.)
372| 
372| Aside, Haskell version:
372|   +------------------------------------------------------------------------------+
372|   | qsort []     = []
372|   | qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger
372|   |                where
372|   |                    smaller = filter (<=x) xs
372|   |                    larger  = filter (>x)  xs
372|   | {{x is must be distinct from xs; how does passed <list> become x:xs?}}
372|   +------------------------------------------------------------------------------+
372| 
372| '''

373|     cap = FrameCapture()
374| 
375|     def qsort (xs):
376|         Log.trace(f'qsort({len(xs)} item{"" if len(xs)==1 else "s"})')
377| 
378|         # No need to sort single items or empty lists...
379|         if len(xs) < 2:
380|             return xs
381| 
382|         # If list has two items, simply compare them...
383|         if len(xs) == 2:
384|             if xs[0] < xs[1]:
385|                 # The two are already sorted...
386|                 return xs
387| 
388|             # The two are out of order, return reverse order...
389|             swap = [xs[1], xs[0]]
390|             return swap
391| 
392|         # Pick an item from the list...
393|         # (Ideal would be to take the mean, but that requires an iteration.)
394|         # ((We might try a random point.))
395|         m = xs[0]
396|         Log.trace(f'pivot-point: {m}')
397| 
398|         # Divide list into two halves...
399|         smaller = [x for x in xs[1:] if x <= m]
400|         larger  = [x for x in xs[1:] if m < x]
401|         Log.trace(f'smaller-items: {len(smaller)}; larger-items: {len(larger)}')
402| 
403|         # Recurse on the halves and return the result...
404|         # NOTE THE DOUBLE RECURSION!
405|         return qsort(smaller) +[m]+ qsort(larger)
406| 
407|     if capture: cap.add(-1, -1, xs)
408| 
409|     xs = qsort(xs)
410| 
411|     if capture: cap.add(len(xs), len(xs), xs)
412| 
413|     # Return list...
414|     return (xs, cap)
415| 
416| ##================================================================================================##
417| def shellsort (xs, capture=False):
418|     '''SHELL SORT.'''
419|     cap = FrameCapture()
420|     if capture: cap.add(-1, -1, xs)
421| 
422|     # Ciura gap sequence
423|     gaps = [701, 301, 132, 57, 23, 10, 4, 1]
424| 
425|     # Start with the largest gap and work down to a gap of 1
426|     # similar to insertion sort but instead of 1, gap is being used in each step
427|     for gap in gaps:
428| 
429|         # Do a gapped insertion sort for every element in gaps
430|         # Each loop leaves a[0..gap-1] in gapped order
431|         for ix in range(gap, len(xs)):
432| 
433|             # Save xs[ix] in temp to make a hole at xs[ix]...
434|             tmp = xs[ix]
435| 
436|             # Shift earlier gap-sorted elements up to correct location for xs[ix] is found
437|             jx = ix
438|             while (gap <= jx) and (tmp < xs[jx-gap]):
439|                 xs[jx] = xs[jx-gap]
440|                 jx -= gap
441| 
442|                 if capture: cap.add(ix, jx, xs)
443| 
444|             # put temp (the original a[i]) in its correct location
445|             xs[jx] = tmp
446| 
447|     if capture: cap.add(len(xs), len(xs), xs)
448| 
449|     # Return list...
450|     return (xs, cap)
451| 
452| 
453| ##================================================================================================##
454| def do_sort_routine (sort_function, **kwargs):
455|     """General Sort Function. Requires 'which sort' information."""
456|     title = KWARG('title', 'Sort', str, kwargs)
457|     fpath = KWARG('fpath', DataPath, str, kwargs)
458|     fname = KWARG('fname', 'sort.list', str, kwargs)
459|     dpath = KWARG('dpath', DataPath, str, kwargs)
460|     dname = KWARG('dname', '', str, kwargs)
461|     opath = KWARG('opath', DataPath, str, kwargs)
462|     oname = KWARG('oname', 'sort.tab', str, kwargs)
463|     count = KWARG('n'    , DefaultCount, int, kwargs)
464|     vmin  = KWARG('lo'   , DefaultLoVal, float, kwargs)
465|     vmax  = KWARG('hi'   , DefaultHiVal, float, kwargs)
466|     cap   = KWARG('cap'  , 0, int, kwargs)
467|     Log.info('SORT-ROUTINE:: %s' % str(list(kwargs.keys())))
468|     Log.debug(f'{title=}')
469|     Log.debug(f'F={fpath}\\{fname}')
470|     Log.debug(f'D={dpath}\\{dname}')
471|     Log.debug(f'O={opath}\\{oname}')
472|     Log.debug(f'{count=}')
473|     Log.debug(f'{vmin=}')
474|     Log.debug(f'{vmax=}')
475|     Log.debug(f'{cap=}')
476|     Log.info()
477|     print(title)
478| 
479|     def is_sorted (xs):
480|         '''Test if list is sorted.'''
481|         for a,b in zip(xs[:-1], xs[1:]):
482|             if b < a:
483|                 return False
484|         return True
485| 
486|     # If a test-set name was provided...
487|     if 0 < len(dname):
488|         # Load list of numbers to sort...
489|         fn = path.join(dpath,dname) if dpath else dname
490|         nums = TestSet(fn)
491|         count = len(nums)
492|     else:
493|         # Otherwise, generate a list of random numbers to sort...
494|         nums = [RandNum(vmin, vmax) for _ in range(count)]
495| 
496|     # Keep a copy of the original list...
497|     nums_orig = list(nums)
498| 
499|     Log.info(f'{title} {count:,} item{"" if count==1 else "s"}')
500|     Log.info(f'item-range: {vmin} to {vmax+vmin}')
501| 
502|     # SORT LIST USING SOME SORT ROUTINE...
503|     t0 = perf_counter_ns()
504|     nums,frms = sort_function(nums, capture=cap)
505| 
506|     # Done! Capture timing...
507|     tt = (perf_counter_ns() - t0) / 1e9
508|     ts = f'sort-time: {tt:.6f} seconds'
509|     Log.info(ts)
510|     Log.info()
511|     print(ts)
512|     print()
513| 
514|     # Make sure we didn't lose or gain any list elements...
515|     if len(nums_orig) != len(nums):
516|         RuntimeError(f'Mismatch in before and after lengths: {len(nums_orig)}!={len(nums)}')
517| 
518|     # Make sure list is truly sorted...
519|     if not is_sorted(nums):
520|         RuntimeError('List was not sorted.')
521| 
522|     # Save the frames data...
523|     fn = path.join(opath,oname) if opath else oname
524|     frms.save(fn)
525| 
526|     # Save the results file...
527|     fn = path.join(fpath,fname) if fpath else fname
528|     fo = linefile(fn)
529|     fo.add(f'{title} ({count} item{"" if count==1 else "s"})')
530|     fo.add(ts)
531|     fo.add()
532|     for ix,a,b in zip(RowNum(1), nums_orig, nums):
533|         fo.add(f'{ix:04d}: {a:+13.9f} {b:+13.9f}')
534|     fo.add()
535|     fo.save()
536| 
537|     # Return sorted-list, original-list, secs-taken, frames...
538|     return (nums, nums_orig, tt, frms)
539| 
540| 
541| ##================================================================================================##
542| def do_bubble_sort (**kwargs):
543|     """CMND: BUBBLE SORT."""
544|     Log.info('BUBBLE-SORT:: %s' % str(list(kwargs.keys())))
545|     kwargs['title'] = 'Bubble Sort'
546|     kwargs['fname'] = 'bubblesort.list'
547|     kwargs['oname'] = 'bubblesort.tab'
548| 
549|     do_sort_routine(bubble, **kwargs)
550| 
551|     Log.info()
552|     return 'Done'
553| ##================================================================================================##
554| def do_shaker_sort (**kwargs):
555|     """CMND: SHAKER SORT."""
556|     Log.info('SHAKER-SORT:: %s' % str(list(kwargs.keys())))
557|     kwargs['title'] = 'Shaker Sort'
558|     kwargs['fname'] = 'shakersort.list'
559|     kwargs['oname'] = 'shakersort.tab'
560| 
561|     do_sort_routine(shaker, **kwargs)
562| 
563|     Log.info()
564|     return 'Done'
565| ##================================================================================================##
566| def do_insertion_sort (**kwargs):
567|     """CMND: INSERTION SORT."""
568|     Log.info('INSERTION-SORT:: %s' % str(list(kwargs.keys())))
569|     kwargs['title'] = 'Insertion Sort'
570|     kwargs['fname'] = 'insertionsort.list'
571|     kwargs['oname'] = 'insertionsort.tab'
572| 
573|     do_sort_routine(insertion, **kwargs)
574| 
575|     Log.info()
576|     return 'Done'
577| ##================================================================================================##
578| def do_selection_sort (**kwargs):
579|     """CMND: SELECTION SORT."""
580|     Log.info('SELECTION-SORT:: %s' % str(list(kwargs.keys())))
581|     kwargs['title'] = 'Selection Sort'
582|     kwargs['fname'] = 'selectionsort.list'
583|     kwargs['oname'] = 'selectionsort.tab'
584| 
585|     do_sort_routine(selection, **kwargs)
586| 
587|     Log.info()
588|     return 'Done'
589| ##================================================================================================##
590| def do_merge_sort (**kwargs):
591|     """CMND: MERGE SORT."""
592|     Log.info('MERGE-SORT:: %s' % str(list(kwargs.keys())))
593|     kwargs['title'] = 'Merge Sort'
594|     kwargs['fname'] = 'mergesort.list'
595|     kwargs['oname'] = 'mergesort.tab'
596| 
597|     do_sort_routine(merge, **kwargs)
598| 
599|     Log.info()
600|     return 'Done'
601| ##================================================================================================##
602| def do_heap_sort (**kwargs):
603|     """CMND: HEAP SORT."""
604|     Log.info('HEAP-SORT:: %s' % str(list(kwargs.keys())))
605|     kwargs['title'] = 'Heap Sort'
606|     kwargs['fname'] = 'heapsort.list'
607|     kwargs['oname'] = 'heapsort.tab'
608| 
609|     do_sort_routine(heapsort, **kwargs)
610| 
611|     Log.info()
612|     return 'Done'
613| ##================================================================================================##
614| def do_quick_sort (**kwargs):
615|     """CMND: QUICK SORT."""
616|     Log.info('QUICK-SORT:: %s' % str(list(kwargs.keys())))
617|     kwargs['title'] = 'Quick Sort'
618|     kwargs['fname'] = 'quicksort.list'
619|     kwargs['oname'] = 'quicksort.tab'
620| 
621|     do_sort_routine(quicksort, **kwargs)
622| 
623|     Log.info()
624|     return 'Done'
625| ##================================================================================================##
626| def do_shell_sort (**kwargs):
627|     """CMND: SHELL SORT."""
628|     Log.info('SHELL-SORT:: %s' % str(list(kwargs.keys())))
629|     kwargs['title'] = 'Shell Sort'
630|     kwargs['fname'] = 'shellsort.list'
631|     kwargs['oname'] = 'shellsort.tab'
632| 
633|     do_sort_routine(shellsort, **kwargs)
634| 
635|     Log.info()
636|     return 'Done'
637| 
638| ##================================================================================================##
639| def do_all (**kwargs):
640|     """CMND: Do all sorts."""
641|     Log.info('ALL:: %s' % str(list(kwargs.keys())))
642| 
643|     kwargs['title'] = 'Bubble Sort'
644|     kwargs['fname'] = 'bubblesort.list'
645|     kwargs['oname'] = 'bubblesort.tab'
646|     do_sort_routine(bubble, **kwargs)
647| 
648|     kwargs['title'] = 'Shaker Sort'
649|     kwargs['fname'] = 'shakersort.list'
650|     kwargs['oname'] = 'shakersort.tab'
651|     do_sort_routine(shaker, **kwargs)
652| 
653|     kwargs['title'] = 'Insertion Sort'
654|     kwargs['fname'] = 'insertionsort.list'
655|     kwargs['oname'] = 'insertionsort.tab'
656|     do_sort_routine(insertion, **kwargs)
657| 
658|     kwargs['title'] = 'Selection Sort'
659|     kwargs['fname'] = 'selectionsort.list'
660|     kwargs['oname'] = 'selectionsort.tab'
661|     do_sort_routine(selection, **kwargs)
662| 
663|     kwargs['title'] = 'Merge Sort'
664|     kwargs['fname'] = 'mergesort.list'
665|     kwargs['oname'] = 'mergesort.tab'
666|     do_sort_routine(merge, **kwargs)
667| 
668|     kwargs['title'] = 'Heap Sort'
669|     kwargs['fname'] = 'heapsort.list'
670|     kwargs['oname'] = 'heapsort.tab'
671|     do_sort_routine(heapsort, **kwargs)
672| 
673|     kwargs['title'] = 'Quick Sort'
674|     kwargs['fname'] = 'quicksort.list'
675|     kwargs['oname'] = 'quicksort.tab'
676|     do_sort_routine(quicksort, **kwargs)
677| 
678|     kwargs['title'] = 'Shell Sort'
679|     kwargs['fname'] = 'shellsort.list'
680|     kwargs['oname'] = 'shellsort.tab'
681|     do_sort_routine(shellsort, **kwargs)
682| 
683|     Log.info()
684|     return 'Done'
685| 
686| ##================================================================================================##
687| def do_generate_test_set (**kwargs):
688|     """CMND: Generate a test set of numbers for sorting."""
689|     dpath = KWARG('dpath', BasePath, str, kwargs)
690|     dname = KWARG('dname', 'sortset.list', str, kwargs)
691|     count = KWARG('n'    , DefaultCount, int, kwargs)
692|     vmin  = KWARG('lo'   , DefaultLoVal, int, kwargs)
693|     vmax  = KWARG('hi'   , DefaultHiVal, int, kwargs)
694|     Log.info('GENERATE-TEST-SET:: %s' % str(list(kwargs.keys())))
695|     Log.debug(f'{dpath=}')
696|     Log.debug(f'{dname=}')
697|     Log.debug(f'{count=}')
698|     Log.debug(f'{vmin=}')
699|     Log.debug(f'{vmax=}')
700|     Log.info()
701| 
702|     # Generate a list of random numbers to sort...
703|     fn = path.join(dpath,dname) if dpath else dname
704|     fo = linefile(fn)
705|     fo.data = [str(RandNum(vmin, vmax)) for _ in range(count)]
706|     fo.save()
707| 
708|     Log.info()
709|     return 'Done'
710| 
711| ##================================================================================================##
712| def do_animation (**kwargs):
713|     """CMND: Generate PNG animation frames from a sort TAB file."""
714|     fpath = KWARG('fpath', DataPath, str, kwargs)
715|     fname = KWARG('fname', 'sort.tab', str, kwargs)
716|     apath = KWARG('apath', AnimPath, str, kwargs)
717|     count = KWARG('n'    , 100, int, kwargs)
718|     Log.info('ANIMATION:: %s' % str(list(kwargs.keys())))
719|     Log.debug(f'{fpath=}')
720|     Log.debug(f'{fname=}')
721|     Log.debug(f'{apath=}')
722|     Log.debug(f'{count=}')
723|     Log.info()
724|     dims = (1920, 1080)
725|     view = ((0, count),  (0, 100))
726| 
727|     fn = path.join(fpath,fname) if fpath else fname
728|     fo = tabfile(fn)
729|     fo.load()
730|     Log.info(fo)
731|     Log.info(fo.hdrs)
732|     Log.info()
733| 
734|     for rx,row in enumerate(fo):
735|         ix = int(row[0])
736|         jx = int(row[1])
737|         xs = [float(x) for x in row[2:]]
738|         Log.debug(f'F{rx:04d}: {ix:2d} {jx:2d} ({len(xs)})')
739| 
740|         im = Canvas(dims, view)
741| 
742|         for xx,x in enumerate(xs):
743|             bg = (255,255,0) if xx==ix else ((255,0,0) if xx==jx else (63,127,255))
744|             p1 = (xx, x)
745|             p2 = (xx+1, 0)
746|             Log.debug(f'{x=}, {p1=}, {p2=}')
747| 
748|             im.box(p1, p2, fg=(0,0,0), bg=bg, lw=1)
749| 
750|         fn = path.join(apath, f'img_{rx:04d}.png')
751|         im.save(fn)
752| 
753|     Log.debug()
754| 
755|     Log.info()
756|     return 'Done'
757| 
758| ##================================================================================================##
759| def do_test (**kwargs):
760|     """CMND: Do a test."""
761|     fpath = KWARG('fpath', BasePath, str, kwargs)
762|     fname = KWARG('fname', 'test.out', str, kwargs)
763|     oname = KWARG('oname', 'test.tab', str, kwargs)
764|     count = KWARG('n'    , DefaultCount, int, kwargs)
765|     vmin  = KWARG('lo'   , DefaultLoVal, int, kwargs)
766|     vmax  = KWARG('hi'   , DefaultHiVal, int, kwargs)
767|     cap   = KWARG('cap'  , 0, int, kwargs)
768|     Log.info('TEST:: %s' % str(list(kwargs.keys())))
769|     Log.debug(f'{fpath=}')
770|     Log.debug(f'{fname=}')
771|     Log.debug(f'{oname=}')
772|     Log.debug(f'{count=}')
773|     Log.debug(f'{vmin=}')
774|     Log.debug(f'{vmax=}')
775|     Log.debug(f'{cap=}')
776|     Log.info()
777|     Log.info()
778|     return 'Done'
779| ####################################################################################################
780| def dispatch (cmd, **kwargs):
781|     """Dispatch to a module function based on CMD."""
782|     Log.info(f'CMD: {cmd}')
783|     for kw in kwargs:
784|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
785|     Log.info()
786|     if cmd == 'all': return do_all(**kwargs)
787|     if cmd == 'pngs': return do_animation(**kwargs)
788| 
789|     if cmd == 'bubble': return do_bubble_sort(**kwargs)
790|     if cmd == 'shaker': return do_shaker_sort(**kwargs)
791|     if cmd == 'insert': return do_insertion_sort(**kwargs)
792|     if cmd == 'select': return do_selection_sort(**kwargs)
793|     if cmd == 'merge' : return do_merge_sort(**kwargs)
794|     if cmd == 'heap'  : return do_heap_sort(**kwargs)
795|     if cmd == 'qsort' : return do_quick_sort(**kwargs)
796|     if cmd == 'shell' : return do_shell_sort(**kwargs)
797| 
798|     if cmd == 'tset': return do_generate_test_set(**kwargs)
799|     if cmd == 'test': return do_test(**kwargs)
800|     return 'Nothing to do!'
801| ####################################################################################################
802| if __name__ == '__main__':
803|     print('autorun: %s' % argv[0])
804|     #Log.start(path.join(BasePath,'sort_routines.log'))
805|     Log.start(path.join(BasePath,LogFilenameTimestamp('sort_routines_%s.log')))
806|     Log.level(trace())
807|     Log.info(argv[0])
808|     Log.info()
809|     cmd = argv[1] if 1 < len(argv) else CMND
810|     kwargs = ARGS
811|     for a in argv[2:]:
812|         nv = a.split('=', 1)
813|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
814|     try:
815|         print(f'CMD: {cmd}')
816|         print()
817|         obj = dispatch(cmd, **kwargs)
818|         print()
819|         print(obj)
820|         Log.info()
821|         Log.info(obj)
822|     except:
823|         etype, evalue, tb = exc_info()
824|         ts = extract_tb(tb)
825|         Log.error()
826|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
827|         Log.error()
828|         for t in ts[-5:]:
829|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
830|             Log.error(' %s' % t[3])
831|             Log.error()
832|         raise
833|     finally:
834|         Log.end()
835| ####################################################################################################
836| '''eof'''
837|