-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnstroke.py
599 lines (539 loc) · 17.6 KB
/
nstroke.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
import itertools
from typing import Sequence, Callable, NamedTuple, Tuple
import operator
import functools
from board import Coord
from fingermap import Finger
# Tristroke = collections.namedtuple("Tristroke", "note fingers coords")
class Tristroke(NamedTuple):
note: str
fingers: Tuple[Finger, ...]
coords: Tuple[Coord, ...]
Nstroke = Tristroke
def bistroke(tristroke: Tristroke, index0: int, index1: int):
# TODO: special handling for slides, altfingers etc
return Nstroke(tristroke.note,
(tristroke.fingers[index0], tristroke.fingers[index1]),
(tristroke.coords[index0], tristroke.coords[index1]))
# If category starts or ends with ".", it's purely a sum of others
# Note that order is important; supercategories before their subcategories
all_bistroke_categories = [
"",
"alt",
"roll.",
"roll.in",
"roll.in.scissor",
"roll.out",
"roll.out.scissor",
"sfb",
"sfr",
"unknown"
]
all_tristroke_categories = [
"",
".scissor",
".scissor.twice",
".scissor_and_skip",
".scissor_skip",
"alt.",
"alt.in",
"alt.in.scissor_skip",
"alt.out",
"alt.out.scissor_skip",
"onehand.",
"onehand.in",
"onehand.in.scissor",
"onehand.in.scissor.twice",
"onehand.out",
"onehand.out.scissor",
"onehand.out.scissor.twice",
"redirect",
"redirect.scissor",
"redirect.scissor_and_skip",
"redirect.scissor_skip",
"roll.",
"roll.in",
"roll.in.scissor",
"roll.out",
"roll.out.scissor",
"sfb.",
"sfb.alt",
"sfb.roll.in",
"sfb.roll.in.scissor",
"sfb.roll.out",
"sfb.roll.out.scissor",
"sfr.",
"sfr.alt",
"sfr.roll.in",
"sfr.roll.in.scissor",
"sfr.roll.out",
"sfr.roll.out.scissor",
"sfs.",
"sfs.alt",
"sfs.redirect",
"sfs.redirect.scissor",
"sfs.redirect.scissor.twice",
"sfs.trill",
"sfs.trill.scissor.twice",
"sft",
"unknown"
]
category_display_names = {
"": "total",
"alt.": "alt",
"onehand.": "onehand",
"roll.": "roll",
".scissor": "*.scissor",
".scissor.twice": "*.scissor.twice",
".scissor_and_skip": "*.scissor_and_skip",
".scissor_skip": "*.scissor_skip",
"sfb.": "sfb",
"sfr.": "sfr",
"sfs.": "sfs"
}
hand_names = {
"R": "right hand total",
"L": "left hand total",
}
finger_names = {
"T": "thumb total",
"I": "index total",
"M": "middle total",
"R": "ring total",
"P": "pinky total"
}
def parse_category(user_input: str = ""):
"""Returns None if category not found."""
if not user_input:
category_name = ""
else:
category_name = user_input.lower().strip()
if "(" in category_name:
category_name = category_name[:category_name.find("(")].strip()
if category_name in all_tristroke_categories:
return category_name
elif category_name in category_display_names.values():
for cat in category_display_names:
if category_display_names[cat] == category_name:
return cat
else:
return None
def category_display_name(category: str):
category_name = (category_display_names[category]
if category in category_display_names else category)
if category.endswith(".") or not category:
category_name += " (total)"
return category_name
def applicable_function(target_category: str) -> Callable[[str], bool]:
"""Given a target category, returns a function(category: str) which tells
whether category is applicable to target_category.
"""
if target_category.endswith("."):
return lambda cat: cat.startswith(target_category)
elif target_category.startswith("."):
return lambda cat: cat.endswith(target_category)
elif not target_category:
return lambda _: True
else:
return lambda cat: cat == target_category
@functools.cache
def compatible(a: Tristroke, b: Tristroke):
"""Assumes it is already known that a.fingers == b.fingers.
Tristrokes are compatible if they are equal, or if
there exists a pair of floats c1 and c2, which when added
to the x-coords of the left and right hands respectively,
cause the tristrokes to become equal."""
if a == b:
return True
for ac, bc in zip(a.coords, b.coords):
if ac.y != bc.y:
return False
for i, j in itertools.combinations(range(3), 2):
if (a.fingers[i] > 0) == (a.fingers[j] > 0):
if ((a.coords[i].x - a.coords[j].x) !=
(b.coords[i].x - b.coords[j].x)):
return False
return True
@functools.cache
def bifinger_category(fingers: Sequence[Finger], coords: Sequence[Coord]):
# Used by both bistroke_category() and tristroke_category()
if Finger.UNKNOWN in fingers:
return "unknown"
elif (fingers[0] > 0) != (fingers[1] > 0):
return "alt"
delta = abs(fingers[1]) - abs(fingers[0])
if delta == 0:
return "sfr" if coords[1] == coords[0] else "sfb"
else:
return "roll.out" if delta > 0 else "roll.in"
@functools.cache
def bistroke_category(nstroke: Nstroke,
index0: int = 0, index1: int = 1):
category = bifinger_category(
(nstroke.fingers[index0], nstroke.fingers[index1]),
(nstroke.coords[index0], nstroke.coords[index1]))
if category.startswith("roll"):
category += detect_scissor(nstroke, index0, index1)
return category
@functools.cache
def tristroke_category(tristroke: Tristroke):
if Finger.UNKNOWN in tristroke.fingers:
return "unknown"
first, skip, second = map(
bifinger_category,
itertools.combinations(tristroke.fingers, 2),
itertools.combinations(tristroke.coords, 2))
if skip in ("sfb", "sfr"):
if first in ("sfb", "sfr"):
return "sft"
if first.startswith("roll"):
if skip == "sfr":
return "sfs.trill" + detect_scissor_roll(tristroke)
else:
return "sfs.redirect" + detect_scissor_roll(tristroke)
else:
return "sfs.alt" + detect_scissor_skip(tristroke)
elif first in ("sfb", "sfr"):
return first + "." + second + detect_scissor(tristroke, 1, 2)
elif second in ("sfb", "sfr"):
return second + "." + first + detect_scissor(tristroke, 0, 1)
elif first == "alt" and second == "alt":
return "alt" + skip[4:] + detect_scissor_skip(tristroke)
elif first.startswith("roll"):
if second.startswith("roll"):
if first == second:
return "onehand" + first[4:] + detect_scissor_roll(tristroke)
else:
return "redirect" + detect_scissor_any(tristroke)
else:
return first + detect_scissor(tristroke, 0, 1) # roll
else: # second.startswith("roll")
return second + detect_scissor(tristroke, 1, 2) # roll
@functools.cache
def detect_scissor(nstroke: Nstroke, index0: int = 0, index1: int = 1):
"""Given that the keys (optionally specified by index) are typed with the
same hand, return \".scissor\" if neighboring fingers must reach coords
that are a distance of 2.0 apart or farther. Return an empty string
otherwise."""
if abs(nstroke.fingers[index0] - nstroke.fingers[index1]) != 1:
return ""
thumbs = (Finger.LT, Finger.RT)
if nstroke.fingers[index0] in thumbs or nstroke.fingers[index1] in thumbs:
return ""
vec = map(operator.sub, nstroke.coords[index0], nstroke.coords[index1])
dist_sq = sum((n**2 for n in vec))
return ".scissor" if dist_sq >= 4 else ""
@functools.cache
def detect_scissor_roll(tristroke: Tristroke):
if detect_scissor(tristroke, 0, 1):
if detect_scissor(tristroke, 1, 2):
return ".scissor.twice"
else:
return ".scissor"
elif detect_scissor(tristroke, 1, 2):
return ".scissor"
else:
return ""
@functools.cache
def detect_scissor_skip(tristroke: Tristroke):
if detect_scissor(tristroke, 0, 2):
return ".scissor_skip"
else:
return ""
@functools.cache
def detect_scissor_any(tristroke: Tristroke):
cat = detect_scissor_roll(tristroke) + detect_scissor_skip(tristroke)
return ".scissor_and_skip" if cat == ".scissor.scissor_skip" else cat
def new_bifinger_category(fingers: Sequence[Finger], coords: Sequence[Coord]):
if Finger.UNKNOWN in fingers:
return "unknown"
if (fingers[0] > 0) != (fingers[1] > 0):
return "alt"
delta = abs(fingers[1]) - abs(fingers[0])
if delta == 0:
return "sfr" if coords[1] == coords[0] else "sfb"
else:
return "out" if delta > 0 else "in"
def new_detect_scissor(ts: Tristroke, i: int, j: int):
HALF_SCISSOR_THRESHOLD = 0.5
FULL_SCISSOR_THRESHOLD = 1.5
if (ts.fingers[i] > 0) != (ts.fingers[j] > 0):
return False
if abs(ts.fingers[i] - ts.fingers[j]) != 1:
return False
dy = ts.coords[i].y - ts.coords[j].y
if abs(dy) < HALF_SCISSOR_THRESHOLD:
return False
lower = j if dy > 0 else i
if ts.fingers[lower].name[1] == "P" and abs(dy) > FULL_SCISSOR_THRESHOLD:
return "fsb"
if ts.fingers[lower].name[1] not in ("M", "R"):
return False
if abs(dy) < FULL_SCISSOR_THRESHOLD:
return "hsb"
return "fsb"
def new_detect_lateral_stretch(ts: Tristroke, i: int, j: int):
"""Must be adjacent fingers and not thumb."""
LATERAL_STRETCH_THRESHOLD = 2.0
if (ts.fingers[i] > 0) != (ts.fingers[j] > 0):
return False
if abs(ts.fingers[i] - ts.fingers[j]) != 1:
return False
if abs(ts.fingers[i]) == 1 or abs(ts.fingers[j]) == 1:
return False
if abs(ts.coords[i].x - ts.coords[j].x) < LATERAL_STRETCH_THRESHOLD:
return False
return True
def new_detect_row_change(ts: Tristroke, i: int, j: int):
"""Must be same hand and not same finger."""
ROW_CHANGE_THRESHOLD = 0.5
if (ts.fingers[i] > 0) != (ts.fingers[j] > 0):
return False
if (ts.fingers[i] == ts.fingers[j]):
return False
if abs(ts.coords[i].y - ts.coords[j].y) < ROW_CHANGE_THRESHOLD:
return False
return True
def any_stretch(ts: Tristroke, *pairs: tuple[tuple[int]]):
for pair in pairs:
if new_detect_lateral_stretch(ts, *pair):
return True
if new_detect_scissor(ts, *pair) == "fsb":
return True
return False
def akl_bistroke_tags(bs: Nstroke) -> Sequence[str]:
"""
Returns any of the following tags:
* sfr (same finger)
* sfb (same finger)
* asb (any stretch)
* vsb (vertical stretch)
* lsb (lateral stretch)
* ahb (alternate hand)
* shb (same hand, other finger)
* shb-in"""
bt = new_bifinger_category(bs.fingers, bs.coords)
match bt:
case "alt":
return ("ahb",)
case "sfb" | "sfr":
return (bt,)
case "unknown":
return ()
case _:
tags = ["shb"]
if bt == "in":
tags.append("shb-in")
stretch = False
if new_detect_lateral_stretch(bs, 0, 1):
tags.append("lsb")
stretch = True
if new_detect_scissor(bs, 0, 1) == "fsb":
tags.append("vsb")
stretch = True
if stretch:
tags.append("asb")
return tags
def akl_tristroke_tags(ts: Tristroke) -> Sequence[str]:
"""
Returns any of the following tags:
* sft
* has-sfb (only if not sft)
* redir-best
* redir-stretch
* redir-sfs
* redir-weak
* redir-total
* alt-best
* alt-stretch
* alt-sfs
* alt-total
* oneh-best
* oneh-stretch
* oneh-in
* oneh-total
* roll-best
* roll-stretch
* roll-in
* roll-total"""
if Finger.UNKNOWN in ts.fingers:
return ()
first, skip, second = map(
new_bifinger_category,
itertools.combinations(ts.fingers, 2),
itertools.combinations(ts.coords, 2))
sfs = False
if skip in ("sfb", "sfr"):
if first in ("sfb", "sfr"):
return ("sft",)
else:
sfs = True
elif first in ("sfb", "sfr") or second in ("sfb", "sfr"):
return ("has-sfb",)
# sfb, sft eliminated by this point. sfs noted
if skip == "alt":
tags = ["roll-total"]
if "in" in (first, second):
tags.append("roll-in")
if any_stretch(ts, (0, 1), (1, 2)):
tags.append("roll-stretch")
else:
tags.append("roll-best")
return tags
# rolls eliminated by this point
if first == "alt":
tags = ["alt-total"]
if sfs:
tags.append("alt-sfs")
if any_stretch(ts, (0, 2)):
tags.append("alt-stretch")
elif not sfs:
tags.append("alt-best")
return tags
# alt eliminated by this point
if first == second:
tags = ["oneh-total"]
if first == "in":
tags.append("oneh-in")
if any_stretch(ts, (0, 1), (1, 2)):
tags.append("oneh-stretch")
else:
tags.append("oneh-best")
return tags
# redir only at this point
tags = ["redir-total"]
best = True
if all(abs(f.value) in range(3, 6) for f in ts.fingers):
best = False
tags.append("redir-weak")
if any_stretch(ts, (0, 1), (1, 2), (0, 2)):
best = False
tags.append("redir-stretch")
if sfs:
tags.append("redir-sfs")
elif best:
tags.append("redir-best")
return tags
def experimental_describe_tristroke(ts: Tristroke):
"""
All tags always appear if they apply, except where noted with "Only for ...".
Tags considering whole trigram:
- sft
- sfb (contains sfb, not sft)
- sfr (contains sfr, not sft)
- sfs (not sft)
- fsb (contains fsb)
- hsb (contains hsb)
- lsb (contains lsb)
- hand-change (reflecting one bigram of sfb. Only for sfb)
- in, out (reflecting one bigram of sfb, sfr, tutu; or both bigrams of rolll. Only for those)
- tutu
- alt
- rolll
- redir
- bad-redir (Only for redir)
Tags considering bigrams:
- (first, second)-(alt, in, out, sfb, sfr, fsb, hsb, lsb, rcb)
- skip-(in, out)
- fss (contains fss)
- hss (contains hss)
- rcs (contains rcs)
"""
tags = set()
if Finger.UNKNOWN in ts.fingers:
return ("unknown",)
first, skip, second = map(
new_bifinger_category,
itertools.combinations(ts.fingers, 2),
itertools.combinations(ts.coords, 2))
tags.add(f"first-{first}")
tags.add(f"second-{second}")
if skip in ("in", "out"):
tags.add(f"skip-{skip}")
if skip in ("sfb", "sfr"):
if first in ("sfb", "sfr"):
tags.add("sft")
else:
tags.add("sfs")
elif first in ("sfb", "sfr"):
tags.add(first)
if second in ("in", "out"):
tags.add(second)
elif second in ("sfb", "sfr"):
tags.add(second)
if first in ("in", "out"):
tags.add(first)
if skip == "alt":
if "sfb" not in (first, second) and "sfr" not in (first, second):
tags.add("tutu")
if "in" in (first, second):
tags.add("in")
else:
tags.add("out")
else:
tags.add("hand-change")
else:
if first in ("in, out") and second in ("in, out"):
if first == second:
tags.add("rolll")
tags.add(first)
else:
tags.add("redir")
if Finger.LI not in ts.fingers and Finger.RI not in ts.fingers:
tags.add("bad-redir")
elif first == "alt" and second == "alt":
tags.add("alt") # includes sfs
# else it's sfb or sfr
if (s1 := new_detect_scissor(ts, 0, 1)):
tags.add(s1)
tags.add(f"first-{s1}")
if (s2 := new_detect_scissor(ts, 1, 2)):
tags.add(s2)
tags.add(f"second-{s2}")
if (ss := new_detect_scissor(ts, 0, 2)):
if "hsb" in ss:
tags.add("hss")
else:
tags.add("fss")
if new_detect_lateral_stretch(ts, 0, 1):
tags.add("first-lsb")
tags.add("lsb")
if new_detect_lateral_stretch(ts, 1, 2):
tags.add("second-lsb")
tags.add("lsb")
if new_detect_lateral_stretch(ts, 0, 2):
tags.add("lss")
if new_detect_row_change(ts, 0, 1):
tags.add("first-rcb")
tags.add("rcb")
if new_detect_row_change(ts, 1, 2):
tags.add("second-rcb")
tags.add("rcb")
if new_detect_row_change(ts, 0, 2):
tags.add("rcs")
if Finger.LT in ts.fingers or Finger.RT in ts.fingers:
tags.add("thumb")
if abs(ts.fingers[1]) == 1:
tags.add("middle-thumb")
return tags
if __name__ == "__main__":
from collections import defaultdict
from statistics import mean
import layout
from typingdata import TypingData
qwerty = layout.get_layout("qwerty")
td = TypingData("tanamr")
all_known = td.exact_tristrokes_for_layout(qwerty)
sf = td.tristroke_speed_calculator(qwerty)
ts_to_cat = {}
cat_to_ts = defaultdict(list)
for ts in qwerty.all_nstrokes():
cat = frozenset(experimental_describe_tristroke(ts))
ts_to_cat[ts] = cat
cat_to_ts[cat].append(ts)
cat_times = {cat: mean(sf(ts)[0] for ts in strokes) for cat, strokes in cat_to_ts.items()}
cat_samples = {cat: [0, len(cat_to_ts[cat])] for cat in cat_times}
for ts in all_known:
cat_samples[frozenset(experimental_describe_tristroke(ts))][0] += 1
for cat in sorted(cat_times, key=lambda c: cat_times[c]):
print(f'{cat_times[cat]:.2f} ms from {cat_samples[cat][0]}/{cat_samples[cat][1]} samples: {", ".join(sorted(list(cat)))}')