-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.py
1964 lines (1805 loc) · 69.1 KB
/
command.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# `Command`s bundle names/aliases, help-strings, and functionality.
# Also defines all the individual commands in trialyzer.
# Also contains backend functions which are useful for the commands.
import csv
import curses
import enum
import math
import operator
import os
import statistics
from typing import Callable, Iterable
import time
import analysis
import constraintmap
import corpus
from fingermap import Finger
import gui_util
import layout
import nstroke
import remap
from session import Session
from typingdata import TypingData
import typingtest
class CommandType(enum.Enum):
GENERAL = enum.auto()
DATA = enum.auto()
ANALYSIS = enum.auto()
EDITING = enum.auto()
class Command:
def __init__(self, type: CommandType, help: tuple[str], names: tuple[str],
fn: Callable[[list[str], Session], str | None]):
"""
`names` is a list of aliases that the user can use to activate the
command. The first of these will be use to alphabetize commands.
The first string of `help` will be used as a brief summary when the
`help` command is used with no args. The rest will be joined with
newlines.
`fn` is the actual function to be run, with parameters being
`args: str` and `session`. It is usually void, but may return `"quit"`
to trigger application exit.
"""
self.names = names
self.type = type
self.help = help
self.fn = fn
commands = list()
by_name = dict()
def register_command(cmd: Command):
commands.append(cmd)
for name in cmd.names:
by_name[name] = cmd
def run_command(name: str, args: list[str], s: Session):
cmd = by_name.get(name, None)
if cmd is None:
s.say("Unrecognized command", gui_util.red)
else:
return cmd.fn(args, s)
# Actual commands
def cmd_type(args: list[str], s: Session):
if not args: # autosuggest trigram
# Choose the most frequent trigram from the least completed
# category of the analysis target layout
exact_tristrokes = s.typingdata_.exact_tristrokes_for_layout(
s.analysis_target)
catdata = s.typingdata_.tristroke_category_data(s.analysis_target)
s.analysis_target.preprocessors["counts"].join()
counts = s.analysis_target.counts
completion = {}
for cat in catdata:
if cat.startswith(".") or cat.endswith(".") or cat == "":
continue
n = catdata[cat][1]
completion[cat] = n/counts[cat] if n > 0 else 0
ruled_out = {s.analysis_target.to_ngram(tristroke)
for tristroke in exact_tristrokes} # already have data
user_tg = None
def find_from_best_cat():
if not completion:
return None
best_cat = min(completion, key = lambda cat: completion[cat])
# is sorted by descending frequency
for tg in s.target_corpus.trigram_counts:
if tg in ruled_out:
continue
if (tristroke := s.analysis_target.to_nstroke(tg)) is None:
continue
if nstroke.tristroke_category(tristroke) == best_cat:
ruled_out.add(tg)
if s.user_layout.to_ngram(tristroke): # keys exist
return tristroke
# if we get to this point,
# there was no compatible trigram in the category
# Check next best category
del completion[best_cat]
return find_from_best_cat()
tristroke = find_from_best_cat()
user_tg = s.user_layout.to_ngram(tristroke)
targ_tg = s.analysis_target.to_ngram(tristroke)
if not tristroke:
s.say("Unable to autosuggest - all compatible trigrams"
" between the user layout and analysis target"
" already have data", gui_util.red)
return
else:
estimate, _ = s.typingdata_.tristroke_speed_calculator(
s.analysis_target)(tristroke)
# TODO: frequency?
fingers = tuple(finger.name for finger in tristroke.fingers)
freq = (s.target_corpus.trigram_counts[targ_tg]/
s.target_corpus.trigram_counts.total())
s.say(f"Autosuggesting trigram "
f"{corpus.display_str(user_tg, s.corpus_settings)}\n"
f"({s.analysis_target.name} "
f"{corpus.display_str(targ_tg, s.corpus_settings)})\n" +
"Be sure to use {} {} {}".format(*fingers) +
f"\nFrequency: {freq:.3%}",
gui_util.blue)
elif args[0] == "cat":
args.pop(0)
with_fingers = set()
without_fingers = set()
with_keys = set()
without_keys = set()
for i in reversed(range(len(args))):
if args[i] == "with":
for _ in range(len(args)-i-1):
item = args.pop()
try:
with_fingers.add(Finger[item])
except KeyError:
with_keys.add(item)
with_keys.add(item)
with_keys.add(
corpus.display_name(item, s.corpus_settings))
with_keys.add(
corpus.undisplay_name(item, s.corpus_settings))
args.pop() # remove "with"
elif args[i] == "without":
for _ in range(len(args)-i-1):
item = args.pop()
try:
without_fingers.add(Finger[item])
except KeyError:
without_keys.add(item)
without_keys.add(
corpus.display_name(item, s.corpus_settings))
without_keys.add(
corpus.undisplay_name(item, s.corpus_settings))
args.pop() # remove "without"
if not with_fingers:
with_fingers.update(Finger)
with_fingers -= without_fingers
if not with_keys:
with_keys.update(s.analysis_target.positions)
with_keys -= without_keys
if not args:
category = ""
else:
category = nstroke.parse_category(args[0])
exact_tristrokes = s.typingdata_.exact_tristrokes_for_layout(
s.analysis_target)
targ_tg = None
applicable = nstroke.applicable_function(category)
for tg in s.target_corpus.trigram_counts:
if with_keys and with_keys.isdisjoint(tg):
continue
if (ts := s.analysis_target.to_nstroke(tg)) is None:
continue
if not applicable(nstroke.tristroke_category(ts)):
continue
if ts in exact_tristrokes:
continue
if with_fingers.isdisjoint(ts.fingers):
continue
reject = False
for finger in ts.fingers:
if finger in without_fingers:
reject = True
break
if reject:
continue
targ_tg = tg
user_tg = s.user_layout.to_ngram(ts)
tristroke = ts
break
if targ_tg is None:
s.say("Unable to autosuggest - all trigrams"
" matching these specs already have data", gui_util.red)
return
else:
estimate, _ = s.typingdata_.tristroke_speed_calculator(
s.analysis_target)(tristroke)
fingers = tuple(finger.name for finger in tristroke.fingers)
freq = (s.target_corpus.trigram_counts[targ_tg]/
s.target_corpus.trigram_counts.total())
s.say(f"Autosuggesting trigram "
f"{nstroke.display_str(user_tg, s.corpus_settings)}\n"
f"({s.analysis_target.name} "
f"{nstroke.display_str(targ_tg, s.corpus_settings)})\n" +
"Be sure to use {} {} {}".format(*fingers) +
f"\nFrequency: {freq:.3%}",
gui_util.blue)
else:
if len(args) == 1:
args = tuple(args)
if len(tuple(args)) != 3:
s.say("Trigram must be length 3", gui_util.red)
return
if (tristroke := s.user_layout.to_nstroke(tuple(args))) is None:
s.say("That trigram isn't in this layout", gui_util.red)
return
estimate, _ = s.typingdata_.tristroke_speed_calculator(
s.user_layout)(tristroke)
user_corp = s.user_layout.get_corpus(s.corpus_settings)
try:
freq = (
user_corp.trigram_counts[s.user_layout.to_ngram(tristroke)]/
user_corp.trigram_counts.total())
s.say(f"\nFrequency: {freq:.3%}", gui_util.blue)
except (KeyError, TypeError):
freq = None
csvdata = s.typingdata_.csv_data
if tristroke in csvdata:
s.say(
f"Note: this tristroke already has "
f"{len(csvdata[tristroke][0])} data points",
gui_util.blue)
s.say("Starting typing test >>>", gui_util.green)
typingtest.test(s, tristroke, estimate)
s.input_win.clear()
s.typingdata_.save_csv()
s.say("Typing data saved", gui_util.green)
s.typingdata_.refresh()
register_command(Command(
CommandType.DATA,
(
"t[ype] [trigram]: Run typing test\n"
"t[ype] cat [category] [with <fingers/keys>] [without <fingers/keys>]:"
" Run typing test with trigram of a certain type",
"If no argument is given, a trigram is autosuggested based on the "
"analysis target."
),
("type", "t"),
cmd_type
))
def cmd_clear(args: list[str], s: Session):
if len(args) == 3:
trigram = tuple(args)
elif len(args) == 1 and len(args[0]) == 3:
trigram = tuple(args[0])
else:
s.say("Usage: c[lear] <trigram>", gui_util.red)
return
csvdata = s.typingdata_.csv_data
if (tristroke := s.user_layout.to_nstroke(trigram)) is None:
if (tristroke := s.user_layout.to_nstroke(tuple(
corpus.undisplay_name(key, s.corpus_settings)
for key in trigram))) is None:
s.say("That trigram does not exist in the user layout",
gui_util.red)
return
try:
num_deleted = len(csvdata.pop(tristroke)[0])
except KeyError:
num_deleted = 0
s.typingdata_.save_csv()
s.typingdata_.refresh()
s.say(f"Deleted {num_deleted} data points for "
f"{corpus.display_str(trigram, s.corpus_settings)}")
register_command(Command(
CommandType.DATA,
("c[lear] <trigram>: Erase data for trigram",),
("clear", "c"),
cmd_clear
))
def cmd_target(args: list[str], s: Session):
layout_name = " ".join(args)
if layout_name: # set layout
try:
s.analysis_target = layout.get_layout(layout_name)
s.say("Set " + layout_name + " as the analysis target.",
gui_util.green)
s.corpus_settings["repeat_key"] = s.analysis_target.repeat_key
s.target_corpus = s.analysis_target.get_corpus(s.corpus_settings)
s.save_settings()
except FileNotFoundError:
s.say(f"/layouts/{layout_name} was not found.",
gui_util.red)
else:
s.say("Usage: target <layout name>", gui_util.red)
register_command(Command(
CommandType.GENERAL,
(
"target <layout name>: Set analysis target (for further commands)",
"Not to be confused with use"
),
("target"),
cmd_target
))
def cmd_layout(args: list[str], s: Session):
layout_name = " ".join(args)
if layout_name:
try:
s.output("\n"+ layout_name + "\n" +
limited_repr(layout.get_layout(layout_name)))
except FileNotFoundError:
s.say(f"/layouts/{layout_name} was not found.",
gui_util.red)
s.say("Searching for similar layouts...",
gui_util.blue)
return cmd_layouts(args, s)
else:
s.output("\n" + s.analysis_target.name + "\n"
+ limited_repr(s.analysis_target))
register_command(Command(
CommandType.GENERAL,
(
"l[ayout] [layout name]: View layout",
"If no argument given, uses the target layout.\n"
"Searches for similar layouts if no match found."
),
("layout", "l"),
cmd_layout
))
def cmd_layouts(args: list[str], s: Session):
if not args:
s.say("Missing search terms. Did you mean 'list'?", gui_util.red)
return
layout_names = scan_dir()
if not layout_names:
s.say("No layouts found in /layouts/", gui_util.red)
return
layouts: list[layout.Layout] = []
for name in layout_names:
for str_ in args:
if str_ in name:
layouts.append(layout.get_layout(name))
break
if not layouts:
s.say(f"No layouts matched these terms")
return
for l in layouts:
s.output(f"\n{l.name}\n{repr(l)}")
register_command(Command(
CommandType.GENERAL,
(
"layouts <search terms>: View multiple layouts",
"Uses the target layout if none specified"
),
("layouts",),
cmd_layouts
))
def cmd_list(args: list[str], s: Session):
try:
page_num = int(args[0])
except IndexError:
page_num = 1
except ValueError:
s.say("Usage: list [page]", gui_util.red)
return
layout_file_list = scan_dir()
if not layout_file_list:
s.say("No layouts found in /layouts/", gui_util.red)
return
s.output(f"{len(layout_file_list)} layouts found")
first_row = 3
num_rows = s.right_pane.getmaxyx()[0] - first_row
names = [str(layout.get_layout(filename))
for filename in layout_file_list]
col_width = len(max(names, key=len))
padding = 3
num_cols = (1 +
(s.right_pane.getmaxyx()[1] - col_width) // (col_width + padding))
num_pages = math.ceil(len(names) / (num_rows * num_cols))
if page_num > num_pages:
page_num = num_pages
elif page_num <= 0:
page_num = 1
s.output(f"Page {page_num} of {num_pages}"
+ " - Use list [page] to view others" * (num_pages > 1)
+ "\n---", )
first_index = (page_num - 1) * num_rows * num_cols
last_index = min(len(names), first_index + num_rows * num_cols)
s.right_pane.scroll(num_rows)
for i in range(last_index - first_index):
s.right_pane.addstr(
first_row + i % num_rows,
(i // num_rows) * (col_width + padding),
names[first_index + i])
s.right_pane.refresh()
register_command(Command(
CommandType.GENERAL,
("list|ls [page]: List all layouts",),
("list", "ls"),
cmd_list
))
def cmd_use(args: list[str], s: Session):
layout_name = " ".join(args)
if not layout_name:
s.say("Usage: u[se] <layout name>", gui_util.red)
return
try:
s.user_layout = layout.get_layout(layout_name)
s.say("Set " + layout_name + " as the user layout.",
gui_util.green)
s.save_settings()
except FileNotFoundError:
s.say(f"/layouts/{layout_name} was not found.",
gui_util.red)
register_command(Command(
CommandType.DATA,
(
"u[se] <layout name>: Set user layout (for typing test, etc)",
"Not to be confused with target"
),
("use", "u"),
cmd_use
))
def cmd_alias(args: list[str], s: Session):
remove = False
if not args:
s.say("Usage:\n" + "\n".join((
"alias <key1> <key2> [key3, ...]: "
"Set equivalent keys in typing test",
"alias list: Show existing aliases",
"alias remove <key1> <key2> [key3, ...]: Remove alias",
)), gui_util.red)
return
elif args[0] == "list":
if s.key_aliases:
s.say("Existing aliases:", gui_util.blue)
for keys in s.key_aliases:
s.say(" <-> ".join(keys), gui_util.blue)
else:
s.say("No existing aliases", gui_util.blue)
return
elif args[0] == "remove":
remove = True
args.pop(0)
if len(args) < 2:
s.say("At least two keys must be specified", gui_util.red)
return
keys = frozenset(args)
if remove:
try:
s.key_aliases.remove(keys)
s.say("Removed alias", gui_util.green)
except ValueError:
s.say("That alias wasn't there", gui_util.red)
for a in s.key_aliases:
if keys < a:
s.say(f"Maybe you meant {' '.join(a)}?")
break
return
else:
if keys not in s.key_aliases:
s.key_aliases.add(keys)
s.say("Added alias", gui_util.green)
else:
s.say("That alias already exists", gui_util.green)
return
s.save_settings()
register_command(Command(
CommandType.DATA,
(
"alias <key1> <key2> [key3, ...]: Set equivalent keys in typing test\n"
"alias list: Show existing aliases\n"
"alias remove <key1> <key2> [key3, ...]: Remove alias",
"This is intended for making the typing test more convenient. "
"Keys added in the same command form a group. Keys in a group are "
"considered equivalent to each other in the typing test. "
"Groups are not transitive, eg. with groups (a, b) and (b, c), "
"a will not work as an alias for c."
),
("alias",),
cmd_alias
))
def cmd_analyze_diff_common(s: Session, baseline_layout: layout.Layout,
target_layout: layout.Layout, show_all: bool, hint: str):
base_tri_stats = analysis.layout_tristroke_analysis(
baseline_layout, s.typingdata_, s.corpus_settings)
base_bi_stats = analysis.layout_bistroke_analysis(
baseline_layout, s.typingdata_, s.corpus_settings)
base_tri_ms = base_tri_stats[""][2]
base_tri_wpm = 24000/base_tri_ms
base_bi_ms = base_bi_stats[""][2]
base_bi_wpm = 12000/base_bi_ms
tar_tri_stats = analysis.layout_tristroke_analysis(
target_layout, s.typingdata_, s.corpus_settings)
tar_bi_stats = analysis.layout_bistroke_analysis(
target_layout, s.typingdata_, s.corpus_settings)
tar_tri_ms = tar_tri_stats[""][2]
tar_tri_wpm = 24000/tar_tri_ms
tar_bi_ms = tar_bi_stats[""][2]
tar_bi_wpm = 12000/tar_bi_ms
def diff(target, baseline):
return {key:
tuple(map(operator.sub, target[key], baseline[key]))
for key in target}
tri_stats = diff(tar_tri_stats, base_tri_stats)
bi_stats = diff(tar_bi_stats, base_bi_stats)
tri_ms = tar_tri_ms - base_tri_ms
tri_wpm = tar_tri_wpm - base_tri_wpm
bi_ms = tar_bi_ms - base_bi_ms
bi_wpm = tar_bi_wpm - base_bi_wpm
s.output(f"\nLayout {target_layout} relative to {baseline_layout}")
s.output(f"Overall {tri_ms:+.2f} ms per trigram ({tri_wpm:+.2f} wpm)")
s.output(f"Overall {bi_ms:+.2f} ms per bigram ({bi_wpm:+.2f} wpm)")
tri_header_line = (
"\nTristroke categories freq exact avg_ms ms")
bi_header_line = (
"\nBistroke categories freq exact avg_ms ms")
if show_all:
tri_disp = tri_stats
bi_disp = bi_stats
else:
tri_disp = {cat: vals for (cat, vals) in tri_stats.items()
if (tar_tri_stats[cat][0] or base_tri_stats[cat][0]) and not (
"scissor" in cat[2:] or "sfr" in cat or "sft" in cat)}
bi_disp = {cat: vals for (cat, vals) in bi_stats.items()
if (tar_bi_stats[cat][0] or base_bi_stats[cat][0]) and (
"scissor" not in cat or cat.startswith("."))}
print_analysis_stats(tri_disp, tri_header_line, True)
if not show_all:
s.output(f"Use command \"{hint}\" to see remaining categories")
print_analysis_stats(bi_disp, bi_header_line, True)
def cmd_analyze(args: list[str], s: Session, show_all: bool = False):
if args:
layout_name = " ".join(args)
try:
target_layout = layout.get_layout(layout_name)
except FileNotFoundError:
s.say(f"/layouts/{layout_name} was not found.",
gui_util.red)
return
else:
target_layout = s.analysis_target
s.say("Crunching the numbers >>>", gui_util.green)
s.repl_win.refresh()
tri_stats = analysis.layout_tristroke_analysis(
target_layout, s.typingdata_, s.corpus_settings)
bi_stats = analysis.layout_bistroke_analysis(
target_layout, s.typingdata_, s.corpus_settings)
tri_ms = tri_stats[""][2]
tri_wpm = int(24000/tri_ms) if tri_ms else 0.0
bi_ms = bi_stats[""][2]
bi_wpm = int(12000/bi_ms) if bi_ms else 0.0
s.output(f"\nLayout: {target_layout}")
s.output(f"Overall {tri_ms:.1f} ms per trigram ({tri_wpm} wpm)")
s.output(f"Overall {bi_ms:.1f} ms per bigram ({bi_wpm} wpm)")
tri_header_line = (
"\nTristroke categories freq exact avg_ms ms")
bi_header_line = (
"\nBistroke categories freq exact avg_ms ms")
if show_all:
tri_disp = tri_stats
bi_disp = bi_stats
else:
tri_disp = {cat: vals for (cat, vals) in tri_stats.items()
if vals[0] and not (
"scissor" in cat[2:] or "sfr" in cat or "sft" in cat)}
bi_disp = {cat: vals for (cat, vals) in bi_stats.items()
if vals[0] and ("scissor" not in cat or cat.startswith("."))}
print_analysis_stats(s, tri_disp, tri_header_line)
if not show_all:
s.output("Use command \"fulla[nalyze]\" "
"to see remaining categories")
print_analysis_stats(s, bi_disp, bi_header_line)
register_command(Command(
CommandType.ANALYSIS,
(
"a[nalyze] [layout name]: Detailed layout analysis",
"Uses target layout if no args given.\n"
"This is the main special feature of trialyzer. Uses the selected "
"typing speed data.\n"
"Shows only a more interesting selection of "
"tristroke categories, for brevity - use fullanalyze to see them "
"all."
),
("analyze", "analyse", "a"),
cmd_analyze
))
register_command(Command(
CommandType.ANALYSIS,
(
"fulla[nalyze] [layout name]: Like analyze but shows all tristroke "
"categories",
"Use analyze to see a more concise version."
),
("fullanalyze", "fulla", "fullanalyse"),
lambda args, s: cmd_analyze(args, s, True)
))
def cmd_analyze_diff(args: list[str], s: Session, show_all: bool = False):
if not args:
s.say("Usage: adiff [baseline_layout] <layout>", gui_util.red)
return
baseline_layout = None
lay1, remain = extract_layout_front(args)
if lay1:
if remain:
lay2, _ = extract_layout_front(remain, True)
if lay2:
baseline_layout, target_layout = lay1, lay2
else:
s.say(f"/layouts/{' '.join(remain)} was not found.",
gui_util.red)
return
else:
baseline_layout, target_layout = s.analysis_target, lay1
else:
s.say(f"/layouts/{' '.join(args)} was not found.",
gui_util.red)
return
s.say("Crunching the numbers >>>", gui_util.green)
s.repl_win.refresh()
cmd_analyze_diff_common(s, baseline_layout, target_layout,
show_all, "fulladiff")
register_command(Command(
CommandType.ANALYSIS,
(
"a[nalyze]diff [baseline_layout] <layout>: "
"Like analyze but compares two layouts",
"Shows the incremental stats difference between the specified "
"layouts.\nIf a baseline layout is not given, the analysis target "
"is used."
),
("analyzediff", "diffa", "adiff", "analysediff"),
cmd_analyze_diff
))
register_command(Command(
CommandType.ANALYSIS,
(
"fulla[nalyze]diff [baseline_layout] <layout>: "
"Like analyze but compares two layouts. Shows all tristroke "
"categories",
"Use analyzediff to see a more concise version."
),
("fullanalyzediff", "fullanalysediff", "fulladiff"),
lambda args, s: cmd_analyze_diff(args, s, True)
))
def cmd_analyze_swap(args: list[str], s: Session, show_all: bool = False):
if len(args) < 2:
s.say("Usage: aswap [letter1 ... [with letter2 ...]]", gui_util.red)
return
baseline_layout = s.analysis_target
if "with" in args:
i = args.index("with")
remap_ = remap.set_swap(args[:i], args[i+1:])
else:
remap_ = remap.cycle(*args)
target_layout = layout.Layout(
f"{baseline_layout.name}, {remap_}",
False, repr(baseline_layout))
try:
target_layout.remap(remap_)
except KeyError as ke:
s.say(f"Key '{ke.args[0]}' does not exist "
f"in layout {baseline_layout.name}",
gui_util.red)
return
s.say("Crunching the numbers >>>", gui_util.green)
s.repl_win.refresh()
if not show_all:
s.output("\n" + target_layout.name + "\n"+ repr(target_layout))
s.right_pane.refresh()
cmd_analyze_diff_common(s, baseline_layout, target_layout,
show_all, "fullaswap")
register_command(Command(
CommandType.ANALYSIS,
(
"a[nalyze]swap <key1 key2> [...] [with ...]: Analyze a swap or cycle",
"Same idea as analyzediff, but creates the edited layout on the fly. "
"The edit is not saved."
),
(
"analyzeswap", "aswap", "analyseswap",
"acycle", "analyzecycle", "analysecycle"
),
cmd_analyze_swap
))
register_command(Command(
CommandType.ANALYSIS,
(
"fulla[nalyze]swap <key1 key2> [...] [with ...]: "
"Analyze a swap or cycle. Shows all tristroke categories.",
"Use analyzeswap to see a more concise version."
),
(
"fullanalyzeswap", "fullaswap", "fullanalyseswap",
"fullacycle", "fullanalyzecycle", "fullanalysecycle"
),
lambda args, s: cmd_analyze_diff(args, s, True)
))
def cmd_stats(args: list[str], s: Session):
if args:
layout_name = " ".join(args)
try:
target_layout = layout.get_layout(layout_name)
except FileNotFoundError:
s.say(f"/layouts/{layout_name} was not found.", gui_util.red)
return
else:
target_layout = s.analysis_target
s.say("Crunching the numbers >>>", gui_util.green)
s.repl_win.refresh()
bstats, sstats, tstats, btop, stop = analysis.layout_stats_analysis(
target_layout, s.corpus_settings)
width = 46
lwidth = 14
output = ["", f"{'BIGRAMS ':-<{width}s}"]
output.append(" "*lwidth+"Bigram Skip-1-gram")
bg_labels = (
"Same finger",
"Repeat",
"Any stretch",
" Vertical",
" Lateral",
"Alt hand",
"Same hand"
)
bg_tags = ("sfb", "sfr", "asb", "vsb", "lsb", "ahb", "shb")
for label, tag in zip(bg_labels, bg_tags):
output.append(f"{label:<{lwidth}s}"
f"{bstats[tag]:6.2%}"
f" {' '.join(''.join(bg) for bg in btop[tag]):<8}"
f" {sstats[tag]:6.2%}"
f" {' '.join(''.join(sg) for sg in stop[tag]):<8}")
output.append(f"{'In/out ratio':<{lwidth}s}{bstats['inratio']:5.2f}"
f" {sstats['inratio']:5.2f}")
output.append("")
output.append(f"{'TRIGRAMS ':-<{width}s}")
output.append(f"")
output.append(f"SFT excluded: {tstats['sft']:6.2%}")
output.append(f"Total in/out: {tstats['inratio-trigram']:5.2f}")
output.append(" "*lwidth+"Redir Alt Oneh Roll")
tg_labels = (
"Good",
"Any stretch",
"SFS",
"Weak fingers",
"Total"
)
tg_tags = ("best", "stretch", "sfs", "weak", "total")
for label, tag in zip(tg_labels, tg_tags):
line = f"{label:<{lwidth}s}"
for cat in ("redir", "alt", "oneh", "roll"):
if f'{cat}-{tag}' in tstats.keys():
line += f"{tstats[f'{cat}-{tag}']:6.2%} "
else:
line += " "*8
output.append(line)
output.append(f"{'In/out ratio':<{lwidth+16}s}"
f"{tstats['inratio-oneh']:5.2f}"
f" {sstats['inratio-roll']:5.2f}")
s.output("\n".join(output))
ymax = s.right_pane.getmaxyx()[0]
row = ymax - 20
for r, tag in enumerate(bg_tags, start=row):
s.right_pane.addstr(r, lwidth+7,
f"{' '.join(''.join(bg) for bg in btop[tag]):<8}",
curses.color_pair(gui_util.gray))
s.right_pane.addstr(r, lwidth+24,
f"{' '.join(''.join(sg) for sg in stop[tag]):<8}",
curses.color_pair(gui_util.gray))
s.right_pane.refresh()
register_command(Command(
CommandType.ANALYSIS,
(
"s[tats] [layout name]: More conventional frequency-only analysis",
"Uses target layout if no args given."
),
("stats", "s"),
cmd_stats
))
def cmd_dump(args: list[str], s: Session):
if not args:
s.say("Usage: dump <a[nalysis]|m[edians]>", gui_util.red)
return
if args[0] in ("a", "analysis"):
return cmd_dump_analysis(args, s)
elif args[0] in ("m", "medians"):
return cmd_dump_medians(args, s)
def cmd_dump_analysis(args: list[str], s: Session):
layout_file_list = scan_dir()
if not layout_file_list:
s.say("No layouts found in /layouts/", gui_util.red)
return
s.say(f"Analyzing {len(layout_file_list)} layouts...", gui_util.green)
layouts = [layout.get_layout(name) for name in layout_file_list]
s.right_pane.scroll(2)
rownum = s.right_pane.getmaxyx()[0] - 1
tristroke_display_names = []
for cat in sorted(nstroke.all_tristroke_categories):
try:
tristroke_display_names.append(
nstroke.category_display_names[cat])
except KeyError:
tristroke_display_names.append(cat)
bistroke_display_names = []
for cat in sorted(nstroke.all_bistroke_categories):
try:
bistroke_display_names.append(
nstroke.category_display_names[cat])
except KeyError:
bistroke_display_names.append(cat)
header = ["name"]
for cat in tristroke_display_names:
for colname in ("freq", "exact", "avg_ms", "ms"):
header.append(f"tristroke-{cat}-{colname}")
for cat in bistroke_display_names:
for colname in ("freq", "exact", "avg_ms", "ms"):
header.append(f"bistroke-{cat}-{colname}")
filename = analysis.find_free_filename("output/dump-analysis", ".csv")
with open(filename, "w", newline="") as csvfile:
w = csv.writer(csvfile)
w.writerow(header)
for i, lay in enumerate(layouts):
tridata = analysis.layout_tristroke_analysis(
lay, s.typingdata_, s.corpus_settings)
bidata = analysis.layout_bistroke_analysis(lay, s.typingdata_,
s.corpus_settings)
s.right_pane.addstr(rownum, 0,
f"Analyzed {i+1}/{len(layouts)} layouts")
s.right_pane.refresh()
row = [lay.name]
for cat in sorted(nstroke.all_tristroke_categories):
row.extend(tridata[cat])
for cat in sorted(nstroke.all_bistroke_categories):
row.extend(bidata[cat])
row.extend(repr(lay).split("\n"))
w.writerow(row)
curses.beep()
s.output(f"Done\nSaved as {filename}", gui_util.green)
def cmd_dump_medians(args: list[str], s: Session):
s.say("Crunching the numbers...", gui_util.green)
tristroke_display_names = []
for cat in sorted(nstroke.all_tristroke_categories):
try:
tristroke_display_names.append(nstroke.category_display_names[cat])
except KeyError:
tristroke_display_names.append(cat)
header = ["trigram", "category", "ms_low", "ms_high", "ms_first",
"ms_second", "ms_total"]
exacts = s.typingdata_.exact_tristrokes_for_layout(s.analysis_target)
filename = analysis.find_free_filename("output/dump-catmedians", ".csv")
with open(filename, "w", newline="") as csvfile:
w = csv.writer(csvfile)
w.writerow(header)
for tristroke in exacts:
row = [" ".join(s.analysis_target.to_ngram(tristroke))]
if not row:
continue
row.append(nstroke.tristroke_category(tristroke))
row.extend(sorted(s.typingdata_.tri_medians[tristroke][:2]))
row.extend(s.typingdata_.tri_medians[tristroke])
w.writerow(row)
s.output(f"Done\nSaved as {filename}", gui_util.green)
register_command(Command(
CommandType.ANALYSIS,
(
"dump <a[nalysis]|m[edians]>: Write some data to a csv",
"analysis: full bistroke and tristroke statistics of each layout.\n"
"medians: typing speeds of known trigrams (in the analysis target)"
),
("dump",),
cmd_dump
))
def cmd_fingers(args: list[str], s: Session):
if args:
layout_name = " ".join(args)
try:
target_layout = layout.get_layout(layout_name)
except FileNotFoundError:
s.say(f"/layouts/{layout_name} was not found.", gui_util.red)
return
else:
target_layout = s.analysis_target
s.say("Crunching the numbers >>>", gui_util.green)
finger_stats = analysis.finger_analysis(
target_layout, s.typingdata_, s.corpus_settings)
s.output(f"\nHand/finger breakdown for {target_layout}")
print_finger_stats({k:v for k, v in finger_stats.items() if v[0]})
register_command(Command(
CommandType.ANALYSIS,
(
"f[ingers] [layout name]: Hand/finger usage breakdown",
"Uses analysis target if no layout given."
),
("fingers", "f"),
cmd_fingers
))
def cmd_rank(args: list[str], s: Session):
output = False
if "output" in args:
args.remove("output")
output = True
layout_file_list = scan_dir()
if not layout_file_list:
s.say("No layouts found in /layouts/", gui_util.red)
return
layouts: list[layout.Layout] = []
if not args:
args.append("") # match all layouts
for name in layout_file_list:
for str_ in args:
if str_ in name:
layouts.append(layout.get_layout(name))
break
s.say(f"Analyzing {len(layouts)} layouts >>>", gui_util.green)
data = {}
width = max(len(name) for name in layout_file_list)
padding = 3
col_width = width + 18 + 6
header = "Layout" + " "*(width-3) + "avg_ms wpm exact"
s.output(f"\n{header}")
ymax, xmax = s.right_pane.getmaxyx()
first_row = ymax - len(layouts) - 2