evolution.html


001| ####################################################################################################
002| from sys import argv, exc_info
003| from traceback import extract_tb
004| from os import path
005| from time import process_time_ns
006| from random import randint
007| import matplotlib.pyplot as plt
008| from matplotlib.ticker import MultipleLocator,FormatStrFormatter, NullLocator,NullFormatter
009| from files import linefile, tabfile
010| from logger import logger,info,debug,trace, LogFilenameTimestamp
011| from webpage import KWARG
012| ####################################################################################################
013| Log = logger('EVOLVE')
014| BasePath = r'C:\CJS\prj\Python\app\arc\evo'
015| DataPath = path.join(BasePath, 'out')
016| ImgsPath = path.join(BasePath, 'img')
017| 
018| Target0 = r'Science Fiction'
019| Target1 = r'It takes a long time to understand nothing.'
020| Target2 = r'Some subjects are so serious that one can only joke about them.'
021| Target3 = r"I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me."
022| Target4 = r"You can't be a real country unless you have a beer and an airline. It helps if you have some kind of a football team, or some nuclear weapons, but at the very least you need a beer."
023| Target5 = r'The Terminal Experiment, Robert J. Forward, 2012'
024| Target6 = r'My dog Sam was a black Lab.'
025| Target7 = r"Last post I wrote about a simple substitution cipher Robert J. Sawyer used in his 2012 science fiction political thriller, Triggers. This post I'm writing about a completely different cool thing from a different book by Sawyer, The Terminal Experiment. Published in 1995, it's one of his earlier novels. It won both a Nebula and a Hugo."
026| Targets = [Target0, Target1, Target2, Target3, Target4, Target5, Target6, Target7]
027| 
028| CMND = '' ## s[0,1] c[1-4] csm crs test
029| ARGS = {
030|     'targ': Target0,
031|     'ftag': '-t0-m1',
032|     'gens': '99999',
033|     'offs': '50',
034|     'mode': '1',
035|     'delt': '15',
036|     'muts': '1',
037|     'nmbr': '42',
038|     'loop': '7',
039|     #'loop': '150', 'jump': '1',
040|     'xtk0': '100', 'xtk1': '50',
041|     'ytk0': '500', 'ytk1': '100',
042|     #'bars': '20', 'jump': '9', # 180, T4
043|     #'xtk0': '9', 'xtk1': '1',
044|     #'bars': '16', 'jump': '4', # 64, T2
045|     #'xtk0': '4', 'xtk1': '1',
046|     'dots': '100',
047|     #'fname': 'evolve',
048|     'fpath': BasePath,
049|     'dpath': BasePath,
050|     'ipath': BasePath,
051| }
052| 
053| SPC = ' '
054| A0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
055| A1 = 'abcdefghijklmnopqrstuvwxyz'
056| DIG = '0123456789'
057| SY1 = ',.?!'
058| SY2 = '\'\"-()='
059| 
060| GetAlphabet = lambda u,l,d,s1,s2:(SPC+(A0 if u else'')+(A1 if l else'')+(DIG if d else'')+(SY1 if s1 else'')+(SY2 if s2 else''))
061| GetFullAlphabet = lambda: ''.join([chr(n) for n in range(0x20, 0x7f)])
062| 
063| Alphabet0 = GetAlphabet(1,1,1,1,0)
064| Alphabet1 = GetFullAlphabet()
065| Alphabet = Alphabet1
066| FindChar = lambda ch: Alphabet.index(ch)
067| RandChar = lambda: Alphabet[randint(0,len(Alphabet)-1)]
068| RandString = lambda n: ''.join([RandChar() for _ in range(n)])
069| 
070| TimeBuckets = {
071|     'Total': [0, 0, 0],
072|     'generate_random_string': [1, 0, 0],
073|     'compare_string': [2, 0, 0],
074|     'mutate_string': [3, 0, 0],
075|     'mutate_char': [4, 0, 0],
076| }
077| 
078| ##================================================================================================##
079| class TargetString ():
080|     """Target String class for evolution function."""
081| 
082|     def __init__ (self, target, offspring=42, mode=1, delta=12, mutations=1):
083|         self.target = str(target)
084|         self.n = len(self.target)
085|         self.offspring = offspring
086|         self.mode = mode
087|         self.delta = delta
088|         self.mutations = mutations
089|         # Initialize with a random string of length N...
090|         self.current = RandString(self.n)
091|         self.kids = []
092|         self.scores = []
093|         self.dbuff = [(self(), self.current, 0)]
094| 
095|     def vdiff (self):
096|         """Return a vector of differences between target and current strings."""
097|         return [abs(FindChar(c0)-FindChar(c1)) for c0,c1 in zip(self.target,self.current)]
098| 
099|     def distance (self):
100|         """Return a distance value between the target and current strings. Zero=MATCH!"""
101|         deltas = self.vdiff()
102|         # Distance is the sum of the deltas...
103|         return sum(deltas)
104| 
105|     def spawn (self):
106|         """Spawn a set of offspring and select a winner."""
107|         self.kids = [self.mutate() for _ in range(self.offspring)]
108|         self.kids.append(self.current)
109|         # Score each child...
110|         self.scores = [self(kid) for kid in self.kids]
111|         # Pick the winner...
112|         best_score = min(self.scores)
113|         which_kid = self.scores.index(best_score)
114|         winner = self.kids[which_kid]
115|         datum = (best_score, winner, which_kid)
116|         # Add winner to DataBuffer...
117|         self.dbuff.append(datum)
118|         return datum
119| 
120|     def mutate (self):
121|         """Return a mutated version of the current string."""
122|         ss = list(self.current)
123|         # For each mutation of the string (usually just one)...
124|         for _ in range(self.mutations):
125|             # Select a random character position in the string...
126|             ix = randint(0,len(ss)-1)
127|             # And replace it with a mutated character...
128|             ss[ix] = self.mutate_char(ss[ix])
129|         # Convert the modified list to a string...
130|         return ''.join(ss)
131| 
132|     def mutate_char (self, ch):
133|         """Given a character, return a mutated version."""
134|         # Mode1: Completely random character...
135|         if self.mode == 1:
136|             return RandChar()
137|         # Mode2: Next or previous character...
138|         cx = FindChar(ch)
139|         if self.mode == 2:
140|             cx2 = ((cx+1) if randint(0,1) else (cx-1)) % len(Alphabet)
141|             return Alphabet[cx2]
142|         # Mode3: Delta change...
143|         if self.mode == 3:
144|             dx = randint(1,self.delta)
145|             cx2 = ((cx+dx) if randint(0,1) else (cx-dx)) % len(Alphabet)
146|             return Alphabet[cx2]
147|         # Mode0: No change...
148|         return ch
149| 
150|     def __call__ (self, other=None):
151|         """Compare target string with another string (default=current)."""
152|         if other is None:
153|             # If no other string provided, use the current string...
154|             return compare_string(self.target, self.current)
155|         # Compare target with other string...
156|         return compare_string(self.target, other)
157| 
158|     def __bool__ (self):
159|         """Instance is TRUE if current string matches target string."""
160|         return (self.distance() == 0)
161| 
162|     def __len__ (self):
163|         """Length is the length of the target/current string."""
164|         return self.n
165| 
166|     def __str__ (self):
167|         """String version is just the current string."""
168|         return self.current
169| 
170| 
171| ##================================================================================================##
172| def generate_random_string (n):
173|     """Return a random string from Alphabet of length N."""
174|     t0 = process_time_ns()
175|     cs = [RandChar() for _ in range(n)]
176|     s = ''.join(cs)
177|     t1 = process_time_ns()
178|     TimeBuckets['generate_random_string'][1] += (t1 - t0)
179|     TimeBuckets['generate_random_string'][2] += 1
180|     return s
181| 
182| ##================================================================================================##
183| def compare_string (s0, s1):
184|     """Return a number indicating how different two equal-length strings are."""
185|     t0 = process_time_ns()
186|     # Generate a list of character deltas...
187|     deltas = [abs(FindChar(c0)-FindChar(c1)) for c0,c1 in zip(s0,s1)]
188|     # Distance is the sum of the deltas...
189|     diff = sum(deltas)
190|     # Record the processing time...
191|     t1 = process_time_ns()
192|     TimeBuckets['compare_string'][1] += (t1 - t0)
193|     TimeBuckets['compare_string'][2] += 1
194|     return diff
195| 
196| ##================================================================================================##
197| def _mutate_char (ch, mode=1, delta=5):
198|     """Given a character, return a mutated version."""
199|     # Mode1: Completely random character...
200|     if mode == 1:
201|         return RandChar()
202|     # Mode2: Next or previous character...
203|     cx = FindChar(ch)
204|     if mode == 2:
205|         cx2 = ((cx+1) if randint(0,1) else (cx-1)) % len(Alphabet)
206|         return Alphabet[cx2]
207|     # Mode3: Delta change...
208|     if mode == 3:
209|         dx = randint(1,delta)
210|         cx2 = ((cx+dx) if randint(0,1) else (cx-dx)) % len(Alphabet)
211|         return Alphabet[cx2]
212|     # Mode0: No change...
213|     return ch
214| ##================================================================================================##
215| def mutate_char (ch, mode=1, delta=5):
216|     """Given a character, return a mutated version. (Instrumented)"""
217|     t0 = process_time_ns()
218|     ch = _mutate_char(ch, mode=mode, delta=delta)
219|     # Record the processing time...
220|     t1 = process_time_ns()
221|     TimeBuckets['mutate_char'][1] += (t1 - t0)
222|     TimeBuckets['mutate_char'][2] += 1
223|     return ch
224| 
225| ##================================================================================================##
226| def mutate_string (s, mutations=1, mode=1, delta=5):
227|     """Given a string, return a mutated version."""
228|     t0 = process_time_ns()
229|     # Convert the string to a list...
230|     ss = list(s)
231|     # For each mutation of the string (usually just one)...
232|     for _ in range(mutations):
233|         # Select a random character position in the string...
234|         ix = randint(0,len(ss)-1)
235|         # And replace it with a mutated character...
236|         ss[ix] = mutate_char(ss[ix], mode=mode, delta=delta)
237|     # Convert the modified list to a string...
238|     rs = ''.join(ss)
239|     # Record the processing time...
240|     t1 = process_time_ns()
241|     TimeBuckets['mutate_string'][1] += (t1 - t0)
242|     TimeBuckets['mutate_string'][2] += 1
243|     return rs
244| 
245| ##================================================================================================##
246| def evolve_string (target, **kwargs):
247|     """Evolve a random start string to a target string."""
248|     generations = KWARG('generations', 100, int, kwargs)
249|     offspring = KWARG('offspring', 25, int, kwargs)
250|     mutations = KWARG('mutations', 1, int, kwargs)
251|     mode = KWARG('mode', 1, int, kwargs)
252|     delta = KWARG('delta', 12, int, kwargs)
253|     dots = KWARG('dots', 1000, int, kwargs)
254|     Log.info('evolve-string:: %s' % str(list(kwargs.keys())))
255|     Log.info('max-generations=%d' % generations)
256|     Log.info('offspring-per-gen=%d' % offspring)
257|     Log.info('mutation-mode=%d' % mode)
258|     Log.info('mutation-delta=%d' % delta)
259|     Log.info('mutations-per-str=%d' % mutations)
260|     Log.info('display-freq=%d' % dots)
261|     Log.info('target=|%s|' % target)
262|     Log.info()
263| 
264|     t0 = process_time_ns()
265|     # String evolution data buffer...
266|     start = generate_random_string(len(target))
267|     curr = start
268|     dbuff = [(compare_string(target,start), start, 0)]
269|     for gx in range(generations):
270|         # Create next generation...
271|         kids = [mutate_string(curr,mutations=mutations,mode=mode,delta=delta) for _ in range(offspring)]
272|         kids.append(curr)
273|         # Score each child...
274|         scores = [compare_string(target,kid) for kid in kids]
275|         # Pick the winner...
276|         best_score = min(scores)
277|         which_kid = scores.index(best_score)
278|         winner = kids[which_kid]
279|         curr = winner
280|         dbuff.append([best_score, winner, which_kid+1])
281|         # If we found a perfect match, we're done...
282|         if best_score == 0:
283|             break
284|         if 0==(gx % dots):
285|             s = '%8d: %s' % (gx,curr)
286|             print(s)
287|             Log.info(s)
288|     s = '%8d: %s' % (gx+1,curr)
289|     print(s)
290|     print()
291|     Log.info(s)
292|     Log.info()
293|     # Record the processing time...
294|     t1 = process_time_ns()
295|     TimeBuckets['Total'][1] += (t1 - t0)
296|     TimeBuckets['Total'][2] = gx+1
297| 
298|     # Statistics...
299|     stats = []
300|     stats.append('TARGET: %s' % target)
301|     if best_score == 0:
302|         stats.append('>>> SUCCESS in %d Generations! <<<' % (gx+1))
303|     else:
304|         stats.append('### Did Not Evolve to Target! ###')
305|     stats.append('')
306|     stats.append('Start-Final Delta: %d' % compare_string(start,curr))
307|     stats.append('')
308|     stats.append('START: %s (%d)' % (start,compare_string(target,start)))
309|     stats.append('FINAL: %s (%d)' % (curr,compare_string(target,curr)))
310|     stats.append('')
311|     stats.append('Max Generations: %s' % generations)
312|     stats.append('Offspring/Generation: %d (mode %d)' % (offspring,mode))
313|     stats.append('Mutations/Offspring: %d' % mutations)
314|     if mode==3:
315|         stats.append('Mode3-Mutation-Delta: %d' % delta)
316|     stats.append('')
317|     for tx,tn in enumerate(sorted(TimeBuckets, key=lambda k:TimeBuckets[k][0])):
318|         t = TimeBuckets[tn]
319|         stats.append('%d: %8.3f secs, %d calls (%s)' % (tx, t[1]/pow(10,9), t[2], tn))
320|     stats.append('')
321|     stats.append('Last set of offspring:')
322|     for ix,kid in enumerate(kids):
323|         stats.append('%3d: %s (%d)' % (ix+1,kid,compare_string(target,kid)))
324|     stats.append('')
325| 
326|     return (dbuff,stats)
327| 
328| 
329| ##================================================================================================##
330| def do_string_0 (**kwargs):
331|     """Basic String Evolution function using TargetString class."""
332|     fpath = KWARG('fpath', BasePath, str, kwargs)
333|     dpath = KWARG('dpath', DataPath, str, kwargs)
334|     fname = KWARG('fname', 'evolution.out', str, kwargs)
335|     ftag = KWARG('ftag', '', str, kwargs)
336|     targ = KWARG('targ', Target0, str, kwargs)
337|     gens = KWARG('gens', 5000, int, kwargs)
338|     offs = KWARG('offs', 50, int, kwargs)
339|     mode = KWARG('mode', 1, int, kwargs)
340|     delt = KWARG('delt', 25, int, kwargs)
341|     dots = KWARG('dots', 500, int, kwargs)
342|     dataname = path.join(dpath,'%s%s.tab' % (fname,ftag))
343|     statname = path.join(dpath,'%s%s.out' % (fname,ftag))
344|     Log.info('string-0:: %s' % str(list(kwargs.keys())))
345|     Log.info('fpath="%s"' % fpath)
346|     Log.info('dpath="%s"' % dpath)
347|     Log.info('fname="%s"' % fname)
348|     Log.info('ftag="%s"' % ftag)
349|     Log.info('stat-filename="%s"' % statname)
350|     Log.info('data-filename="%s"' % dataname)
351|     Log.info('max-generations=%d' % gens)
352|     Log.info('offspring-per-gen=%d' % offs)
353|     Log.info('mutation-mode=%d' % mode)
354|     Log.info('mutation-delta=%d' % delt)
355|     Log.info('display-freq=%d' % dots)
356|     Log.info('target=|%s|' % targ)
357|     Log.info()
358| 
359|     tobj = TargetString(targ, offspring=offs, mode=mode, delta=delt)
360|     Log.info(tobj)
361|     Log.info()
362| 
363|     for gx in range(gens):
364|         d = tobj.spawn()
365|         Log.info(d)
366|         tobj.current = d[1]
367|         if tobj:
368|             break
369|         if 0==(gx % dots):
370|             print('%8d: %s' % (gx,tobj.current))
371|     print('%8d: %s' % (gx+1,tobj.current))
372|     print()
373|     Log.info()
374|     Log.info(':OFFSPRING:')
375|     for kid in tobj.kids:
376|         Log.info(kid)
377|     Log.info()
378|     Log.info(':DATABUFF:')
379|     for datum in tobj.dbuff:
380|         Log.info(datum)
381|     Log.info('::')
382|     Log.info()
383|     return 'Done'
384| 
385| ##================================================================================================##
386| def do_string_1 (**kwargs):
387|     """Evolve a given string with a given configuration. Make data files!"""
388|     fpath = KWARG('fpath', BasePath, str, kwargs)
389|     dpath = KWARG('dpath', DataPath, str, kwargs)
390|     fname = KWARG('fname', 'evolution', str, kwargs)
391|     ftag = KWARG('ftag', '', str, kwargs)
392|     targ = KWARG('targ', Target0, str, kwargs)
393|     gens = KWARG('gens', 5000, int, kwargs)
394|     offs = KWARG('offs', 50, int, kwargs)
395|     mode = KWARG('mode', 1, int, kwargs)
396|     muts = KWARG('muts', 1, int, kwargs)
397|     delt = KWARG('delt', 25, int, kwargs)
398|     dots = KWARG('dots', 500, int, kwargs)
399|     dataname = path.join(dpath,'%s%s.tab' % (fname,ftag))
400|     statname = path.join(dpath,'%s%s.out' % (fname,ftag))
401|     Log.info('string-1:: %s' % str(list(kwargs.keys())))
402|     Log.info('fpath="%s"' % fpath)
403|     Log.info('dpath="%s"' % dpath)
404|     Log.info('fname="%s"' % fname)
405|     Log.info('ftag="%s"' % ftag)
406|     Log.info('stat-filename="%s"' % statname)
407|     Log.info('data-filename="%s"' % dataname)
408|     Log.info('max-generations=%d' % gens)
409|     Log.info('offspring-per-gen=%d' % offs)
410|     Log.info('mutation-mode=%d' % mode)
411|     Log.info('mutation-delta=%d' % delt)
412|     Log.info('mutations-per-str=%d' % muts)
413|     Log.info('display-freq=%d' % dots)
414|     Log.info('target=|%s|' % targ)
415|     Log.info()
416|     if targ.startswith('/'):
417|         tx = int(targ[1:])
418|         targ = Targets[tx]
419|     print('Target: %d <%s>' % (len(targ),targ))
420|     print()
421|     print('Max Generations: %s' % gens)
422|     print('Offspring/Generation: %d (mode=%d%s)' % (offs,mode,(', delta=%d' % delt)if mode==3 else''))
423|     print('Mutations/Offspring: %d' % muts)
424|     print()
425| 
426|     # Evolve String...
427|     props = dict(generations=gens, offspring=offs, mutations=muts, mode=mode, delta=delt, dots=dots)
428|     dbuff,stats = evolve_string(targ, **props)
429|     Log.info()
430|     for stat in stats:
431|         Log.info(stat)
432|     Log.info()
433|     starts = dbuff[0][1]
434|     print('Start: <%s> (%d)' % (starts,compare_string(targ,starts)))
435|     print()
436| 
437|     # String evolution file...
438|     ft = tabfile(dataname)
439|     ft.hdrs = ['distance','string','index']
440|     ft.data = dbuff
441|     ft.save()
442|     Log.info('wrote: %s' % dataname)
443| 
444|     # Evolution statistics file...
445|     fo = linefile(statname)
446|     fo.data = stats
447|     fo.save()
448|     Log.info('wrote: %s' % statname)
449| 
450|     Log.info()
451|     return 'Done'
452| 
453| ##================================================================================================##
454| def do_string_mutation_chart (**kwargs):
455|     fpath = KWARG('fpath', BasePath, str, kwargs)
456|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
457|     fname = KWARG('fname', 'str-mut', str, kwargs)
458|     ftag = KWARG('ftag', '', str, kwargs)
459|     targ = KWARG('targ', Target0, str, kwargs)
460|     gens = KWARG('gens', 500, int, kwargs)
461|     offs = KWARG('offs', 500, int, kwargs)
462|     mode = KWARG('mode', 1, int, kwargs)
463|     delt = KWARG('delt', 15, int, kwargs)
464|     muts = KWARG('muts', 1, int, kwargs)
465|     dots = KWARG('dots', 100, int, kwargs)
466|     xtk0 = KWARG('xtk0', 500, int, kwargs)
467|     xtk1 = KWARG('xtk1', 100, int, kwargs)
468|     ytk0 = KWARG('ytk0', 500, int, kwargs)
469|     ytk1 = KWARG('ytk1', 100, int, kwargs)
470|     imgw = KWARG('w', 8.8, float, kwargs)
471|     imgh = KWARG('h', 4.0, float, kwargs)
472|     marl = KWARG('ml', 0.09, float, kwargs)
473|     marr = KWARG('mr', 0.99, float, kwargs)
474|     marb = KWARG('mb', 0.17, float, kwargs)
475|     mart = KWARG('mt', 0.93, float, kwargs)
476|     filename = path.join(ipath,'%s%s.png' % (fname,ftag))
477|     Log.info('string-mutation:: %s' % str(list(kwargs.keys())))
478|     Log.info('fpath="%s"' % fpath)
479|     Log.info('ipath="%s"' % ipath)
480|     Log.info('fname="%s"' % fname)
481|     Log.info('ftag="%s"' % ftag)
482|     Log.info('imag-filename="%s"' % filename)
483|     Log.info('max-generations=%d' % gens)
484|     Log.info('offspring-per-gen=%d' % offs)
485|     Log.info('mutation-mode=%d' % mode)
486|     Log.info('mutation-delta=%d' % delt)
487|     Log.info('mutations-per-str=%d' % muts)
488|     Log.info('display-freq=%d' % dots)
489|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
490|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
491|     Log.info('image-size=%d x %d' % (imgw,imgh))
492|     Log.info('margin=%.2f, %.2f, %.2f, %.2f' % (marl,marr,marb,mart))
493|     Log.info('target=|%s|' % targ)
494|     Log.info()
495| 
496|     adjust = lambda n: (n if n < (len(Alphabet)/2) else abs(n-len(Alphabet)))
497|     rand_strs = [mutate_string(targ,muts,mode,delt) for _ in range(offs)]
498|     test_strs = [(ix+1, s, adjust(compare_string(targ,s))) for ix,s in enumerate(rand_strs)]
499| 
500|     min_score = min(test_strs, key=lambda t:t[2])
501|     max_score = max(test_strs, key=lambda t:t[2])
502| 
503|     Log.info('Min-Score: [%3d] (%d) %s' % (min_score[0],min_score[2],min_score[1]))
504|     Log.info('Max-Score: [%3d] (%d) %s' % (max_score[0],max_score[2],max_score[1]))
505|     Log.info()
506|     Log.info('[%4d] %s (%4d)' % (0,targ,0))
507|     for t in test_strs:
508|         Log.info('[%4d] %s (%4d)' % t)
509|     Log.info()
510| 
511|     xs = [t[0] for t in test_strs]
512|     ys = [t[2] for t in test_strs]
513| 
514|     xmin,xmax = 0, len(xs)+1
515|     ymin,ymax = 0, ((max(ys)//10)+1)*10
516| 
517|     fig, ax = plt.subplots()
518|     fig.suptitle('String Mutation Distance from Target', fontweight='bold')
519|     # Horizontal Axis...
520|     ax.set_xlabel('Mutation')
521|     ax.set_xlim(xmin,xmax)
522|     ax.xaxis.set_major_locator(MultipleLocator(xtk0))
523|     ax.xaxis.set_minor_locator(MultipleLocator(xtk1))
524|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
525|     ax.xaxis.set_minor_formatter(NullFormatter())
526|     for tick in ax.xaxis.get_major_ticks():
527|         tick.label1.set_rotation('vertical')
528|         tick.label1.set_size(9)
529|     # Vertical Axis...
530|     ax.set_ylabel('Distance')
531|     ax.set_ylim(ymin,ymax)
532|     ax.yaxis.set_major_locator(MultipleLocator(ytk0))
533|     ax.yaxis.set_minor_locator(MultipleLocator(ytk1))
534|     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
535|     ax.yaxis.set_minor_formatter(NullFormatter())
536|     # Grid...
537|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
538|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
539|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
540|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
541|     # Data...
542|     ax.plot(xs,ys, c='#996633', lw=1.6, zorder=11, alpha=0.85)
543|     # Chart...
544|     fig.set_figwidth(imgw)
545|     fig.set_figheight(imgh)
546|     fig.subplots_adjust(left=marl, right=marr, bottom=marb, top=mart)
547|     fig.savefig(filename)
548|     Log.info('wrote: %s' % filename)
549|     Log.info()
550|     return 'Done'
551| 
552| ##================================================================================================##
553| def do_random_string_chart (**kwargs):
554|     fpath = KWARG('fpath', BasePath, str, kwargs)
555|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
556|     fname = KWARG('fname', 'random-string', str, kwargs)
557|     ftag = KWARG('ftag', '', str, kwargs)
558|     targ = KWARG('targ', Target0, str, kwargs)
559|     nmbr = KWARG('nmbr', 3000, int, kwargs)
560|     xtk0 = KWARG('xtk0', 500, int, kwargs)
561|     xtk1 = KWARG('xtk1', 100, int, kwargs)
562|     ytk0 = KWARG('ytk0', 500, int, kwargs)
563|     ytk1 = KWARG('ytk1', 100, int, kwargs)
564|     imgw = KWARG('w', 8.8, float, kwargs)
565|     imgh = KWARG('h', 4.0, float, kwargs)
566|     marl = KWARG('ml', 0.09, float, kwargs)
567|     marr = KWARG('mr', 0.99, float, kwargs)
568|     marb = KWARG('mb', 0.17, float, kwargs)
569|     mart = KWARG('mt', 0.93, float, kwargs)
570|     filename = path.join(ipath,'%s%s.png' % (fname,ftag))
571|     Log.info('random-strings:: %s' % str(list(kwargs.keys())))
572|     Log.info('fpath="%s"' % fpath)
573|     Log.info('ipath="%s"' % ipath)
574|     Log.info('fname="%s"' % fname)
575|     Log.info('ftag="%s"' % ftag)
576|     Log.info('imag-filename="%s"' % filename)
577|     Log.info('number-of-strings=%d' % nmbr)
578|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
579|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
580|     Log.info('image-size=%d x %d' % (imgw,imgh))
581|     Log.info('margin=%.2f, %.2f, %.2f, %.2f' % (marl,marr,marb,mart))
582|     Log.info('target=|%s|' % targ)
583|     Log.info()
584| 
585|     rand_strs = [RandString(len(targ)) for _ in range(nmbr)]
586|     test_strs = [(ix, s, compare_string(targ,s)) for ix,s in enumerate(rand_strs)]
587|     min_score = min(test_strs, key=lambda t:t[2])
588|     max_score = max(test_strs, key=lambda t:t[2])
589| 
590|     Log.info('Min-Score: [%3d] (%d) %s' % (min_score[0],min_score[2],min_score[1]))
591|     Log.info('Max-Score: [%3d] (%d) %s' % (max_score[0],max_score[2],max_score[1]))
592|     Log.info()
593|     for t in test_strs:
594|         Log.info('[%4d] %s (%4d)' % t)
595|     Log.info()
596|     Log.info()
597| 
598|     xs = [t[0]+1 for t in test_strs]
599|     ys = [t[2] for t in test_strs]
600| 
601|     xmin,xmax = 0, len(xs)+1
602|     ymin,ymax = 0, ((max(ys)//100)+1)*100
603| 
604|     fig, ax = plt.subplots()
605|     fig.suptitle('Random String Distance from Target', fontweight='bold')
606|     # Horizontal Axis...
607|     ax.set_xlabel('Random String')
608|     ax.set_xlim(xmin,xmax)
609|     ax.xaxis.set_major_locator(MultipleLocator(xtk0))
610|     ax.xaxis.set_minor_locator(MultipleLocator(xtk1))
611|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
612|     ax.xaxis.set_minor_formatter(NullFormatter())
613|     for tick in ax.xaxis.get_major_ticks():
614|         tick.label1.set_rotation('vertical')
615|         tick.label1.set_size(9)
616|     # Vertical Axis...
617|     ax.set_ylabel('Distance')
618|     ax.set_ylim(ymin,ymax)
619|     ax.yaxis.set_major_locator(MultipleLocator(ytk0))
620|     ax.yaxis.set_minor_locator(MultipleLocator(ytk1))
621|     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
622|     ax.yaxis.set_minor_formatter(NullFormatter())
623|     # Grid...
624|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
625|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
626|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
627|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
628|     # Data...
629|     ax.plot(xs,ys, c='#339966', lw=1.6, zorder=11, alpha=0.85)
630|     # Chart...
631|     fig.set_figwidth(imgw)
632|     fig.set_figheight(imgh)
633|     fig.subplots_adjust(left=marl, right=marr, bottom=marb, top=mart)
634|     fig.savefig(filename)
635|     Log.info('wrote: %s' % filename)
636|     Log.info()
637|     return 'Done'
638| 
639| ##================================================================================================##
640| def distance_generations_chart (data, lbls, **kwargs):
641|     """Create a Distance/Generation chart (image)."""
642|     filename = KWARG('filename', 'evolution.png', str, kwargs)
643|     gens = KWARG('gens', 5000, int, kwargs)
644|     offs = KWARG('offs', 32, int, kwargs)
645|     mode = KWARG('mode', 1, int, kwargs)
646|     delt = KWARG('delt', 15, int, kwargs)
647|     muts = KWARG('muts', 1, int, kwargs)
648|     xtk0 = KWARG('xtk0', 500, int, kwargs)
649|     xtk1 = KWARG('xtk1', 100, int, kwargs)
650|     ytk0 = KWARG('ytk0', 500, int, kwargs)
651|     ytk1 = KWARG('ytk1', 100, int, kwargs)
652|     imgw = KWARG('w', 8.8, float, kwargs)
653|     imgh = KWARG('h', 4.0, float, kwargs)
654|     marl = KWARG('ml', 0.09, float, kwargs)
655|     marr = KWARG('mr', 0.99, float, kwargs)
656|     marb = KWARG('mb', 0.17, float, kwargs)
657|     mart = KWARG('mt', 0.93, float, kwargs)
658|     # Calculate some stuff...
659|     max_gens = max([len(ys) for ys in data])
660|     max_dist = max([ys[0] for ys in data])
661|     xmin, xmax = 0, ((1+(max_gens//10))*10)
662|     ymin, ymax = 0, ((1+(max_dist//ytk0))*ytk0)
663|     # Log it...
664|     Log.info('make-chart:: %s' % str(list(kwargs.keys())))
665|     Log.info('image-size=%d x %d' % (imgw,imgh))
666|     Log.info('filename="%s"' % filename)
667|     Log.info('max-gens: %s' % str(max_gens))
668|     Log.info('max-dist: %s' % str(max_dist))
669|     Log.info('X-min-max=(%d, %d)' % (xmin,xmax))
670|     Log.info('Y-min-max=(%d, %d)' % (ymin,ymax))
671|     Log.info('X-axis-ticks=(%d, %d)' % (xtk0,xtk1))
672|     Log.info('Y-axis-ticks=(%d, %d)' % (ytk0,ytk1))
673|     Log.info('margin=%.2f, %.2f, %.2f, %.2f' % (marl,marr,marb,mart))
674|     Log.info('mode/gens/offs/delt/muts=%d/%d/%d/%d/%d' % (mode,gens,offs,delt,muts))
675|     Log.info()
676| 
677|     fig, ax = plt.subplots()
678|     s1 = ('%d Offspring, '%offs) if offs else ''
679|     s2 = ('Mode %d'%mode) if mode else ''
680|     s3 = (' (delta=%d)'%delt) if mode==3 else ''
681|     fig.suptitle('String Evolution - %s%s%s' % (s1,s2,s3), fontweight='bold')
682|     # Horizontal Axis...
683|     ax.set_xlabel('Generations (%d max)' % gens)
684|     ax.set_xlim(xmin,xmax)
685|     ax.xaxis.set_major_locator(MultipleLocator(xtk0))
686|     ax.xaxis.set_minor_locator(MultipleLocator(xtk1))
687|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
688|     ax.xaxis.set_minor_formatter(NullFormatter())
689|     for tick in ax.xaxis.get_major_ticks():
690|         tick.label1.set_rotation('vertical')
691|         tick.label1.set_size(9)
692|     # Vertical Axis...
693|     ax.set_ylabel('Distance from Target')
694|     ax.set_ylim(ymin,ymax)
695|     ax.yaxis.set_major_locator(MultipleLocator(ytk0))
696|     ax.yaxis.set_minor_locator(MultipleLocator(ytk1))
697|     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
698|     ax.yaxis.set_minor_formatter(NullFormatter())
699|     # Grid...
700|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
701|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
702|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
703|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
704|     # Data...
705|     xs = list(range(1, max_gens+2))
706|     for ix,ys in enumerate(data):
707|         n = len(ys)
708|         ax.plot(xs[0:n],ys, lw=2.2, label=lbls[ix], zorder=11+ix, alpha=0.85)
709|     ax.legend(loc='upper right', shadow=True)
710|     # Chart...
711|     fig.set_figwidth(imgw)
712|     fig.set_figheight(imgh)
713|     fig.subplots_adjust(left=marl, right=marr, bottom=marb, top=mart)
714|     fig.savefig(filename)
715|     Log.info('wrote: %s' % filename)
716|     Log.info()
717| 
718| Label = lambda a,s0,s1:(s0%len(a)) if a[-1]==0 else (s1%a[-1])
719| 
720| ##================================================================================================##
721| def do_chart_1 (**kwargs):
722|     """Distance/Generation Chart with multiple evolutions of a given configuration."""
723|     fpath = KWARG('fpath', BasePath, str, kwargs)
724|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
725|     fname = KWARG('fname', 'chart1', str, kwargs)
726|     ftag = KWARG('ftag', '', str, kwargs)
727|     targ = KWARG('targ', Target2, str, kwargs)
728|     gens = KWARG('gens', 500, int, kwargs)
729|     offs = KWARG('offs', 30, int, kwargs)
730|     mode = KWARG('mode', 1, int, kwargs)
731|     muts = KWARG('muts', 1, int, kwargs)
732|     delt = KWARG('delt', 15, int, kwargs)
733|     dots = KWARG('dots', 1000, int, kwargs)
734|     xtk0 = KWARG('xtk0', 500, int, kwargs)
735|     xtk1 = KWARG('xtk1', 100, int, kwargs)
736|     ytk0 = KWARG('ytk0', 500, int, kwargs)
737|     ytk1 = KWARG('ytk1', 100, int, kwargs)
738|     loop = KWARG('loop', 5, int, kwargs)
739|     Log.info('chart-1:: %s' % str(list(kwargs.keys())))
740|     Log.info('file-path="%s"' % fpath)
741|     Log.info('imgs-path="%s"' % ipath)
742|     Log.info('file-name="%s"' % fname)
743|     Log.info('file-tag="%s"' % ftag)
744|     Log.info('number-of-plots=%d' % loop)
745|     Log.info('max-generations=%d' % gens)
746|     Log.info('offspring-per-gen=%d' % offs)
747|     Log.info('mutation-mode=%d' % mode)
748|     Log.info('mutation-delta=%d' % delt)
749|     Log.info('mutations-per-str=%d' % muts)
750|     Log.info('display-freq=%d' % dots)
751|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
752|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
753|     Log.info('target=|%s|' % targ)
754|     Log.info()
755|     kwargs['filename'] = path.join(ipath,'%s%s.png' % (fname,ftag))
756|     # Generate data...
757|     props = dict(generations=gens, offspring=offs, mutations=muts, mode=mode, delta=delt, dots=dots)
758|     data = []
759|     for ix in range(loop):
760|         # Evolve String...
761|         ds,_ = evolve_string(targ, **props)
762|         ys = [d[0] for d in ds]
763|         data.append(ys)
764|     Log.info()
765|     # Labels...
766|     labs = [Label(ys,'gens %d','max (%d)') for ys in data]
767|     for ix,lab in enumerate(labs):
768|         Log.debug('label[%d]=%s' % (ix,lab))
769|     Log.debug()
770| 
771|     # Create Chart...
772|     distance_generations_chart(data, labs, **kwargs)
773|     Log.info()
774|     return 'Done'
775| 
776| ##================================================================================================##
777| def do_chart_2 (**kwargs):
778|     """Distance/Generation Chart with varying length Targets."""
779|     fpath = KWARG('fpath', BasePath, str, kwargs)
780|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
781|     fname = KWARG('fname', 'chart2', str, kwargs)
782|     ftag = KWARG('ftag', '', str, kwargs)
783|     targ = KWARG('targ', Target4, str, kwargs)
784|     gens = KWARG('gens', 500, int, kwargs)
785|     offs = KWARG('offs', 30, int, kwargs)
786|     mode = KWARG('mode', 1, int, kwargs)
787|     muts = KWARG('muts', 1, int, kwargs)
788|     delt = KWARG('delt', 15, int, kwargs)
789|     dots = KWARG('dots', 1000, int, kwargs)
790|     xtk0 = KWARG('xtk0', 500, int, kwargs)
791|     xtk1 = KWARG('xtk1', 100, int, kwargs)
792|     ytk0 = KWARG('ytk0', 500, int, kwargs)
793|     ytk1 = KWARG('ytk1', 100, int, kwargs)
794|     loop = KWARG('loop', 5, int, kwargs)
795|     jump = KWARG('jump', 20, int, kwargs)
796|     Log.info('chart-2:: %s' % str(list(kwargs.keys())))
797|     Log.info('file-path="%s"' % fpath)
798|     Log.info('imgs-path="%s"' % ipath)
799|     Log.info('file-name="%s"' % fname)
800|     Log.info('file-tag="%s"' % ftag)
801|     Log.info('number-of-plots=%d' % loop)
802|     Log.info('length-increment=%d' % jump)
803|     Log.info('max-generations=%d' % gens)
804|     Log.info('offspring-per-gen=%d' % offs)
805|     Log.info('mutation-mode=%d' % mode)
806|     Log.info('mutation-delta=%d' % delt)
807|     Log.info('mutations-per-str=%d' % muts)
808|     Log.info('display-freq=%d' % dots)
809|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
810|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
811|     Log.info('target=|%s|' % targ)
812|     Log.info()
813|     kwargs['filename'] = path.join(ipath,'%s%s.png' % (fname,ftag))
814|     # Generate data...
815|     props = dict(generations=gens, offspring=offs, mutations=muts, mode=mode, delta=delt, dots=dots)
816|     data = []
817|     for ix in range(1, loop+1):
818|         # Evolve String...
819|         ds,_ = evolve_string(targ[0:(ix*jump)], **props)
820|         ys = [d[0] for d in ds]
821|         data.append(ys)
822|     Log.info()
823|     # Labels...
824|     sn = lambda n:'len %d '%((n+1)*jump)
825|     labs = [Label(ys,sn(ix)+'gens %d',sn(ix)+'max (%d)') for ix,ys in enumerate(data)]
826|     for ix,lab in enumerate(labs):
827|         Log.debug('label[%d]=%s' % (ix,lab))
828|     Log.debug()
829| 
830|     # Create Chart...
831|     distance_generations_chart(data, labs, **kwargs)
832|     Log.info()
833|     return 'Done'
834| 
835| ##================================================================================================##
836| def do_chart_3 (**kwargs):
837|     """Generations/String Length Chart."""
838|     fpath = KWARG('fpath', BasePath, str, kwargs)
839|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
840|     fname = KWARG('fname', 'chart3', str, kwargs)
841|     ftag = KWARG('ftag', '', str, kwargs)
842|     loop = KWARG('loop', 6, int, kwargs)
843|     bars = KWARG('bars', 10, int, kwargs)
844|     jump = KWARG('jump', 18, int, kwargs)
845|     targ = KWARG('targ', Target4, str, kwargs)
846|     gens = KWARG('gens', 5000, int, kwargs)
847|     offs = KWARG('offs', 30, int, kwargs)
848|     mode = KWARG('mode', 1, int, kwargs)
849|     muts = KWARG('muts', 1, int, kwargs)
850|     delt = KWARG('delt', 15, int, kwargs)
851|     dots = KWARG('dots', 1000, int, kwargs)
852|     xtk0 = KWARG('xtk0', 500, int, kwargs)
853|     xtk1 = KWARG('xtk1', 100, int, kwargs)
854|     ytk0 = KWARG('ytk0', 500, int, kwargs)
855|     ytk1 = KWARG('ytk1', 100, int, kwargs)
856|     imgw = KWARG('w', 8.8, float, kwargs)
857|     imgh = KWARG('h', 4.0, float, kwargs)
858|     marl = KWARG('ml', 0.09, float, kwargs)
859|     marr = KWARG('mr', 0.99, float, kwargs)
860|     marb = KWARG('mb', 0.17, float, kwargs)
861|     mart = KWARG('mt', 0.93, float, kwargs)
862|     filename = path.join(ipath,'%s%s.png' % (fname,ftag))
863|     Log.info('chart-3:: %s' % str(list(kwargs.keys())))
864|     Log.info('file-path="%s"' % fpath)
865|     Log.info('imgs-path="%s"' % ipath)
866|     Log.info('file-name="%s"' % fname)
867|     Log.info('file-tag="%s"' % ftag)
868|     Log.info('chart-filename="%s"' % filename)
869|     Log.info('number-of-plots=%d' % loop)
870|     Log.info('number-of-bars=%d' % bars)
871|     Log.info('length-increment=%d' % jump)
872|     Log.info('max-generations=%d' % gens)
873|     Log.info('offspring-per-gen=%d' % offs)
874|     Log.info('mutation-mode=%d' % mode)
875|     Log.info('mutation-delta=%d' % delt)
876|     Log.info('mutations-per-str=%d' % muts)
877|     Log.info('display-freq=%d' % dots)
878|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
879|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
880|     Log.info('image-size=%d x %d' % (imgw,imgh))
881|     Log.info('margin=%.2f, %.2f, %.2f, %.2f' % (marl,marr,marb,mart))
882|     Log.info('target=|%s|' % targ)
883|     Log.info()
884| 
885|     # Generate data...
886|     props = dict(generations=gens, offspring=offs, mutations=muts, mode=mode, delta=delt, dots=dots)
887|     data = {}
888|     for ix in range(bars):
889|         n = (ix+1)*jump
890|         for jx in range(loop):
891|             # Evolve String...
892|             ds,_ = evolve_string(targ[0:n], **props)
893|             dist = ds[0][0]
894|             head = [d for d in ds if (dist/20) < d[0]]
895|             data[ix,jx] = (n, jx, len(ds), len(head)) # len, jx, nbr-gens, %5
896| 
897|     plots0 = []
898|     plots1 = []
899|     max_gens = 0
900|     for jx in range(loop):
901|         p0 = []
902|         p1 = []
903|         for ix in range(bars):
904|             n,jx,y0,y1 = data[ix,jx]
905|             Log.debug('%d.%d: [%d] %d %d' % (ix,jx, n, y0,y1))
906|             p0.append((n,y0))
907|             p1.append((n,y1))
908|             if max_gens < y0:
909|                 max_gens = y0
910|         Log.debug()
911|         plots0.append(list(zip(*p0)))
912|         plots1.append(list(zip(*p1)))
913| 
914|     xmin,xmax = 0, (bars*jump)+2
915|     ymin,ymax = 0, (1+(max_gens//ytk0))*ytk0
916|     Log.info('max-gens: %s' % str(max_gens))
917|     Log.info('xmin/xmax: %s, %s' % (xmin,xmax))
918|     Log.info('ymin/ymax: %s, %s' % (ymin,ymax))
919|     Log.info()
920| 
921|     fig, ax = plt.subplots()
922|     s0 = ('offspring %d, mode %d, max gens %d' % (offs, mode, gens))
923|     sx = (', delta %d'%delt) if mode==3 else ''
924|     fig.suptitle('String Evolution - %s%s' % (s0,sx), fontweight='bold')
925|     # Horizontal Axis...
926|     ax.set_xlabel('String Length')
927|     ax.set_xlim(xmin,xmax)
928|     ax.xaxis.set_major_locator(MultipleLocator(xtk0))
929|     #ax.xaxis.set_minor_locator(MultipleLocator(xtk1))
930|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
931|     ax.xaxis.set_minor_formatter(NullFormatter())
932|     for tick in ax.xaxis.get_major_ticks():
933|         tick.label1.set_rotation('vertical')
934|         tick.label1.set_size(9)
935|     # Vertical Axis...
936|     ax.set_ylabel('Generations')
937|     ax.set_ylim(ymin,ymax)
938|     ax.yaxis.set_major_locator(MultipleLocator(ytk0))
939|     ax.yaxis.set_minor_locator(MultipleLocator(ytk1))
940|     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
941|     ax.yaxis.set_minor_formatter(NullFormatter())
942|     # Grid...
943|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
944|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
945|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
946|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
947|     # Data...
948|     for ix,p in enumerate(plots0):
949|         Log.debug(p)
950|         ax.plot(p[0],p[1], c='#ff0000', lw=2.2, zorder=51+ix, alpha=0.85)
951|     Log.debug()
952|     for ix,p in enumerate(plots1):
953|         Log.debug(p)
954|         ax.plot(p[0],p[1], c='#0000ff', lw=2.2, zorder=11+ix, alpha=0.85)
955|     Log.debug()
956|     # Chart...
957|     fig.set_figwidth(imgw)
958|     fig.set_figheight(imgh)
959|     fig.subplots_adjust(left=marl, right=marr, bottom=marb, top=mart)
960|     fig.savefig(filename)
961|     Log.info('wrote: %s' % filename)
962|     Log.info()
963|     return 'Done'
964| 
965| ##================================================================================================##
966| def do_chart_4 (**kwargs):
967|     """Generation/Mode 3 Delta Chart."""
968|     fpath = KWARG('fpath', BasePath, str, kwargs)
969|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
970|     fname = KWARG('fname', 'chart4', str, kwargs)
971|     ftag = KWARG('ftag', '', str, kwargs)
972|     loop = KWARG('loop', 6, int, kwargs)
973|     jump = KWARG('jump', 20, int, kwargs)
974|     targ = KWARG('targ', Target4, str, kwargs)
975|     gens = KWARG('gens', 500, int, kwargs)
976|     offs = KWARG('offs', 30, int, kwargs)
977|     mode = KWARG('mode', 1, int, kwargs)
978|     delt = KWARG('delt', 15, int, kwargs)
979|     dots = KWARG('dots', 1000, int, kwargs)
980|     xtk0 = KWARG('xtk0', 500, int, kwargs)
981|     xtk1 = KWARG('xtk1', 100, int, kwargs)
982|     ytk0 = KWARG('ytk0', 500, int, kwargs)
983|     ytk1 = KWARG('ytk1', 100, int, kwargs)
984|     imgw = KWARG('w', 8.8, float, kwargs)
985|     imgh = KWARG('h', 4.0, float, kwargs)
986|     marl = KWARG('ml', 0.09, float, kwargs)
987|     marr = KWARG('mr', 0.99, float, kwargs)
988|     marb = KWARG('mb', 0.17, float, kwargs)
989|     mart = KWARG('mt', 0.93, float, kwargs)
990|     filename = path.join(ipath,'%s%s.png' % (fname,ftag))
991|     Log.info('chart-4:: %s' % str(list(kwargs.keys())))
992|     Log.info('file-path="%s"' % fpath)
993|     Log.info('imgs-path="%s"' % ipath)
994|     Log.info('file-name="%s"' % fname)
995|     Log.info('file-tag="%s"' % ftag)
996|     Log.info('number-of-plots=%d' % loop)
997|     Log.info('delta-increment=%d' % jump)
998|     Log.info('chart-filename="%s"' % filename)
999|     Log.info('max-generations=%d' % gens)
1000|     Log.info('offspring-per-gen=%d' % offs)
1001|     Log.info('mutation-mode=%d' % mode)
1002|     Log.info('mutation-delta=%d' % delt)
1003|     Log.info('display-freq=%d' % dots)
1004|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
1005|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
1006|     Log.info('image-size=%d x %d' % (imgw,imgh))
1007|     Log.info('margin=%.2f, %.2f, %.2f, %.2f' % (marl,marr,marb,mart))
1008|     Log.info('target=|%s|' % targ)
1009|     Log.info()
1010| 
1011|     # Generate data...
1012|     props = dict(generations=gens, offspring=offs, mode=mode, delta=delt, dots=dots)
1013|     data = []
1014|     for ix in range(loop):
1015|         # Evolve String...
1016|         n = (ix+1)*jump
1017|         props['delta'] = n
1018|         ds,_ = evolve_string(targ, **props)
1019|         datum = (ix, n, len(ds), ds[-1][0])
1020|         data.append(datum)
1021|         Log.info(datum)
1022|     Log.info()
1023|     # Extract plot data...
1024|     xs = [d[1] for d in data]
1025|     ys = [d[2] for d in data]
1026|     # Calculate plot parameters...
1027|     max_gens = max(ys)
1028|     xmin,xmax = 0, (loop+1)*jump
1029|     ymin,ymax = 0, (1+(max_gens//ytk0))*ytk0
1030|     Log.info('max-gens: %s' % str(max_gens))
1031|     Log.info('xmin/xmax: %s, %s' % (xmin,xmax))
1032|     Log.info('ymin/ymax: %s, %s' % (ymin,ymax))
1033|     Log.info()
1034| 
1035|     fig, ax = plt.subplots()
1036|     ttl = ('String Evolution - offspring %d, mode %d, max gens %d' % (offs, mode, gens))
1037|     fig.suptitle(ttl, fontweight='bold')
1038|     # Horizontal Axis...
1039|     ax.set_xlabel('Mutation Mode 3 Delta')
1040|     ax.set_xlim(xmin,xmax)
1041|     ax.xaxis.set_major_locator(MultipleLocator(xtk0))
1042|     ax.xaxis.set_minor_locator(MultipleLocator(xtk1))
1043|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
1044|     ax.xaxis.set_minor_formatter(NullFormatter())
1045|     for tick in ax.xaxis.get_major_ticks():
1046|         tick.label1.set_rotation('vertical')
1047|         tick.label1.set_size(9)
1048|     # Vertical Axis...
1049|     ax.set_ylabel('Generations')
1050|     ax.set_ylim(ymin,ymax)
1051|     ax.yaxis.set_major_locator(MultipleLocator(ytk0))
1052|     ax.yaxis.set_minor_locator(MultipleLocator(ytk1))
1053|     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
1054|     ax.yaxis.set_minor_formatter(NullFormatter())
1055|     # Grid...
1056|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
1057|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
1058|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
1059|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
1060|     # Data...
1061|     ax.plot(xs,ys, c='#3366ff', lw=2.2, zorder=11, alpha=0.85)
1062|     # Chart...
1063|     fig.set_figwidth(imgw)
1064|     fig.set_figheight(imgh)
1065|     fig.subplots_adjust(left=marl, right=marr, bottom=marb, top=mart)
1066|     fig.savefig(filename)
1067|     Log.info('wrote: %s' % filename)
1068|     Log.info()
1069|     return 'Done'
1070| 
1071| ##================================================================================================##
1072| def do_test (**kwargs):
1073|     fpath = KWARG('fpath', BasePath, str, kwargs)
1074|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
1075|     dpath = KWARG('dpath', DataPath, str, kwargs)
1076|     fname = KWARG('fname', 'test', str, kwargs)
1077|     ftag = KWARG('ftag', '', str, kwargs)
1078|     targ = KWARG('targ', Target0, str, kwargs)
1079|     gens = KWARG('gens', 5000, int, kwargs)
1080|     offs = KWARG('offs', 50, int, kwargs)
1081|     mode = KWARG('mode', 1, int, kwargs)
1082|     delt = KWARG('delt', 15, int, kwargs)
1083|     muts = KWARG('muts', 1, int, kwargs)
1084|     dots = KWARG('dots', 100, int, kwargs)
1085|     nmbr = KWARG('nmbr', 1000, int, kwargs)
1086|     loop = KWARG('loop', 5, int, kwargs)
1087|     jump = KWARG('jump', 25, int, kwargs)
1088|     xtk0 = KWARG('xtk0', 500, int, kwargs)
1089|     xtk1 = KWARG('xtk1', 100, int, kwargs)
1090|     ytk0 = KWARG('ytk0', 500, int, kwargs)
1091|     ytk1 = KWARG('ytk1', 100, int, kwargs)
1092|     imgw = KWARG('w', 8.8, float, kwargs)
1093|     imgh = KWARG('h', 4.0, float, kwargs)
1094|     marl = KWARG('ml', 0.09, float, kwargs)
1095|     marr = KWARG('mr', 0.99, float, kwargs)
1096|     marb = KWARG('mb', 0.17, float, kwargs)
1097|     mart = KWARG('mt', 0.93, float, kwargs)
1098|     filename = path.join(dpath,'%s%s.png' % (fname,ftag))
1099|     statname = path.join(dpath,'%s%s.out' % (fname,ftag))
1100|     dataname = path.join(dpath,'%s%s.tab' % (fname,ftag))
1101|     Log.info('test:: %s' % str(list(kwargs.keys())))
1102|     Log.info('fpath="%s"' % fpath)
1103|     Log.info('fname="%s"' % fname)
1104|     Log.info('dpath="%s"' % dpath)
1105|     Log.info('fname="%s"' % fname)
1106|     Log.info('ftag="%s"' % ftag)
1107|     Log.info('imag-filename="%s"' % filename)
1108|     Log.info('stat-filename="%s"' % statname)
1109|     Log.info('data-filename="%s"' % dataname)
1110|     Log.info('max-generations=%d' % gens)
1111|     Log.info('offspring-per-gen=%d' % offs)
1112|     Log.info('mutation-mode=%d' % mode)
1113|     Log.info('mutation-delta=%d' % delt)
1114|     Log.info('mutations-per-str=%d' % muts)
1115|     Log.info('display-freq=%d' % dots)
1116|     Log.info('number-of-items=%d' % nmbr)
1117|     Log.info('number-of-loops=%d' % loop)
1118|     Log.info('loop-increment=%d' % loop)
1119|     Log.info('x-axis-ticks=%d, %d' % (xtk0,xtk1))
1120|     Log.info('y-axis-ticks=%d, %d' % (ytk0,ytk1))
1121|     Log.info('image-size=%d x %d' % (imgw,imgh))
1122|     Log.info('margin=%.2f, %.2f, %.2f, %.2f' % (marl,marr,marb,mart))
1123|     Log.info('target=|%s|' % targ)
1124|     Log.info()
1125|     #
1126|     print(filename)
1127|     #
1128|     Log.info()
1129|     return 'Done'
1130| ####################################################################################################
1131| def dispatch (cmd, **kwargs):
1132|     Log.info('command: %s' % cmd)
1133|     for kw in kwargs:
1134|         Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
1135|     Log.info()
1136|     Log.info('Alphabet: <%s> (%d chars)' % (Alphabet,len(Alphabet)))
1137|     Log.info()
1138|     Log.info('T0: %d chars' % len(Target0))
1139|     Log.info('T1: %d chars' % len(Target1))
1140|     Log.info('T2: %d chars' % len(Target2))
1141|     Log.info('T3: %d chars' % len(Target3))
1142|     Log.info('T4: %d chars' % len(Target4))
1143|     Log.info('T5: %d chars' % len(Target5))
1144|     Log.info()
1145|     if cmd == 's0': return do_string_0(**kwargs)
1146|     if cmd == 's1': return do_string_1(**kwargs)
1147|     if cmd == 'c1': return do_chart_1(**kwargs)
1148|     if cmd == 'c2': return do_chart_2(**kwargs)
1149|     if cmd == 'c3': return do_chart_3(**kwargs)
1150|     if cmd == 'c4': return do_chart_4(**kwargs)
1151|     if cmd == 'csm': return do_string_mutation_chart(**kwargs)
1152|     if cmd == 'crs': return do_random_string_chart(**kwargs)
1153|     if cmd == 'test': return do_test(**kwargs)
1154|     return 'Nothing to do!'
1155| ####################################################################################################
1156| if __name__ == '__main__':
1157|     print('autorun: %s' % argv[0])
1158|     #Log.start(path.join(BasePath,LogFilenameTimestamp('evolution%s.log')))
1159|     Log.start(path.join(BasePath,'evolution.log'))
1160|     Log.level(info())
1161|     Log.info(argv[0])
1162|     Log.info()
1163|     cmd = argv[1] if 1 < len(argv) else CMND
1164|     kwargs = ARGS
1165|     for a in argv[2:]:
1166|         nv = a.split('=', 2)
1167|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
1168|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
1169|     try:
1170|         print('CMD: %s' % cmd)
1171|         print()
1172|         obj = dispatch(cmd, **kwargs)
1173|         print()
1174|         print(obj)
1175|         Log.info()
1176|         Log.info(obj)
1177|     except:
1178|         etype, evalue, tb = exc_info()
1179|         ts = extract_tb(tb)
1180|         Log.error()
1181|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
1182|         Log.error()
1183|         for t in ts[-5:]:
1184|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
1185|             Log.error(' %s' % t[3])
1186|             Log.error()
1187|         raise
1188|     finally:
1189|         Log.end()
1190| ####################################################################################################
1191| '''eof'''
1192|