keyscore: a scorer, optimizer and GUI for keyboard layouts
Scores layouts for ISO Swedish with the angle mod on Swedish and English text, by Michael Capewell's rules plus row motion, triples, pinky load and finger distance. - src/main.bjo: the report. src/optimize.bjo: simulated annealing. - src/gui.bjo: a bjogui window for tuning the numbers, with help on every number, presets and saved layouts. - corpus/: the texts, and fetch.py for the Wikipedia ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
53a0002907
20 changed files with 64897 additions and 0 deletions
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
.bjo/
|
||||
publish/
|
||||
*.dll
|
||||
*.exe
|
||||
*.pdb
|
||||
*.bjobuild
|
||||
*.runtimeconfig.json
|
||||
*.deps.json
|
||||
55690
corpus/bjolang.txt
Normal file
55690
corpus/bjolang.txt
Normal file
File diff suppressed because it is too large
Load diff
2882
corpus/en.txt
Normal file
2882
corpus/en.txt
Normal file
File diff suppressed because it is too large
Load diff
72
corpus/fetch.py
Executable file
72
corpus/fetch.py
Executable file
|
|
@ -0,0 +1,72 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Fetches the prose corpus: plain text of featured Wikipedia articles.
|
||||
|
||||
./corpus/fetch.py writes corpus/sv.txt and corpus/en.txt
|
||||
|
||||
- A fixed-seed sample of the featured articles of sv and en Wikipedia, so a
|
||||
rerun fetches the same articles (unless the categories change).
|
||||
- The text is the TextExtracts plain-text extract: no markup. Section
|
||||
headings ("== ... ==") and empty lines are dropped.
|
||||
- Stops at about TARGET characters per language.
|
||||
"""
|
||||
import json, random, sys, time, urllib.error, urllib.parse, urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
TARGET = 1_500_000
|
||||
CATEGORIES = {
|
||||
'sv': 'Kategori:Wikipedia:Utmärkta artiklar',
|
||||
'en': 'Category:Featured articles',
|
||||
}
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def api(lang, **params):
|
||||
params.update(format='json', formatversion='2')
|
||||
url = f'https://{lang}.wikipedia.org/w/api.php?' + urllib.parse.urlencode(params)
|
||||
req = urllib.request.Request(url, headers={'User-Agent': 'keyscore-corpus/0.1'})
|
||||
for attempt in range(8):
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return json.load(r)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 429: raise
|
||||
wait = int(e.headers.get('Retry-After') or 0) or 5 * 2 ** attempt
|
||||
print(f' rate-limited, waiting {wait} s', file=sys.stderr)
|
||||
time.sleep(wait)
|
||||
raise RuntimeError(f'still rate-limited: {url}')
|
||||
|
||||
|
||||
def titles(lang, limit_pages=4):
|
||||
out, cont = [], {}
|
||||
for _ in range(limit_pages):
|
||||
r = api(lang, action='query', list='categorymembers', cmtitle=CATEGORIES[lang],
|
||||
cmnamespace=0, cmlimit=500, **cont)
|
||||
out += [m['title'] for m in r['query']['categorymembers']]
|
||||
if 'continue' not in r: break
|
||||
cont = {'cmcontinue': r['continue']['cmcontinue']}
|
||||
return out
|
||||
|
||||
|
||||
def extract(lang, title):
|
||||
r = api(lang, action='query', prop='extracts', explaintext=1, titles=title)
|
||||
text = r['query']['pages'][0].get('extract', '')
|
||||
lines = [l.strip() for l in text.split('\n')]
|
||||
return '\n'.join(l for l in lines if l and not l.startswith('=='))
|
||||
|
||||
|
||||
def main():
|
||||
for lang in CATEGORIES:
|
||||
names = titles(lang)
|
||||
random.Random(1).shuffle(names)
|
||||
parts, size = [], 0
|
||||
for name in names:
|
||||
if size >= TARGET: break
|
||||
text = extract(lang, name)
|
||||
parts.append(text); size += len(text)
|
||||
print(f'{lang}: {name} ({len(text)} chars, {size} in all)', file=sys.stderr)
|
||||
time.sleep(1.5)
|
||||
(HERE / f'{lang}.txt').write_text('\n'.join(parts) + '\n', encoding='utf-8')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
3160
corpus/sv.txt
Normal file
3160
corpus/sv.txt
Normal file
File diff suppressed because it is too large
Load diff
19
manifest.bjodat
Normal file
19
manifest.bjodat
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
(package
|
||||
(name (keyscore))
|
||||
(version "0.1.0")
|
||||
|
||||
;; What this package needs. One (package ...) clause each:
|
||||
;;
|
||||
;; (depends
|
||||
;; (package (name (bjorsec))
|
||||
;; (version (version-at-least "0.1"))
|
||||
;; (source (git (url "https://github.com/bjoli/bjorsec")))))
|
||||
;;
|
||||
;; A package on disk, instead of one to fetch:
|
||||
;;
|
||||
;; (depends
|
||||
;; (package (name (bjorsec)) (source (path (dir "../bjorsec")))))
|
||||
|
||||
;; The GUI, src/gui.bjo.
|
||||
(depends
|
||||
(package (name (bjogui)) (source (path (dir "../bjogui"))))))
|
||||
219
packages.lock.json
Normal file
219
packages.lock.json
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
{
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Avalonia": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "Vw+gNvv4RXK5hLeVI9PfalhxPai6hrQjIElfoCDQK1fXTpk+vRyfhuhprrh+EIeuJtoYCy+AsSrqR1wgU28zeQ==",
|
||||
"dependencies": {
|
||||
"Avalonia.BuildServices": "11.3.2",
|
||||
"Avalonia.Remote.Protocol": "12.1.5",
|
||||
"MicroCom.Runtime": "0.11.6"
|
||||
}
|
||||
},
|
||||
"Avalonia.Angle.Windows.Natives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.27548.20260419",
|
||||
"contentHash": "l17nI3XVDN3oMnpjf2pnmJg0YTwK4m6NLsn/itAjDMdObTFxN77D5F1M9sRMSfViSY3KKcse1ROczwgoWLJsnA=="
|
||||
},
|
||||
"Avalonia.BuildServices": {
|
||||
"type": "Transitive",
|
||||
"resolved": "11.3.2",
|
||||
"contentHash": "qHDToxto1e3hci5YqbG9n0Ty8mlp3zBUN5wT66wKqaDVzXyQ0do3EnRILd4Ke9jpvsktaPpgE0YjEk7hornryQ=="
|
||||
},
|
||||
"Avalonia.Desktop": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "l1jo9qKJjJ68gcuUwHgNgpsHV6STcvqfYTFvFPprOf949gmE506X/d7Mox/y36tU2BSWBqLGZ1M3mh8Ggl2g/Q==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"Avalonia.HarfBuzz": "12.1.5",
|
||||
"Avalonia.Native": "12.1.5",
|
||||
"Avalonia.Skia": "12.1.5",
|
||||
"Avalonia.Win32": "12.1.5",
|
||||
"Avalonia.X11": "12.1.5"
|
||||
}
|
||||
},
|
||||
"Avalonia.Fonts.Inter": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "SeFNLktbuxrHxUzPjYubzWB1O9HVCNo3IezZZ9SgkFBAcKcSYrY2KcD8lfP7QWMGxPUvqdLyn0TmioR9d3nZUg==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5"
|
||||
}
|
||||
},
|
||||
"Avalonia.FreeDesktop": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "XqLCj3V2PJsIaNANnFwolEv9Ng8LT7XM//dG39wPv/oeVTijjLNbayWAkeQlpKxi6RtAkjfnXjK+xK/S1caQLA==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"Tmds.DBus.Protocol": "0.94.1"
|
||||
}
|
||||
},
|
||||
"Avalonia.FreeDesktop.AtSpi": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "MTqCBRv1+nkUHPUeMtbh4/dA3AaCEA6LpIT+ZtCnWO4QSxEQFIdlyMZa/d4y6qBBIcxw2DhdY3+JzdhCn6DpUg==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5"
|
||||
}
|
||||
},
|
||||
"Avalonia.HarfBuzz": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "3kspGPaRVrCzgMi4Rv4N33VNbQNN4wcY4NoCufYxKF/kvYqPbrAnGD2Mjm6Kmc3IA3QrLbj5UJpg8WDTAd4cPw==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"HarfBuzzSharp": "8.3.1.3",
|
||||
"HarfBuzzSharp.NativeAssets.Linux": "8.3.1.3",
|
||||
"HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.3"
|
||||
}
|
||||
},
|
||||
"Avalonia.Headless": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "0s3+IiZ/lP7A2R80OOFc3YiSK3qnWOLO9KVsMBGjLX/kg4JSsU2YJiAMNTZIihDmIOYV0VHECJCzsSNKCTMXww==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"Avalonia.Fonts.Inter": "12.1.5",
|
||||
"Avalonia.HarfBuzz": "12.1.5"
|
||||
}
|
||||
},
|
||||
"Avalonia.Native": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "LsC92ialAyccwXiqSjSHVlYGbASfB8XHbGT0XB3zqERF7PM7M3KjSnMgGc1HkzvwtGX+GgTYap6PV8N9H6un8Q==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5"
|
||||
}
|
||||
},
|
||||
"Avalonia.Remote.Protocol": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "yNSke7MNKxJrgcTOQJk70QhPU568dxwRMeQCSmq9N7IGbpPS4zpbr4o6e8rLF/8UfASBQN/yuTgqUfa2nwf6Iw=="
|
||||
},
|
||||
"Avalonia.Skia": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "irfPBtb4UoAT0qfRviYsALBwo0JwXnziRNOTQLzzAQt3eoNPyKFLBsgyj5hE4+6vgunQ7hltEHlvTHPkCoreIg==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"HarfBuzzSharp": "8.3.1.3",
|
||||
"HarfBuzzSharp.NativeAssets.Linux": "8.3.1.3",
|
||||
"HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.3",
|
||||
"SkiaSharp": "3.119.4",
|
||||
"SkiaSharp.NativeAssets.Linux": "3.119.4",
|
||||
"SkiaSharp.NativeAssets.WebAssembly": "3.119.4"
|
||||
}
|
||||
},
|
||||
"Avalonia.Themes.Fluent": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "FGjtJEpeVIbth+u4r507c9nbm1NQWLTvT3RC4e/yqDceRC4crAl37zVUloElA6rexDz69y0WvDfMLGX+t12yBQ==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5"
|
||||
}
|
||||
},
|
||||
"Avalonia.Win32": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "QHfRLCyvVzj74AMCohS5a08Jz5f7VAeRgZ0SJsDTSfqxRzdbw9DXpKsncu21YmEvRWxMPkwyoB9cx9dvS1Bwmg==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"Avalonia.Angle.Windows.Natives": "2.1.27548.20260419"
|
||||
}
|
||||
},
|
||||
"Avalonia.X11": {
|
||||
"type": "Transitive",
|
||||
"resolved": "12.1.5",
|
||||
"contentHash": "5EK2QrM9I3Lm3Aq/ZSpJjg1ZzBXl7YE9PxaB/mLxF9ysZz8qgFaJ5Zj+A9NdtAszupA+81Z3B9EmZP++2Xs4Ug==",
|
||||
"dependencies": {
|
||||
"Avalonia": "12.1.5",
|
||||
"Avalonia.FreeDesktop": "12.1.5",
|
||||
"Avalonia.FreeDesktop.AtSpi": "12.1.5",
|
||||
"Avalonia.Skia": "12.1.5"
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.3",
|
||||
"contentHash": "NGZ2+ZVNPM+NdHB/asW0/ykWngyHWwcqjrbN2nDeH1B/aptPGlCUl8wkQ2cSJxw5fdWgdmIPmNuTPWpLwNVXWg==",
|
||||
"dependencies": {
|
||||
"HarfBuzzSharp.NativeAssets.Win32": "8.3.1.3",
|
||||
"HarfBuzzSharp.NativeAssets.macOS": "8.3.1.3"
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.3",
|
||||
"contentHash": "RI6A1LgmooU30+4QIyFt5rmBCzP0VzTR+587IJSGvYIsHHWlahFufihYxtraLfsIhW7I8dn6+xX+DZGygOPKWQ=="
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.3",
|
||||
"contentHash": "KPTq0xnslkI6nAo0jh3ptcQPJvZZr7MWYXa2jUe4SnHc9q+JlHElmNXp0sfFoiTgoCX7WOYpYsurypuH9Gehxw=="
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.WebAssembly": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.3",
|
||||
"contentHash": "w2QfdNm9Uz/sUa0B5D+OnVQhyq3G/fBq6ibQMdWBlQqqwh0g0/5j3RFvYqZAmRZ5+RzvjVe8o8SFFnWYUSkuxA=="
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.3",
|
||||
"contentHash": "bx8CE8Js+XGX8PUxAHCBDEORt5aaBYtMN4Hr9QFs57Xithh6yjUyYqksizH6eRDhJkwsGI+SXWmPmMm8lZC9Pw=="
|
||||
},
|
||||
"MicroCom.Runtime": {
|
||||
"type": "Transitive",
|
||||
"resolved": "0.11.6",
|
||||
"contentHash": "NdNWGDiZ6eS/Mf/9+QHR91cj1K7Hy+PX9yrHI/zM7xFYuj9IWT2uxtB6sCHjrnxAeLV9fut1R6zHDUGKX6f9lQ=="
|
||||
},
|
||||
"SkiaSharp": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.119.4",
|
||||
"contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==",
|
||||
"dependencies": {
|
||||
"SkiaSharp.NativeAssets.Win32": "3.119.4",
|
||||
"SkiaSharp.NativeAssets.macOS": "3.119.4"
|
||||
}
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Linux": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.119.4",
|
||||
"contentHash": "UAyVzbqNfZsZbKbzj68zXLyUyF/SbTKmzTfOO6qDu++dtIUMMTzPBe8oOuzU/DiewpfKoUUlOSsJmqWc6blxBw=="
|
||||
},
|
||||
"SkiaSharp.NativeAssets.macOS": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.119.4",
|
||||
"contentHash": "fgBOWEqbY012x7gMfJU4ezgz6dfhJb30Z6YdW35h85Zoe39+a8YNbAAwL29ihPfWoppg5AjvyKNzD1oCvlqWwA=="
|
||||
},
|
||||
"SkiaSharp.NativeAssets.WebAssembly": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.119.4",
|
||||
"contentHash": "S1HOxtBbD4bYDtA2e9WH5TX+lxqRrTPvKjrjttRhxnHNNu7YY8VFo/LeCP7tNqoTA6PV+8vsvNbmRUEC2ip8RQ=="
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Win32": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.119.4",
|
||||
"contentHash": "XOpbx/4CReO2wYsq2s6rbvdauc6dntG4Zv499sHGTJ87bwZaFXszFkwql3+FIZMc8kUPeaj3Mx2ezIJmo8a1Kg=="
|
||||
},
|
||||
"Tmds.DBus.Protocol": {
|
||||
"type": "Transitive",
|
||||
"resolved": "0.94.1",
|
||||
"contentHash": "11YMr7FnAbL83bQmVxlhbIKHvSLxjO81D12Ej0QMSGXMDTxNA9MTOa4MQxx43nv5el/efuPHwzyrj6a5ha2gug=="
|
||||
},
|
||||
"bjopackage.bjogui": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Avalonia": "[12.1.5, )",
|
||||
"Avalonia.Desktop": "[12.1.5, )",
|
||||
"Avalonia.Headless": "[12.1.5, )",
|
||||
"Avalonia.Skia": "[12.1.5, )",
|
||||
"Avalonia.Themes.Fluent": "[12.1.5, )"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
138
src/board.bjo
Normal file
138
src/board.bjo
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
;; The physical keyboard: the main block of an ISO Swedish keyboard, typed
|
||||
;; with the angle mod.
|
||||
;;
|
||||
;; - Rows: 0 is the top row (Q), 1 the home row (A), 2 the bottom row (<).
|
||||
;; - Columns count from the left of each row: from Q, from A and from <. Two
|
||||
;; keys of one row are adjacent when their columns differ by 1.
|
||||
;; - Fingers: 0 pinky, 1 ring, 2 middle, 3 index, on either hand.
|
||||
;; - Angle mod: on the bottom row the left pinky types <, the ring finger Z,
|
||||
;; the middle finger X, and the index C and V. B is an index stretch.
|
||||
;; - A stretch key is one the hand reaches for: the centre columns T G B and
|
||||
;; Y H, and the right pinky's keys past P, Ö and -. N is not a stretch key:
|
||||
;; it is as near J as V is to F.
|
||||
;; - Keys are named by what Swedish QWERTY prints on them.
|
||||
;;
|
||||
;; The costs grade Michael Capewell's grid. The keys he leaves at 0 cost more
|
||||
;; the farther they are from the home row: home 0, the top row 1-4, the bottom
|
||||
;; row 1-4. On the top row the middle finger is cheapest, then the index. The index keys of the bottom row cost 1: with the angle mod, C and
|
||||
;; V lie as near F as N and M lie to J.
|
||||
;;
|
||||
;; 10 3 1 2 4 | 10 2 1 3 10 15 top row
|
||||
;; 0 0 0 0 2 | 2 0 0 0 0 5 15 home row
|
||||
;; 10 4 3 1 1 10 | 1 1 3 4 10 bottom row
|
||||
;;
|
||||
;; These are the default costs. (keyscore params) holds the costs scored
|
||||
;; with, and the key weight every cost is multiplied by.
|
||||
;;
|
||||
;; The left and right halves differ only at T and Y: the top row is shifted
|
||||
;; right of the home row, so T is near F and Y is far from J.
|
||||
;;
|
||||
;; Positions, for finger distance, are in key widths, as on an ISO board:
|
||||
;; - x is 0 at A. The top row starts a quarter key left of the home row, at
|
||||
;; Q, and the bottom row half a key left, at <.
|
||||
;; - y is the row: 0 top, 1 home, 2 bottom. Rows are one key width apart.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std maths))
|
||||
|
||||
(export Key board key-named key-position home-key key-distance)
|
||||
|
||||
;; - index: the key's place in `board`.
|
||||
;; - cost: the default grid cost, before the key weight.
|
||||
(type (: Key (Record (: name string)
|
||||
(: index int)
|
||||
(: left? bool)
|
||||
(: finger int)
|
||||
(: row int)
|
||||
(: column int)
|
||||
(: stretch? bool)
|
||||
(: cost int))))
|
||||
|
||||
(def pinky 0)
|
||||
(def ring 1)
|
||||
(def middle 2)
|
||||
(def index 3)
|
||||
|
||||
(: (-> string int int bool int bool int Key))
|
||||
(defun (key name row column left? finger stretch? cost)
|
||||
(Key (name name) (index 0) (left? left?) (finger finger) (row row) (column column)
|
||||
(stretch? stretch?) (cost cost)))
|
||||
|
||||
;; The keys of `board`, before their indices are set.
|
||||
(: (Vec Key))
|
||||
(def keys
|
||||
(let ((L #t) (R #f) (reach #t) (no #f))
|
||||
[;; Top row
|
||||
(key "q" 0 0 L pinky no 10)
|
||||
(key "w" 0 1 L ring no 3)
|
||||
(key "e" 0 2 L middle no 1)
|
||||
(key "r" 0 3 L index no 2)
|
||||
(key "t" 0 4 L index reach 4)
|
||||
(key "y" 0 5 R index reach 10)
|
||||
(key "u" 0 6 R index no 2)
|
||||
(key "i" 0 7 R middle no 1)
|
||||
(key "o" 0 8 R ring no 3)
|
||||
(key "p" 0 9 R pinky no 10)
|
||||
(key "å" 0 10 R pinky reach 15)
|
||||
;; Home row
|
||||
(key "a" 1 0 L pinky no 0)
|
||||
(key "s" 1 1 L ring no 0)
|
||||
(key "d" 1 2 L middle no 0)
|
||||
(key "f" 1 3 L index no 0)
|
||||
(key "g" 1 4 L index reach 2)
|
||||
(key "h" 1 5 R index reach 2)
|
||||
(key "j" 1 6 R index no 0)
|
||||
(key "k" 1 7 R middle no 0)
|
||||
(key "l" 1 8 R ring no 0)
|
||||
(key "ö" 1 9 R pinky no 0)
|
||||
(key "ä" 1 10 R pinky reach 5)
|
||||
(key "'" 1 11 R pinky reach 15)
|
||||
;; Bottom row, angle mod
|
||||
(key "<" 2 0 L pinky no 10)
|
||||
(key "z" 2 1 L ring no 4)
|
||||
(key "x" 2 2 L middle no 3)
|
||||
(key "c" 2 3 L index no 1)
|
||||
(key "v" 2 4 L index no 1)
|
||||
(key "b" 2 5 L index reach 10)
|
||||
(key "n" 2 6 R index no 1)
|
||||
(key "m" 2 7 R index no 1)
|
||||
(key "," 2 8 R middle no 3)
|
||||
(key "." 2 9 R ring no 4)
|
||||
(key "-" 2 10 R pinky no 10)]))
|
||||
|
||||
;; Every key a layout can put a character on, by row and column, each with
|
||||
;; its index.
|
||||
(: (Vec Key))
|
||||
(def board
|
||||
(loop (:for k keys) (:for i (range 0 (vec-length keys)))
|
||||
(:acc out (vecing (record-set k (index i))))))
|
||||
|
||||
;; The key printed with `name` on Swedish QWERTY. Raises if there is none.
|
||||
(: (-> string Key))
|
||||
(defun (key-named name)
|
||||
(match (find (fun (k) (= (record-ref k name) name)) board)
|
||||
((Some k) k)
|
||||
(None (panic! (str "no key is named " name)))))
|
||||
|
||||
;; Where `k` is, in key widths: see the header.
|
||||
(: (-> Key (Tuple double double)))
|
||||
(defun (key-position k)
|
||||
(def offset (match (record-ref k row) (0 -0.25) (1 0.0) (_ -0.5)))
|
||||
(Tuple (+ offset (cast double (record-ref k column))) (cast double (record-ref k row))))
|
||||
|
||||
;; The home-row key that `k`'s finger rests on: the one of its hand and
|
||||
;; finger on the home row that is not a stretch key.
|
||||
(: (-> Key Key))
|
||||
(defun (home-key k)
|
||||
(option-ref (find (fun (h) (and (= (record-ref h row) 1)
|
||||
(= (record-ref h left?) (record-ref k left?))
|
||||
(= (record-ref h finger) (record-ref k finger))
|
||||
(not (record-ref h stretch?))))
|
||||
board)))
|
||||
|
||||
;; How far apart `a` and `b` are, in key widths.
|
||||
(: (-> Key Key double))
|
||||
(defun (key-distance a b)
|
||||
(def (Tuple ax ay) (key-position a))
|
||||
(def (Tuple bx by) (key-position b))
|
||||
(sqrt (+ (* (- ax bx) (- ax bx)) (* (- ay by) (- ay by)))))
|
||||
730
src/gui.bjo
Normal file
730
src/gui.bjo
Normal file
|
|
@ -0,0 +1,730 @@
|
|||
;; A window for tuning the scorer's numbers and seeing what they do.
|
||||
;;
|
||||
;; bjo run src/gui.bjo
|
||||
;;
|
||||
;; Run it from the package's folder: the texts are read from corpus/.
|
||||
;;
|
||||
;; - Left: every layout's score, best first, rescored as soon as a number
|
||||
;; changes. A click chooses a layout for the Layout and Search tabs.
|
||||
;; - Rules: the numbers of (keyscore params), by group. Key costs: each key's
|
||||
;; cost, on the board.
|
||||
;; - Layout: the chosen layout on the board, and the parts of its score.
|
||||
;; - Search: runs (keyscore search) from the chosen layout with the numbers as
|
||||
;; they are. "Keep" adds a result to the list, "Copy" puts it on the
|
||||
;; clipboard as a make-layout form.
|
||||
;; - Save writes the numbers to params.txt, which the other programs read.
|
||||
;; Reload reads it again; Defaults puts back `default-params`, unsaved.
|
||||
;; - Presets, on the Rules tab: named sets of numbers in presets/. See
|
||||
;; (keyscore saved).
|
||||
;; - Layouts can be saved by name, from the Layout tab or from a search
|
||||
;; result, to saved-layouts.txt. The saved layouts are listed at start.
|
||||
;; - An "i" mark shows what a number or an option does.
|
||||
|
||||
(import (std prelude))
|
||||
(import (only (std fmt) numeric render->string))
|
||||
(import (except (bjogui view) Key))
|
||||
(import (bjogui app))
|
||||
(import (bjogui draw))
|
||||
(import (keyscore board))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore saved))
|
||||
(import (keyscore score))
|
||||
(import (keyscore search))
|
||||
(import (keyscore texts))
|
||||
|
||||
(export Model Msg initial gui-update view subscriptions ranking)
|
||||
|
||||
;; --- the model ------------------------------------------------------------------
|
||||
|
||||
;; - params: the numbers scored with.
|
||||
;; - counts: the counts of the texts of `params`, empty until they are read.
|
||||
;; - layouts: (keyscore layouts), then the saved layouts and the search
|
||||
;; results kept.
|
||||
;; - scores: [layout][text], for `generation`: each change of the numbers
|
||||
;; starts a new one, and a score of an older one is dropped.
|
||||
;; - chosen: the layout the Layout and Search tabs show, by index in `layouts`.
|
||||
;; - options, searching, results: the Search tab.
|
||||
;; - saved: the names of the layouts in `layouts-file`.
|
||||
;; - layout-name: the name a layout is saved as.
|
||||
;; - presets, preset-name: the presets, and the name one is saved as.
|
||||
(type (: Model (Record (: params Params)
|
||||
(: counts (Vec Counts))
|
||||
(: layouts (Vec Layout))
|
||||
(: scores (Vec (Vec Score)))
|
||||
(: generation int)
|
||||
(: chosen int)
|
||||
(: tab int)
|
||||
(: options Options)
|
||||
(: searching bool)
|
||||
(: results (Vec Found))
|
||||
(: kept int)
|
||||
(: saved (Vec string))
|
||||
(: layout-name string)
|
||||
(: presets (Vec string))
|
||||
(: preset-name string)
|
||||
(: status string))))
|
||||
|
||||
(type (: Msg (Union (: Counted (Vec Counts))
|
||||
(: Scored int (Vec (Vec Score)))
|
||||
(: SetParam int double)
|
||||
(: Choose int)
|
||||
(: Tab int)
|
||||
(: SetRuns double)
|
||||
(: SetSteps double)
|
||||
(: SetTStart double)
|
||||
(: SetVowels bool)
|
||||
(: SetFixed string)
|
||||
Search
|
||||
(: Searched (Vec Found))
|
||||
(: Failed string)
|
||||
(: Keep int)
|
||||
(: Copy int)
|
||||
Save
|
||||
Saved
|
||||
Reload
|
||||
(: Loaded Params)
|
||||
Defaults
|
||||
(: SetPresetName string)
|
||||
SavePreset
|
||||
(: LoadPreset string)
|
||||
(: PresetLoaded string Params)
|
||||
(: DeletePreset string)
|
||||
(: Listed string (Vec string))
|
||||
(: SetLayoutName string)
|
||||
SaveLayout
|
||||
(: SaveResult int)
|
||||
RemoveLayout
|
||||
(: Wrote string)
|
||||
Noop)))
|
||||
|
||||
;; The layouts of `layouts-file` when the program starts.
|
||||
(: (Vec Layout))
|
||||
(def saved-at-start (read-saved-layouts))
|
||||
|
||||
(: (-> Layout string))
|
||||
(defun (lname l) (record-ref l name))
|
||||
|
||||
|
||||
(: Model)
|
||||
(def initial
|
||||
(Model (params (current-params))
|
||||
(counts [])
|
||||
(layouts (vec-append layouts saved-at-start))
|
||||
(scores [])
|
||||
(generation 0)
|
||||
(chosen (- (vec-length layouts) 1))
|
||||
(tab 0)
|
||||
(options (Options (runs 12) (steps 1000000) (t-start 0.3) (vowels-left #f) (fixed "")))
|
||||
(searching #f)
|
||||
(results [])
|
||||
(kept 0)
|
||||
(saved (vec-map lname saved-at-start))
|
||||
(layout-name "")
|
||||
(presets (preset-names))
|
||||
(preset-name "")
|
||||
(status "Reading the texts…")))
|
||||
|
||||
;; --- scoring --------------------------------------------------------------------
|
||||
|
||||
;; The score of each of `ls` on each of `counts`.
|
||||
(: (-> Params (Vec Layout) (Vec Counts) (Vec (Vec Score))))
|
||||
(defun (score-all p ls counts)
|
||||
(vec-map (fun (l) (vec-map (fun (c) (score-layout p l c)) counts)) ls))
|
||||
|
||||
;; The mean of `xs` weighted by the texts' weights, or 0 when none weighs
|
||||
;; anything.
|
||||
(: (-> Params (Vec double) double))
|
||||
(defun (mean p xs)
|
||||
(def cs (record-ref p corpora))
|
||||
(if (> (vec-fold (fun (c t) (+ t (corpus-weight c))) 0.0 cs) 0.0) (weighted-mean cs xs) 0.0))
|
||||
|
||||
;; `f` of each text's score of the layout `i`, as the weighted mean.
|
||||
(: (-> Model int (-> Score double) double))
|
||||
(defun (mean-of m i f) (mean (.params m) (vec-map f (vec-ref (.scores m) i))))
|
||||
|
||||
;; The indices of the layouts, best first. Empty until they are scored.
|
||||
(: (-> Model (Vec int)))
|
||||
(defun (ranking m)
|
||||
(if (= (vec-length (.scores m)) (vec-length (.layouts m)))
|
||||
(vec-sort-by (fun (a b) (compare (mean-of m a (fun (s) (.total s))) (mean-of m b (fun (s) (.total s)))))
|
||||
(->vec (range 0 (vec-length (.layouts m)))))
|
||||
[]))
|
||||
|
||||
;; A message for the result of `blocking` work: `(f x)` for its value, or
|
||||
;; `(Failed what)` when it raised.
|
||||
(: (-> (-> %a Msg) string (-> (Result System.Exception %a) Msg)))
|
||||
(defun (on-ok f what)
|
||||
(fun (r) (match r ((Ok x) (f x)) ((Err _) (Failed what)))))
|
||||
|
||||
;; The model with `p`, and the command that scores the layouts with it.
|
||||
(: (-> Model Params (Tuple Model (List (Event Msg)))))
|
||||
(defun (rescore m p)
|
||||
(def g (+ (.generation m) 1))
|
||||
(def ls (.layouts m))
|
||||
(def counts (.counts m))
|
||||
(if (= (vec-length counts) 0)
|
||||
(next (record-set m (params p) (generation g)))
|
||||
(next (record-set m (params p) (generation g))
|
||||
(wrap (blocking (fun () (score-all p ls counts)))
|
||||
(on-ok (fun (s) (Scored g s)) "Scoring failed.")))))
|
||||
|
||||
;; `step` with the command `c` as well.
|
||||
(: (-> (Tuple Model (List (Event Msg))) (Event Msg) (Tuple Model (List (Event Msg)))))
|
||||
(defun (and-then step c)
|
||||
(def (Tuple m cs) step)
|
||||
(Tuple m (cons c cs)))
|
||||
|
||||
;; The index of the layout named `n` in `ls`, if there is one.
|
||||
(: (-> (Vec Layout) string (Option int)))
|
||||
(defun (index-named ls n)
|
||||
(find (fun (i) (= (lname (vec-ref ls i)) n)) (range 0 (vec-length ls))))
|
||||
|
||||
;; The command that writes the saved layouts of `ls` to `layouts-file`.
|
||||
(: (-> (Vec Layout) (Vec string) string (Event Msg)))
|
||||
(defun (write-layouts ls saved done)
|
||||
(def built (vec-length layouts))
|
||||
(def to-write (loop (:for l ls) (:for i (range 0 (vec-length ls)))
|
||||
(:when (and (>= i built) (vec-contains? saved (lname l))))
|
||||
(:acc out (vecing l))))
|
||||
(wrap (blocking (fun () (write-saved-layouts to-write) #t))
|
||||
(on-ok (fun (_) (Wrote done)) (str "Could not write " layouts-file "."))))
|
||||
|
||||
(: string)
|
||||
(def bad-name "A name cannot be empty, start or end with a space, start with a dot, or hold / \\ or a tab.")
|
||||
|
||||
;; `m` with `l` saved as `name`, and the commands that score the layouts and
|
||||
;; write the file.
|
||||
;;
|
||||
;; - replacing: the index of a layout that `l` takes the place of, such as a
|
||||
;; kept result or a saved layout given a new name. A built-in layout is
|
||||
;; never replaced.
|
||||
;; - Another layout that is not built in and has the same name is replaced.
|
||||
;; - choose?: whether the saved layout becomes the chosen one. If not, the
|
||||
;; chosen layout stays chosen, unless it is replaced.
|
||||
;; - Rejects an invalid name, and the name of a built-in layout.
|
||||
(: (-> Model Layout (Option int) string bool (Tuple Model (List (Event Msg)))))
|
||||
(defun (save-layout m l replacing name choose?)
|
||||
(def ls (.layouts m))
|
||||
(def built (vec-length layouts))
|
||||
(cond
|
||||
((not (valid-name? name)) (next (record-set m (status bad-name))))
|
||||
((some? (index-named layouts name))
|
||||
(next (record-set m (status (str name " is a built-in layout. Choose another name.")))))
|
||||
(else
|
||||
(def replaced (match replacing
|
||||
((Some i) (if (>= i built) (Some i) None))
|
||||
(None None)))
|
||||
(def old (match replaced ((Some i) (Some (lname (vec-ref ls i)))) (None None)))
|
||||
(def others (loop (:for x ls) (:for i (range 0 (vec-length ls)))
|
||||
(:when (or (< i built)
|
||||
(and (not (= (Some i) replaced)) (not (= (lname x) name)))))
|
||||
(:acc out (vecing x))))
|
||||
(def new-ls (vec-append others [(record-set l (name name))]))
|
||||
(def last (- (vec-length new-ls) 1))
|
||||
(def before (lname (vec-ref ls (.chosen m))))
|
||||
(def chosen (if choose? last (option-ref-or (index-named new-ls before) last)))
|
||||
(def saved (vec-append (vec-filter (fun (n) (not (or (= n name) (= (Some n) old)))) (.saved m)) [name]))
|
||||
(and-then (rescore (record-set m (layouts new-ls) (saved saved) (chosen chosen) (scores [])
|
||||
(layout-name name))
|
||||
(.params m))
|
||||
(write-layouts new-ls saved (str "Saved the layout " name " to " layouts-file "."))))))
|
||||
|
||||
;; Whether `l` types a vowel on the right hand.
|
||||
(: (-> Layout bool))
|
||||
(defun (vowel-right? l)
|
||||
(any? (fun (c) (match (layout-key l c)
|
||||
((Some k) (not (record-ref k left?)))
|
||||
(None #f)))
|
||||
(->list "aeiouyåäö")))
|
||||
|
||||
;; --- update ---------------------------------------------------------------------
|
||||
|
||||
(: gui-update (-> Msg Model (Tuple Model (List (Event Msg)))))
|
||||
(defun (gui-update msg m)
|
||||
(def o (.options m))
|
||||
(match msg
|
||||
((Counted cs) (rescore (record-set m (counts cs) (status "")) (.params m)))
|
||||
((Scored g s) (next (if (= g (.generation m)) (record-set m (scores s)) m)))
|
||||
((SetParam i x) (rescore m ((record-ref (vec-ref param-specs i) set) (.params m) x)))
|
||||
((Choose pos)
|
||||
(def r (ranking m))
|
||||
(if (and (>= pos 0) (< pos (vec-length r)))
|
||||
(let ((i (vec-ref r pos)))
|
||||
(next (record-set m (chosen i)
|
||||
(layout-name (if (< i (vec-length layouts)) (.layout-name m)
|
||||
(lname (vec-ref (.layouts m) i)))))))
|
||||
(next m)))
|
||||
((Tab t) (next (record-set m (tab t))))
|
||||
((SetRuns x) (next (record-set m (options (record-set o (runs (cast int x)))))))
|
||||
((SetSteps x) (next (record-set m (options (record-set o (steps (cast int x)))))))
|
||||
((SetTStart x) (next (record-set m (options (record-set o (t-start x))))))
|
||||
((SetVowels b) (next (record-set m (options (record-set o (vowels-left b))))))
|
||||
((SetFixed s) (next (record-set m (options (record-set o (fixed s))))))
|
||||
(Search
|
||||
(def l (vec-ref (.layouts m) (.chosen m)))
|
||||
(def p (.params m))
|
||||
(def counts (.counts m))
|
||||
(cond ((= (vec-length counts) 0) (next m))
|
||||
((= (mean p (vec-map (fun (c) 1.0) counts)) 0.0)
|
||||
(next (record-set m (status "No text weighs anything."))))
|
||||
((and (.vowels-left o) (vowel-right? l))
|
||||
(next (record-set m (status (str (record-ref l name) " has a vowel on the right hand.")))))
|
||||
(else
|
||||
(next (record-set m (searching #t) (results [])
|
||||
(status (str "Searching from " (record-ref l name) "…")))
|
||||
(wrap (blocking (fun () (search (problem-of p l counts) o)))
|
||||
(on-ok Searched "The search failed."))))))
|
||||
((Searched found)
|
||||
(next (record-set m (searching #f) (results (vec-sort-by (fun (a b) (compare (.score a) (.score b))) found))
|
||||
(status ""))))
|
||||
((Failed what) (next (record-set m (searching #f) (status what))))
|
||||
((Keep i)
|
||||
(def rows (.rows (vec-ref (.results m) i)))
|
||||
(def n (+ (.kept m) 1))
|
||||
(def l (make-layout (str "found " (displayed n)) (vec-ref rows 0) (vec-ref rows 1) (vec-ref rows 2)))
|
||||
(rescore (record-set m (layouts (vec-append (.layouts m) [l])) (kept n) (scores [])) (.params m)))
|
||||
((Copy i)
|
||||
(def rows (.rows (vec-ref (.results m) i)))
|
||||
(next m (copy-text (str "(make-layout \"found\"\n \"" (vec-ref rows 0) "\"\n \""
|
||||
(vec-ref rows 1) "\"\n \"" (vec-ref rows 2) "\")"))))
|
||||
(Save
|
||||
(def p (.params m))
|
||||
(next m (wrap (blocking (fun () (save-params p params-file) #t))
|
||||
(on-ok (fun (_) Saved) (str "Could not write " params-file ".")))))
|
||||
(Saved (next (record-set m (status (str "Saved to " params-file ".")))))
|
||||
(Reload (next m (wrap (blocking current-params) (on-ok Loaded (str "Could not read " params-file ".")))))
|
||||
((Loaded p) (rescore (record-set m (status (if (file-exists? params-file)
|
||||
(str "Read " params-file ".")
|
||||
(str "No " params-file ": the defaults."))))
|
||||
p))
|
||||
(Defaults (rescore (record-set m (status "The defaults, not saved.")) default-params))
|
||||
((SetPresetName s) (next (record-set m (preset-name s))))
|
||||
(SavePreset
|
||||
(def name (.preset-name m))
|
||||
(def p (.params m))
|
||||
(if (valid-name? name)
|
||||
(next m (wrap (blocking (fun () (save-preset name p)))
|
||||
(on-ok (fun (names) (Listed (str "Saved the preset " name ".") names))
|
||||
(str "Could not save the preset " name "."))))
|
||||
(next (record-set m (status bad-name)))))
|
||||
((LoadPreset name)
|
||||
(next m (wrap (blocking (fun () (load-preset name)))
|
||||
(on-ok (fun (p) (PresetLoaded name p)) (str "Could not read the preset " name ".")))))
|
||||
((PresetLoaded name p)
|
||||
(rescore (record-set m (preset-name name)
|
||||
(status (str "Loaded the preset " name ". Save writes it to " params-file ".")))
|
||||
p))
|
||||
((DeletePreset name)
|
||||
(next m (wrap (blocking (fun () (delete-preset name)))
|
||||
(on-ok (fun (names) (Listed (str "Deleted the preset " name ".") names))
|
||||
(str "Could not delete the preset " name ".")))))
|
||||
((Listed what names) (next (record-set m (presets names) (status what))))
|
||||
((SetLayoutName s) (next (record-set m (layout-name s))))
|
||||
(SaveLayout
|
||||
(def i (.chosen m))
|
||||
(save-layout m (vec-ref (.layouts m) i) (Some i) (.layout-name m) #t))
|
||||
((SaveResult i)
|
||||
(def rows (.rows (vec-ref (.results m) i)))
|
||||
(save-layout m (make-layout "" (vec-ref rows 0) (vec-ref rows 1) (vec-ref rows 2)) None (.layout-name m) #f))
|
||||
(RemoveLayout
|
||||
(def i (.chosen m))
|
||||
(def ls (.layouts m))
|
||||
(def built (vec-length layouts))
|
||||
(if (< i built)
|
||||
(next (record-set m (status "A built-in layout cannot be removed.")))
|
||||
(let ((name (lname (vec-ref ls i))))
|
||||
(def new-ls (loop (:for x ls) (:for j (range 0 (vec-length ls)))
|
||||
(:when (not (= j i)))
|
||||
(:acc out (vecing x))))
|
||||
(def saved (vec-filter (fun (n) (not (= n name))) (.saved m)))
|
||||
(def step (rescore (record-set m (layouts new-ls) (saved saved) (chosen (- built 1)) (scores [])
|
||||
(status (str "Removed " name ".")))
|
||||
(.params m)))
|
||||
(if (vec-contains? (.saved m) name)
|
||||
(and-then step (write-layouts new-ls saved (str "Removed " name " from " layouts-file ".")))
|
||||
step))))
|
||||
((Wrote what) (next (record-set m (status what))))
|
||||
(Noop (next m))))
|
||||
|
||||
(: subscriptions (-> Model (List (Sub Msg))))
|
||||
(defun (subscriptions m)
|
||||
(if (= (vec-length (.counts m)) 0)
|
||||
(let ((paths (vec-map corpus-path (record-ref (.params m) corpora))))
|
||||
(list (task "count" (wrap (blocking (fun () (count-files layouts paths)))
|
||||
(on-ok Counted "Could not read the texts.")))))
|
||||
'()))
|
||||
|
||||
;; --- the board --------------------------------------------------------------------
|
||||
|
||||
(: double)
|
||||
(def key-size 38.0)
|
||||
|
||||
;; The colour of a finger's keys: pinky, ring, middle, index.
|
||||
(: (-> Key string))
|
||||
(defun (finger-colour k)
|
||||
(match (record-ref k finger)
|
||||
(0 "#f4c7c3")
|
||||
(1 "#fce8b2")
|
||||
(2 "#b7e1cd")
|
||||
(_ "#c6dafc")))
|
||||
|
||||
;; Where `k` is drawn, in pixels: its position on the board, the right hand
|
||||
;; half a key further right.
|
||||
(: (-> Key (Tuple double double)))
|
||||
(defun (key-place k)
|
||||
(def (Tuple x y) (key-position k))
|
||||
(def gap (if (record-ref k left?) 0.0 0.5))
|
||||
(Tuple (* key-size (+ x 0.5 gap)) (* key-size y)))
|
||||
|
||||
(: double)
|
||||
(def board-width (* key-size 13.0))
|
||||
|
||||
(: double)
|
||||
(def board-height (* key-size 3.0))
|
||||
|
||||
;; The board, with a label on each key of `board`, in its order. A stretch
|
||||
;; key has a darker edge.
|
||||
(: keyboard (Component (Vec string) Unit Unit))
|
||||
(def keyboard
|
||||
(component unit
|
||||
(fun (pen w h s labels)
|
||||
(loop (:for k board) (:for label labels)
|
||||
(:let (Tuple x y) (key-place k))
|
||||
(:let size (- key-size 4.0))
|
||||
(:do (fill-rect pen x y size size (finger-colour k) #:radius 5.0)
|
||||
(when (record-ref k stretch?)
|
||||
(stroke-rect pen x y size size "#888888" #:width 1.5 #:radius 5.0))
|
||||
(draw-text pen label (+ x (/ size 2.0)) (+ y 7.0) "#202124"
|
||||
#:size 17.0 #:bold #t #:align "centre"))))))
|
||||
|
||||
;; The character `l` puts on each key of `board`, upper case, or "".
|
||||
(: (-> Layout (Vec string)))
|
||||
(defun (labels-of l)
|
||||
(def on-key (loop (:for c (layout-base-chars l))
|
||||
(:let k (option-ref (layout-key l c)))
|
||||
(:acc out (mapping (Tuple (record-ref k index) c)))))
|
||||
(vec-map (fun (k) (match (map-try-ref on-key (record-ref k index))
|
||||
((Some c) (if (char=? c #\') "’" (char->string (char-upcase c))))
|
||||
(None "")))
|
||||
board))
|
||||
|
||||
(: (-> (Vec string) (View Msg)))
|
||||
(defun (board-view labels)
|
||||
(drawn keyboard labels (fun (_) Noop) #:width board-width #:height board-height))
|
||||
|
||||
;; --- formatting ---------------------------------------------------------------------
|
||||
|
||||
(: (-> double string))
|
||||
(defun (fixed x) (render->string (numeric x #:precision 2)))
|
||||
|
||||
(: (-> double string))
|
||||
(defun (fixed3 x) (render->string (numeric x #:precision 3)))
|
||||
|
||||
(: (-> double string))
|
||||
(defun (pct x) (str (render->string (numeric (* 100.0 x) #:precision 1)) "%"))
|
||||
|
||||
;; A text's name in a heading: its file name with no .txt.
|
||||
(: (-> string string))
|
||||
(defun (file-label path)
|
||||
(def name (option-ref-or (path-filename path) path))
|
||||
(if (string-ends-with? name ".txt") (string-drop-right name 4) name))
|
||||
|
||||
;; The number `s` holds, if it holds one.
|
||||
(: (-> string (Option double)))
|
||||
(defun (number-in s)
|
||||
(result->option (try (string->double s) #:catch (System.Exception))))
|
||||
|
||||
;; A grid of rows of texts, the first column left and the others right.
|
||||
(: (-> string (Vec (Vec string)) (View Msg)))
|
||||
(defun (table columns rows)
|
||||
(apply grid #:columns columns
|
||||
#:rows (string-join (vec-map (fun (_) "Auto") rows) ",")
|
||||
#:spacing 4.0
|
||||
(vec->array (loop (:for r rows) (:for i (range 0 (vec-length rows)))
|
||||
(:let cells r)
|
||||
(:for cell cells) (:for j (range 0 (vec-length cells)))
|
||||
(:acc out (vecing (at i j (text cell))))))))
|
||||
|
||||
;; --- the views ---------------------------------------------------------------------
|
||||
|
||||
;; A blue circle with an "i", 16 pixels across.
|
||||
(: info-mark (Component Unit Unit Unit))
|
||||
(def info-mark
|
||||
(component unit
|
||||
(fun (pen w h s _)
|
||||
(fill-circle pen 8.0 8.0 8.0 "#1a73e8")
|
||||
(draw-text pen "i" 8.0 0.5 "#ffffff" #:size 12.0 #:bold #t #:align "centre"))))
|
||||
|
||||
;; A small "i" mark that shows `help` when the pointer rests on it.
|
||||
(: (-> string (View Msg)))
|
||||
(defun (info help)
|
||||
(tooltip (drawn info-mark unit (fun (_) Noop) #:width 16.0 #:height 16.0) help))
|
||||
|
||||
;; `v` with an "i" mark after it, and `help` shown on both. Where a row has an
|
||||
;; input, the mark goes after the input instead.
|
||||
(: (-> (View Msg) string (View Msg)))
|
||||
(defun (with-info v help)
|
||||
(row #:spacing 6.0 (tooltip v help) (info help)))
|
||||
|
||||
;; The help of `s`, and its default.
|
||||
(: (-> Spec string))
|
||||
(defun (spec-help s)
|
||||
(str (record-ref s help) "\n\nDefault: " (displayed ((record-ref s get) default-params)) "."))
|
||||
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (scores-view m)
|
||||
(def cs (record-ref (.params m) corpora))
|
||||
(def r (ranking m))
|
||||
(def columns (string-join (vec-append ["90" "60"] (vec-map (fun (_) "60") cs)) ","))
|
||||
(: line (-> (Vec string) (View Msg)))
|
||||
(def line (fun (cells)
|
||||
(apply grid #:columns columns
|
||||
(vec->array (loop (:for c cells) (:for j (range 0 (vec-length cells)))
|
||||
(:acc out (vecing (at 0 j (text c)))))))))
|
||||
(def items
|
||||
(vec-map (fun (i)
|
||||
(def l (vec-ref (.layouts m) i))
|
||||
(keyed (record-ref l name)
|
||||
(line (vec-append [(record-ref l name) (fixed (mean-of m i (fun (s) (.total s))))]
|
||||
(vec-map (fun (s) (fixed (.total s))) (vec-ref (.scores m) i))))))
|
||||
r))
|
||||
(def selected (match (find (fun (p) (= (vec-ref r p) (.chosen m))) (range 0 (vec-length r)))
|
||||
((Some p) p)
|
||||
(None -1)))
|
||||
(column #:spacing 6.0 #:margin 8.0
|
||||
(text "Score per key press, lower is better" #:size 15.0)
|
||||
(line (vec-append ["layout" "mean"] (vec-map (fun (c) (file-label (corpus-path c))) cs)))
|
||||
(list-box items selected Choose #:width 340.0)))
|
||||
|
||||
;; The numbers of one group, each with its input.
|
||||
(: (-> Model string (View Msg)))
|
||||
(defun (group-view m group)
|
||||
(def p (.params m))
|
||||
(def specs (loop (:for s param-specs) (:for i (range 0 (vec-length param-specs)))
|
||||
(:when (= (record-ref s group) group))
|
||||
(:acc out (vecing (Tuple i s)))))
|
||||
(border
|
||||
(column #:spacing 6.0
|
||||
(text group #:size 15.0)
|
||||
(apply grid #:columns "Auto,130,Auto" #:rows (string-join (vec-map (fun (_) "Auto") specs) ",") #:spacing 6.0
|
||||
(vec->array
|
||||
(loop (:for (Tuple i s) specs) (:for row (range 0 (vec-length specs)))
|
||||
(:let input (number-input ((record-ref s get) p) (fun (x) (SetParam i x))
|
||||
#:minimum (record-ref s minimum)
|
||||
#:maximum (record-ref s maximum)
|
||||
#:step (record-ref s step)
|
||||
#:width 130.0))
|
||||
(:let help (spec-help s))
|
||||
(:for cell (list (at row 0 (tooltip (text (record-ref s label)) help))
|
||||
(at row 1 (tooltip input help))
|
||||
(at row 2 (info help))))
|
||||
(:acc out (vecing cell))))))
|
||||
#:padding 10.0 #:radius 6.0 #:colour "#9e9e9e"))
|
||||
|
||||
;; The presets: a name to save the numbers as, and each preset with Load and
|
||||
;; Delete.
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (presets-view m)
|
||||
(def items
|
||||
(if (= (vec-length (.presets m)) 0)
|
||||
[(text "No presets yet.")]
|
||||
(vec-map (fun (n)
|
||||
(keyed n (row #:spacing 6.0
|
||||
(text n #:width 160.0)
|
||||
(tooltip (button "Load" (LoadPreset n)) (str "Use the numbers of " n "."))
|
||||
(tooltip (button "Delete" (DeletePreset n)) (str "Delete the file of " n ".")))))
|
||||
(.presets m))))
|
||||
(border
|
||||
(column #:spacing 6.0
|
||||
(text "Presets" #:size 15.0)
|
||||
(row #:spacing 6.0
|
||||
(text-input (.preset-name m) SetPresetName #:placeholder "name" #:width 160.0)
|
||||
(tooltip (button "Save preset" SavePreset)
|
||||
"Saves the numbers as they are under this name. A preset of the same name is replaced.")
|
||||
(info (str "A preset is a named set of all the numbers, key costs and text weights included. "
|
||||
"Presets are kept in the " presets-folder " folder. Load uses a preset's numbers; "
|
||||
"Save at the top writes them to " params-file " for the other programs.")))
|
||||
(apply column #:spacing 4.0 (vec->array items)))
|
||||
#:padding 10.0 #:radius 6.0 #:colour "#9e9e9e"))
|
||||
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (rules-view m)
|
||||
(def groups ["Texts" "Keys" "Pairs" "Row motion" "Triples" "Pinky load" "Finger distance"])
|
||||
(scroll (apply flow #:spacing 10.0 #:margin 8.0
|
||||
(vec->array (vec-append [(presets-view m)] (vec-map (fun (g) (group-view m g)) groups))))))
|
||||
|
||||
;; The key costs, each input where its key is on the board.
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (key-costs-view m)
|
||||
(def p (.params m))
|
||||
(def width 56.0)
|
||||
(: cell (-> Key (View Msg)))
|
||||
(def cell (fun (k)
|
||||
(def i (option-ref (find (fun (j) (= (record-ref (vec-ref param-specs j) name)
|
||||
(str "key." (record-ref k name))))
|
||||
(range 0 (vec-length param-specs)))))
|
||||
(def s (vec-ref param-specs i))
|
||||
(tooltip (column #:spacing 2.0
|
||||
(text (record-ref s label))
|
||||
(text-input (displayed ((record-ref s get) p))
|
||||
(fun (t) (match (number-in t) ((Some x) (SetParam i x)) (None Noop)))
|
||||
#:width (- width 4.0)))
|
||||
(spec-help s))))
|
||||
(: board-row (-> int (View Msg)))
|
||||
(def board-row (fun (r)
|
||||
(: on-row? (-> Key bool))
|
||||
(def on-row? (fun (k) (= (record-ref k row) r)))
|
||||
(def ks (->vec (filter on-row? board)))
|
||||
(def (Tuple x0 _) (key-position (vec-ref ks 0)))
|
||||
;; The first key of the right hand, with a gap before it.
|
||||
(: first-right? (-> int bool))
|
||||
(def first-right? (fun (j) (and (> j 0) (not (record-ref (vec-ref ks j) left?))
|
||||
(record-ref (vec-ref ks (- j 1)) left?))))
|
||||
(apply row #:spacing 4.0
|
||||
(vec->array
|
||||
(vec-append [(text "" #:width (* (+ x0 0.5) width))]
|
||||
(loop (:for k ks) (:for j (range 0 (vec-length ks)))
|
||||
(:acc out (vecing (if (first-right? j)
|
||||
(row (text "" #:width (/ width 2.0)) (cell k))
|
||||
(cell k))))))))))
|
||||
(column #:spacing 10.0 #:margin 8.0
|
||||
(with-info (text (str "Each press costs its key's cost times the key weight, "
|
||||
(displayed (record-ref p key-weight)) ". Set the key weight under Rules."))
|
||||
"Point at a key to see its default cost. A key of the right pinky past P and Ö, and the centre columns, are stretch keys: the Stretch key number is added to pairs with them.")
|
||||
(board-row 0) (board-row 1) (board-row 2)))
|
||||
|
||||
;; What the chosen layout is: built in, saved, or kept and not saved.
|
||||
(: (-> Model string))
|
||||
(defun (kind-of-chosen m)
|
||||
(def i (.chosen m))
|
||||
(cond ((< i (vec-length layouts)) "built in")
|
||||
((vec-contains? (.saved m) (lname (vec-ref (.layouts m) i))) (str "saved in " layouts-file))
|
||||
(else "kept, not saved")))
|
||||
|
||||
;; The name input and the Save layout and Remove buttons.
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (save-layout-view m)
|
||||
(def built? (< (.chosen m) (vec-length layouts)))
|
||||
(row #:spacing 6.0
|
||||
(text "Save as")
|
||||
(text-input (.layout-name m) SetLayoutName #:placeholder "name" #:width 160.0)
|
||||
(tooltip (button "Save layout" SaveLayout)
|
||||
(str "Saves the chosen layout under this name in " layouts-file ". A built-in layout is copied. "
|
||||
"A kept or saved layout gets the new name. A saved layout of the same name is replaced."))
|
||||
(tooltip (button "Remove" RemoveLayout #:enabled (not built?))
|
||||
(str "Removes the chosen layout from the list, and from " layouts-file " if it is saved there."))
|
||||
(info (str "Saved layouts are kept in " layouts-file ", one a line, and are listed at start."))))
|
||||
|
||||
;; The chosen layout on the board, and the parts of its score.
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (layout-view m)
|
||||
(def i (.chosen m))
|
||||
(def l (vec-ref (.layouts m) i))
|
||||
(def heading (row #:spacing 10.0 (text (record-ref l name) #:size 18.0) (text (str "(" (kind-of-chosen m) ")"))))
|
||||
(if (< i (vec-length (.scores m)))
|
||||
(let ((cs (record-ref (.params m) corpora))
|
||||
(scores (vec-ref (.scores m) i)))
|
||||
(: part (-> string (-> Score double) (-> double string) (Vec string)))
|
||||
(def part (fun (label f show)
|
||||
(vec-append (vec-append [label] (vec-map (fun (s) (show (f s))) scores))
|
||||
[(show (mean-of m i f))])))
|
||||
(def rule-rows (loop (:for r rules) (:for j (range 0 (vec-length rules)))
|
||||
(:acc out (vecing (part (record-ref r name) (fun (s) (vec-ref (.rules s) j)) fixed)))))
|
||||
(def rows
|
||||
(vec-append
|
||||
(vec-append [(vec-append (vec-append ["part"] (vec-map (fun (c) (file-label (corpus-path c))) cs)) ["mean"])
|
||||
(part "key costs" (fun (s) (.position s)) fixed)
|
||||
(part "top-row vowels" (fun (s) (.top-vowels s)) fixed)]
|
||||
rule-rows)
|
||||
[(part "hand runs" (fun (s) (.runs s)) fixed)
|
||||
(part "same-finger skips" (fun (s) (.skips s)) fixed)
|
||||
(part "two-finger runs" (fun (s) (.two-fingers s)) fixed)
|
||||
(part "pinky load" (fun (s) (.pinkies s)) fixed)
|
||||
(part "distance cost" (fun (s) (* (record-ref (.params m) distance) (.distance s))) fixed)
|
||||
(part "total" (fun (s) (.total s)) fixed3)
|
||||
(part "finger distance (key widths)" (fun (s) (.distance s)) fixed)
|
||||
(part "home row" (fun (s) (.home s)) pct)
|
||||
(part "hand alternation" (fun (s) (.alternation s)) pct)
|
||||
(part "same finger" (fun (s) (.same-finger s)) pct)
|
||||
(part "triples in hand runs" (fun (s) (.run-share s)) pct)
|
||||
(part "same-finger skip triples" (fun (s) (.skip-share s)) pct)
|
||||
(part "two-finger run triples" (fun (s) (.two-finger-share s)) pct)
|
||||
(part "left hand" (fun (s) (.left-hand s)) pct)
|
||||
(part "left pinky" (fun (s) (.left-pinky s)) pct)
|
||||
(part "right pinky" (fun (s) (.right-pinky s)) pct)]))
|
||||
(scroll
|
||||
(column #:spacing 10.0 #:margin 8.0
|
||||
heading
|
||||
(save-layout-view m)
|
||||
(board-view (labels-of l))
|
||||
(table (string-join (vec-append ["Auto"] (vec-map (fun (_) "70") (vec-ref rows 0))) ",") rows))))
|
||||
(column #:spacing 10.0 #:margin 8.0 heading (save-layout-view m) (board-view (labels-of l)))))
|
||||
|
||||
(: (-> Model (View Msg)))
|
||||
(defun (search-view m)
|
||||
(def o (.options m))
|
||||
(def l (vec-ref (.layouts m) (.chosen m)))
|
||||
(def results
|
||||
(loop (:for f (.results m)) (:for i (range 0 (vec-length (.results m))))
|
||||
(:acc out (vecing (keyed (str "result " (displayed i))
|
||||
(row #:spacing 10.0
|
||||
(text (fixed3 (.score f)) #:width 50.0)
|
||||
(board-view (labels-of (make-layout "" (vec-ref (.rows f) 0) (vec-ref (.rows f) 1)
|
||||
(vec-ref (.rows f) 2))))
|
||||
(column #:spacing 6.0
|
||||
(tooltip (button "Keep" (Keep i) #:width 70.0)
|
||||
"Adds the result to the list on the left as \"found N\". It is not saved.")
|
||||
(tooltip (button "Save" (SaveResult i) #:width 70.0)
|
||||
(str "Adds the result to the list and saves it in " layouts-file
|
||||
" under the name in Save as."))
|
||||
(tooltip (button "Copy" (Copy i) #:width 70.0)
|
||||
"Puts the result on the clipboard as a make-layout form for src/layouts.bjo."))))))))
|
||||
(scroll
|
||||
(column #:spacing 10.0 #:margin 8.0
|
||||
(text (str "From " (record-ref l name) ", the layout chosen on the left, with the numbers as they are.")
|
||||
#:wrap #t)
|
||||
(grid #:columns "Auto,160,Auto" #:rows "Auto,Auto,Auto,Auto,Auto" #:spacing 6.0
|
||||
(at 0 0 (text "Runs, in parallel"))
|
||||
(at 0 1 (number-input (cast double (.runs o)) SetRuns #:minimum 1.0 #:maximum 64.0 #:width 160.0))
|
||||
(at 0 2 (info "How many searches run at the same time. Each starts from the chosen layout with its own random swaps. More runs find good layouts more reliably."))
|
||||
(at 1 0 (text "Swaps per run"))
|
||||
(at 1 1 (number-input (cast double (.steps o)) SetSteps #:minimum 1000.0 #:maximum 20000000.0
|
||||
#:step 100000.0 #:width 160.0))
|
||||
(at 1 2 (info "How many key swaps each run tries. More swaps take longer and search more thoroughly."))
|
||||
(at 2 0 (text "Start temperature"))
|
||||
(at 2 1 (number-input (.t-start o) SetTStart #:minimum 0.002 #:maximum 5.0 #:step 0.01 #:width 160.0))
|
||||
(at 2 2 (info "How readily a run accepts a swap that makes the score worse, at the start. It falls to almost 0 at the end. High (0.3 or more): the search goes far from the start layout. Low (0.02): it refines the start layout."))
|
||||
(at 3 0 (text "Fixed characters"))
|
||||
(at 3 1 (text-input (.fixed o) SetFixed #:placeholder "åäö.," #:width 160.0))
|
||||
(at 3 2 (info "Characters whose keys do not move, written as in a layout, such as åäö.,"))
|
||||
(at 4 0 (checkbox "Vowels on the left hand" (.vowels-left o) SetVowels) #:column-span 2)
|
||||
(at 4 2 (info "Keeps every vowel (a e i o u y å ä ö) on the left hand. The chosen layout must have all its vowels on the left.")))
|
||||
(row #:spacing 6.0
|
||||
(text "Save as")
|
||||
(text-input (.layout-name m) SetLayoutName #:placeholder "name" #:width 160.0)
|
||||
(info "The name that Save on a result saves it under."))
|
||||
(button (if (.searching m) "Searching…" "Search") Search #:enabled (not (.searching m)) #:width 120.0)
|
||||
(apply column #:spacing 10.0 (vec->array results)))))
|
||||
|
||||
(: view (-> Model (View Msg)))
|
||||
(defun (view m)
|
||||
(dock
|
||||
(at-top (row #:spacing 8.0 #:margin 8.0
|
||||
(tooltip (button "Save" Save)
|
||||
(str "Writes the numbers to " params-file ". keyscore and optimize read that file."))
|
||||
(tooltip (button "Reload" Reload) (str "Reads the numbers from " params-file " again."))
|
||||
(tooltip (button "Defaults" Defaults) "Puts back the built-in numbers. Nothing is saved.")
|
||||
(text (.status m) #:margin 6.0)))
|
||||
(at-left (scores-view m))
|
||||
(tabs (.tab m) Tab #:margin 8.0
|
||||
(tab "Rules" (rules-view m))
|
||||
(tab "Key costs" (key-costs-view m))
|
||||
(tab "Layout" (layout-view m))
|
||||
(tab "Search" (search-view m)))))
|
||||
|
||||
(defun (main)
|
||||
(run-app initial gui-update view
|
||||
#:subscriptions subscriptions
|
||||
#:title "keyscore" #:width 1500.0 #:height 900.0)
|
||||
0)
|
||||
206
src/layouts.bjo
Normal file
206
src/layouts.bjo
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
;; Layouts: which character each key of the board types.
|
||||
;;
|
||||
;; - A layout is written as three rows of characters, in the board's order:
|
||||
;; the top row from Q, the home row from A, the bottom row from <. Spaces
|
||||
;; are skipped, so a row can be split at the hands.
|
||||
;; - A row may be shorter than the board's: its last keys type nothing.
|
||||
;; - Letters are written in either case. ’ is the same character as '.
|
||||
;; - The shifted character of a punctuation key is typed on that key:
|
||||
;; , ; . : - _ ' * < >, as on Swedish QWERTY and Svdvorak.
|
||||
|
||||
(import (std prelude))
|
||||
(import (keyscore board))
|
||||
|
||||
(export Layout make-layout aligned-rows layout-key layout-chars layout-base-chars swap-keys common-chars
|
||||
normalize layouts)
|
||||
|
||||
;; - rows: the three rows as written, for making variants.
|
||||
;; - keys: the key of every character typed, shifted ones included.
|
||||
(type (: Layout (Record (: name string) (: rows (Vec string)) (: keys (Map char Key)))))
|
||||
|
||||
;; The shifted character typed on the same key as `c`.
|
||||
(: (-> char (Option char)))
|
||||
(defun (shifted c)
|
||||
(match c
|
||||
(#\, (Some #\;))
|
||||
(#\. (Some #\:))
|
||||
(#\- (Some #\_))
|
||||
(#\' (Some #\*))
|
||||
(#\< (Some #\>))
|
||||
(_ None)))
|
||||
|
||||
;; A character as the scorer counts it: lower case, with ’ as '.
|
||||
(: (-> char char))
|
||||
(defun (normalize c)
|
||||
(if (char=? c (int->char 0x2019)) #\' (char-downcase c)))
|
||||
|
||||
;; The keys of `row` on the board, in column order.
|
||||
(: (-> int (List Key)))
|
||||
(defun (row-keys row)
|
||||
(->list (filter (fun (k) (= (record-ref k row) row)) board)))
|
||||
|
||||
;; A layout named `name` from its three rows. Raises if a row is longer than
|
||||
;; the board's.
|
||||
(: (-> string string string string Layout))
|
||||
(defun (make-layout name top home bottom)
|
||||
(def keys
|
||||
(loop (:for (Tuple row text) (list (Tuple 0 top) (Tuple 1 home) (Tuple 2 bottom)))
|
||||
(:let chars (->list (filter (fun (c) (not (char=? c #\space))) text)))
|
||||
(:let ks (row-keys row))
|
||||
(:do (when (> (list-length chars) (list-length ks))
|
||||
(panic! (str name ": the row " (written text) " has more keys than the board"))))
|
||||
(:for (Tuple c k) (zip chars ks))
|
||||
(:let base (normalize c))
|
||||
(:for (Tuple ch key) (match (shifted base)
|
||||
((Some s) (list (Tuple base k) (Tuple s k)))
|
||||
(None (list (Tuple base k)))))
|
||||
(:acc out (mapping (Tuple ch key)))))
|
||||
(Layout (name name) (rows [top home bottom]) (keys keys)))
|
||||
|
||||
;; The key that types `c`, if the layout has one.
|
||||
(: (-> Layout char (Option Key)))
|
||||
(defun (layout-key l c) (map-try-ref (record-ref l keys) c))
|
||||
|
||||
;; Every character the layout types.
|
||||
(: (-> Layout (List char)))
|
||||
(defun (layout-chars l) (->list (map-keys (record-ref l keys))))
|
||||
|
||||
;; The characters written in the layout's rows, normalized: one per key.
|
||||
(: (-> Layout (List char)))
|
||||
(defun (layout-base-chars l)
|
||||
(loop (:for r (record-ref l rows))
|
||||
(:let row r)
|
||||
(:for c row)
|
||||
(:when (not (char=? c #\space)))
|
||||
(:acc out (listing (normalize c)))))
|
||||
|
||||
;; `l` with the keys of `a` and `b` swapped, named `name`. `a` and `b` are
|
||||
;; compared with the rows' characters after `normalize`.
|
||||
(: (-> Layout string char char Layout))
|
||||
(defun (swap-keys l name a b)
|
||||
(: swap (-> char char))
|
||||
(def swap (fun (c)
|
||||
(def n (normalize c))
|
||||
(cond ((char=? n a) b) ((char=? n b) a) (else c))))
|
||||
(def rows (vec-map (fun (r) (list->string (->list (map swap r)))) (record-ref l rows)))
|
||||
(make-layout name (vec-ref rows 0) (vec-ref rows 1) (vec-ref rows 2)))
|
||||
|
||||
;; `rows` written with the hands apart, so that the rows line up in a
|
||||
;; fixed-width font:
|
||||
;;
|
||||
;; ÖUOF, QVLBJ
|
||||
;; IEADY CTRNS
|
||||
;; ÅÄ.HK Z MGWPX
|
||||
;;
|
||||
;; - Top and home rows: five keys, three spaces, the rest.
|
||||
;; - Bottom row: five keys, the middle key between single spaces, the rest.
|
||||
;; - Spaces already in `rows` are dropped first.
|
||||
(: (-> (Vec string) (Vec string)))
|
||||
(defun (aligned-rows rows)
|
||||
(: gap (-> int int string))
|
||||
(def gap (fun (row i)
|
||||
(cond ((and (< row 2) (= i 5)) " ")
|
||||
((and (= row 2) (or (= i 5) (= i 6))) " ")
|
||||
(else ""))))
|
||||
(loop (:for text rows) (:for row (range 0 3))
|
||||
(:let chars (->list (filter (fun (c) (not (char=? c #\space))) text)))
|
||||
(:let parts (loop (:for c chars) (:for i (range 0 (list-length chars)))
|
||||
(:acc out (vecing (str (gap row i) (char->string c))))))
|
||||
(:acc out (vecing (string-join parts "")))))
|
||||
|
||||
;; The characters every layout in `ls` types.
|
||||
(: (-> (Vec Layout) (List char)))
|
||||
(defun (common-chars ls)
|
||||
(->list (filter (fun (c) (all? (fun (l) (some? (layout-key l c))) ls))
|
||||
(layout-chars (vec-ref ls 0)))))
|
||||
|
||||
(: (Vec Layout))
|
||||
(def layouts
|
||||
[(make-layout "QWERTY"
|
||||
"qwert yuiopå"
|
||||
"asdfg hjklöä'"
|
||||
"<zxcvb nm,.-")
|
||||
(make-layout "Svdvorak"
|
||||
"å,.py fgcrl'"
|
||||
"aoeui dhtns-<"
|
||||
"öäqjkx bmwvz")
|
||||
;; The best of 8 runs of src/optimize.bjo from UENAO, 2 000 000 steps each,
|
||||
;; before the same-hand and hand-run rules, and with T starting at 0.3.
|
||||
(make-layout "Found1"
|
||||
"YBMPW Ö.H,’Z"
|
||||
"ITSDG -ANERX"
|
||||
"ÄVCFK Q ÅOLUJ")
|
||||
;; The best of 8 runs of src/optimize.bjo from IENAO, 2 000 000 steps each,
|
||||
;; with the same-hand and hand-run rules and T starting at 0.02. 7 runs of 8
|
||||
;; ended within 0.001 of it.
|
||||
(make-layout "Found2"
|
||||
"JUKOÄ WCHGZQ"
|
||||
"IENA. FDRTSB"
|
||||
"-,YÖÅ ’ VPLMX")
|
||||
;; The best of 8 runs of src/optimize.bjo from IENAO, 300 000 steps each,
|
||||
;; with row motion, same-finger skips and the key costs doubled.
|
||||
(make-layout "Found3"
|
||||
"-YKÄÖ ZBLMJQ"
|
||||
"IENA, FDRTSW"
|
||||
"ÅUPO. ’ GCHVX")
|
||||
(make-layout "UENAO"
|
||||
"Å.JÄZ QCLHB’"
|
||||
"UENAO DTRSK-"
|
||||
"Y,WÖI X GMVFP")
|
||||
;; UENAO with I and U swapped: the best single swap of src/swaps.bjo.
|
||||
(make-layout "IENAO"
|
||||
"Å.JÄZ QCLHB’"
|
||||
"IENAO DTRSK-"
|
||||
"Y,WÖU X GMVFP")
|
||||
;; Found3 changed by hand. The right pinky's stretch keys type nothing, and
|
||||
;; it has no - and ': these are not scored, as not every layout types them.
|
||||
(make-layout "QYKÄÖ"
|
||||
"QYKÄÖ ZBLMJ"
|
||||
"IENA. FDRTS"
|
||||
"Å,POU W GCHVX")
|
||||
;; The best of 8 runs of src/optimize.bjo from QUPÅÄ, 2 000 000 steps each,
|
||||
;; with T starting at 0.3. 3 runs of 8 ended on it. The vowels are on the
|
||||
;; right hand.
|
||||
(make-layout "JMLBW"
|
||||
"JMLBW QFOUÖ"
|
||||
"STRDP KNAEI"
|
||||
"XV,GC Z YH.ÄÅ")
|
||||
;; The best of the same runs with the vowels on the left hand. 2 runs of 8
|
||||
;; ended on it.
|
||||
(make-layout "ÖUOF,"
|
||||
"ÖUOF, QVLBJ"
|
||||
"IEADY CTRNS"
|
||||
"ÅÄ.HK Z MGWPX")
|
||||
;; Two searches from QUPÅÄ with sv.txt weighing 0.75 and en.txt 0.25,
|
||||
;; 8 runs of 2 000 000 steps each: the best with T starting at 0.02 (7 runs
|
||||
;; of 8 ended on it), and the best with T starting at 0.3 (2 runs of 8).
|
||||
(make-layout "YÖFO."
|
||||
"QUPÅÄ XBLMJ"
|
||||
"IENA, GDRTS"
|
||||
"YÖFO. Z KHCVW")
|
||||
(make-layout "JMLPB"
|
||||
"JMLPB QÄHUÅ"
|
||||
"STNDF .AREI"
|
||||
"XVCKG W ÖO,YZ")
|
||||
;; The best of 8 runs of src/optimize.bjo from QYKÄÖ, 300 000 steps each.
|
||||
(make-layout "QUPÅÄ"
|
||||
"QUPÅÄ XBLMJ"
|
||||
"IENA. GDRTS"
|
||||
"ÖYFO, Z KHCVW")
|
||||
;; The best of 12 runs of src/optimize.bjo from Svdvorak, 3 000 000 steps
|
||||
;; each at t-start 0.3, with Svdvorak's Å Ä Ö . , fixed.
|
||||
(make-layout "Å,.YZ"
|
||||
"Å,.YZ QCHPW"
|
||||
"IEADK VTRNS"
|
||||
"ÖÄOFU X GMLBJ")
|
||||
;; ZYK,Å refined at t-start 0.02 with Swedish weighing 3 to English's 1.
|
||||
(make-layout "Z,K.Å"
|
||||
"Z,K.Å XCHPW"
|
||||
"IEDAÄ VTRNS"
|
||||
"YUFÖO Q GMLBJ")
|
||||
;; The best of 12 runs of src/optimize.bjo from QUPÅÄ, 3 000 000 steps each
|
||||
;; at t-start 0.3, vowels kept left, with vowels on the top row costing more.
|
||||
(make-layout "ZYK,Å"
|
||||
"ZYK,Å XCHPW"
|
||||
"IEDAÄ VTRNS"
|
||||
"ÖUFO. Q GMLBJ")])
|
||||
123
src/main.bjo
Normal file
123
src/main.bjo
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
;; (keyscore): scores keyboard layouts on texts, by Michael Capewell's rules.
|
||||
;;
|
||||
;; bjo run . [text ...]
|
||||
;;
|
||||
;; - With no texts given, scores the texts of (keyscore texts), with their
|
||||
;; weights. Texts given weigh the same.
|
||||
;; - Counts only the characters every layout types, so that every layout
|
||||
;; types the same text.
|
||||
;; - Prints each layout's score per key press on each text, and the parts of
|
||||
;; each score, as the weighted mean over the texts. Lower is better.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std fmt))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore score))
|
||||
(import (std mutable map))
|
||||
(import (keyscore texts))
|
||||
|
||||
;; The file name of a path.
|
||||
(: (-> string string))
|
||||
(defun (file-name path) (option-ref-or (path-filename path) path))
|
||||
|
||||
(: (-> double Block))
|
||||
(defun (fixed x) (numeric x #:precision 2))
|
||||
|
||||
;; A table row: a label, then a block for each of `xs`.
|
||||
(: (-> string (Vec %a) (-> %a Block) (Vec Block)))
|
||||
(defun (row label xs f)
|
||||
(vec-append [(BStr label)] (vec-map f xs)))
|
||||
|
||||
;; A text's row: its name, its size, and how much of it is counted.
|
||||
(: (-> string Counts Score (Vec Block)))
|
||||
(defun (text-row t c s)
|
||||
(def presses (cast double (record-ref s presses)))
|
||||
(def all (cast double (record-ref c chars)))
|
||||
[(BStr (file-name t)) (numeric/comma all) (numeric/comma presses) (percent (/ presses all))])
|
||||
|
||||
;; A layout's row: its score on each text, and the weighted mean.
|
||||
(: (-> (Vec Corpus) Layout (Vec Score) (Vec Block)))
|
||||
(defun (score-row cs l s)
|
||||
(def totals (vec-map (fun (x) (record-ref x total)) s))
|
||||
(vec-append (row (record-ref l name) totals fixed) [(fixed (weighted-mean cs totals))]))
|
||||
|
||||
(defun (main args)
|
||||
(def params (current-params))
|
||||
(when (file-exists? params-file) (show ["Parameters from " params-file "." nl]))
|
||||
(def corpora (if (= (length args) 0)
|
||||
(record-ref params corpora)
|
||||
(list->vec (->list (map (fun (a) (corpus a 1.0)) args)))))
|
||||
(def texts (vec-map (fun (c) (record-ref c path)) corpora))
|
||||
(def chars (common-chars layouts))
|
||||
(def counts (count-files layouts texts))
|
||||
;; scores[layout][text]
|
||||
(def scores (vec-map (fun (l) (vec-map (fun (c) (score-layout params l c)) counts)) layouts))
|
||||
(def right (fun (n) (vec-append [AlignLeft] (->vec (map (fun (_) AlignRight) (range 0 n))))))
|
||||
|
||||
;; --- the texts --------------------------------------------------------------
|
||||
(show ["Counted: " (list->string (list-sort chars)) nl nl])
|
||||
(show (tabular/rows
|
||||
(loop (:for t texts) (:for c counts) (:for s (vec-ref scores 0)) (:acc out (vecing (text-row t c s))))
|
||||
#:titles ["text" "characters" "counted" "share"]
|
||||
#:sep " " #:align (right 3)))
|
||||
(show nl)
|
||||
|
||||
;; --- the score on each text ---------------------------------------------------
|
||||
(show ["Score per key press. Lower is better. The mean weighs " (weights-text corpora) "." nl])
|
||||
(show (tabular/rows
|
||||
(loop (:for l layouts) (:for s scores) (:acc out (vecing (score-row corpora l s))))
|
||||
#:titles (vec-append (row "layout" texts (fun (t) (BStr (file-name t)))) ["mean"])
|
||||
#:sep " " #:align (right (+ (vec-length texts) 1))))
|
||||
(show nl)
|
||||
|
||||
;; --- the parts of the score -------------------------------------------------------
|
||||
(: mean-of (-> (-> Score double) (Vec Score) double))
|
||||
(def mean-of (fun (f s) (weighted-mean corpora (vec-map f s))))
|
||||
(def (: parts (Vec (Vec Block)))
|
||||
(vec-append
|
||||
(vec-append
|
||||
[(row "key costs" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x position)) s))))
|
||||
(row "top-row vowels" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x top-vowels)) s))))]
|
||||
(loop (:for r rules) (:for i (range 0 (vec-length rules)))
|
||||
(:acc out (vecing (row (record-ref r name) scores
|
||||
(fun (s) (fixed (mean-of (fun (x) (vec-ref (record-ref x rules) i)) s))))))))
|
||||
[(row "hand runs" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x runs)) s))))
|
||||
(row "same-finger skips" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x skips)) s))))
|
||||
(row "two-finger runs" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x two-fingers)) s))))
|
||||
(row "pinky load" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x pinkies)) s))))
|
||||
(row "finger distance" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x distance)) s))))
|
||||
(row "total" scores (fun (s) (fixed (mean-of (fun (x) (record-ref x total)) s))))
|
||||
(row "home row" scores (fun (s) (percent (mean-of (fun (x) (record-ref x home)) s))))
|
||||
(row "hand alternation" scores (fun (s) (percent (mean-of (fun (x) (record-ref x alternation)) s))))
|
||||
(row "same finger" scores (fun (s) (percent (mean-of (fun (x) (record-ref x same-finger)) s))))
|
||||
(row "triples in hand runs" scores (fun (s) (percent (mean-of (fun (x) (record-ref x run-share)) s))))
|
||||
(row "same-finger skip triples" scores (fun (s) (percent (mean-of (fun (x) (record-ref x skip-share)) s))))
|
||||
(row "two-finger run triples" scores (fun (s) (percent (mean-of (fun (x) (record-ref x two-finger-share)) s))))
|
||||
(row "left hand" scores (fun (s) (percent (mean-of (fun (x) (record-ref x left-hand)) s))))
|
||||
(row "left / right" scores
|
||||
(fun (s) (let ((l (mean-of (fun (x) (record-ref x left-hand)) s))) (fixed (/ l (- 1.0 l))))))
|
||||
(row "left pinky" scores (fun (s) (percent (mean-of (fun (x) (record-ref x left-pinky)) s))))
|
||||
(row "right pinky" scores (fun (s) (percent (mean-of (fun (x) (record-ref x right-pinky)) s))))]))
|
||||
(show ["The parts, per key press, as the weighted mean." nl])
|
||||
(show (tabular/rows parts
|
||||
#:titles (row "part" layouts (fun (l) (BStr (record-ref l name))))
|
||||
#:sep " " #:align (right (vec-length layouts))))
|
||||
(show nl)
|
||||
|
||||
;; --- the pairs that cost most ----------------------------------------------------
|
||||
(show ["The pairs that cost each layout most, per key press, as the weighted mean." nl])
|
||||
(def weight-sum (vec-fold (fun (c t) (+ t (record-ref c weight))) 0.0 corpora))
|
||||
(loop (:for l layouts)
|
||||
(:let costs (mutablemap))
|
||||
(:do (loop (:for c counts) (:for cp corpora)
|
||||
(:let share (/ (record-ref cp weight) weight-sum))
|
||||
(:let pcs (pair-costs params l c))
|
||||
(:for (Tuple p x) pcs)
|
||||
(:do (mutablemap-update! costs p (fun (t) (+ t (* share x)))
|
||||
#:default (Some 0.0)))))
|
||||
(:let worst (take 12 (vec-sort-by (fun (a b) (compare (snd b) (snd a))) (->vec costs))))
|
||||
(:do (show [(padded/right 10 (record-ref l name))
|
||||
(joined (fun (e) [(written (fst e)) " " (fixed (snd e))]) (->list worst) " ")
|
||||
nl])))
|
||||
0)
|
||||
78
src/optimize.bjo
Normal file
78
src/optimize.bjo
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
;; Searches for a better layout by simulated annealing: see (keyscore search).
|
||||
;;
|
||||
;; bjo run src/optimize.bjo [runs] [steps] [layout] [t-start] [option ...]
|
||||
;;
|
||||
;; - runs: independent searches, each with its own seed. 8 unless given.
|
||||
;; - steps: swaps tried per run. 200000 unless given.
|
||||
;; - layout: the layout to start from, by name. The last in (keyscore layouts)
|
||||
;; unless given, or given as "-".
|
||||
;; - t-start: the starting temperature. 0.02 unless given: a run refines the
|
||||
;; start layout rather than replacing it.
|
||||
;; - options, after t-start, in any order:
|
||||
;; - vowels-left: the vowels (a e i o u y å ä ö) stay on left-hand keys. The
|
||||
;; start layout has to have them there.
|
||||
;; - fixed=CHARS: the keys of CHARS (written as in a layout, any case) do
|
||||
;; not move. Can be given more than once.
|
||||
;;
|
||||
;; Scores with `current-params`: params.txt when there is one. Prints each
|
||||
;; run's best layout, then the best of all as a make-layout form for
|
||||
;; (keyscore layouts), scored again by the full scorer. Raises if the
|
||||
;; search's scorer and the full one disagree on the start layout.
|
||||
|
||||
(import (std prelude))
|
||||
(import (only (std fmt) numeric render->string))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore score))
|
||||
(import (keyscore search))
|
||||
(import (keyscore texts))
|
||||
|
||||
(: (-> double string))
|
||||
(defun (fixed x) (render->string (numeric x #:precision 3)))
|
||||
|
||||
(defun (main args)
|
||||
(def arg (fun (i default) (if (> (length args) i) (string->int (ref args i)) default)))
|
||||
(: named? (-> Layout bool))
|
||||
(def named? (fun (l) (= (record-ref l name) (ref args 2))))
|
||||
(def start-layout (if (and (> (length args) 2) (not (= (ref args 2) "-")))
|
||||
(option-ref (find named? layouts))
|
||||
(vec-ref layouts (- (vec-length layouts) 1))))
|
||||
(def options (loop (:for i (range 4 (length args))) (:acc out (listing (ref args i)))))
|
||||
(loop (:for o options)
|
||||
(:when (not (or (= o "vowels-left") (string-starts-with? o "fixed="))))
|
||||
(:do (panic! (str "unknown option " (written o) ": give vowels-left or fixed=CHARS"))))
|
||||
(def fixed-chars (string-join (list->vec (loop (:for o options) (:when (string-starts-with? o "fixed="))
|
||||
(:acc out (listing (string-drop o 6)))))
|
||||
""))
|
||||
(def o (Options (runs (arg 0 8))
|
||||
(steps (arg 1 200000))
|
||||
(t-start (if (> (length args) 3) (string->double (ref args 3))
|
||||
(record-ref default-options t-start)))
|
||||
(vowels-left (any? (fun (o) (= o "vowels-left")) options))
|
||||
(fixed fixed-chars)))
|
||||
(def params (current-params))
|
||||
(when (file-exists? params-file) (println (str "Parameters from " params-file ".")))
|
||||
(def counts (count-files layouts (vec-map corpus-path (record-ref params corpora))))
|
||||
(def p (problem-of params start-layout counts))
|
||||
(def fast-start (problem-score p))
|
||||
(def full-start (mean-score params start-layout counts))
|
||||
(println (str "Starting temperature " (fixed (record-ref o t-start)) "."))
|
||||
(println (str (record-ref start-layout name) ": " (fixed full-start)
|
||||
" by the full scorer, " (fixed fast-start) " by the search's."))
|
||||
(when (> (abs (- fast-start full-start)) 0.000001)
|
||||
(panic! "the search's scorer does not agree with the full one"))
|
||||
(when (record-ref o vowels-left) (println "Vowels stay on the left hand."))
|
||||
(when (not (= fixed-chars "")) (println (str "Fixed: " fixed-chars ".")))
|
||||
(def results (search p o))
|
||||
(loop (:for f results) (:for run (range 1 (+ (vec-length results) 1)))
|
||||
(:do (println (str "run " (displayed run) ": " (fixed (record-ref f score)) "\n "
|
||||
(string-join (record-ref f rows) "\n ")))))
|
||||
(def best (vec-fold (fun (f b) (if (< (record-ref f score) (record-ref b score)) f b))
|
||||
(vec-ref results 0) results))
|
||||
(def rows (record-ref best rows))
|
||||
(def found (make-layout "found" (vec-ref rows 0) (vec-ref rows 1) (vec-ref rows 2)))
|
||||
(println "")
|
||||
(println (str "The best, " (fixed (mean-score params found counts)) " by the full scorer:"))
|
||||
(println (str " (make-layout \"found\"\n \"" (vec-ref rows 0) "\"\n \""
|
||||
(vec-ref rows 1) "\"\n \"" (vec-ref rows 2) "\")"))
|
||||
0)
|
||||
285
src/params.bjo
Normal file
285
src/params.bjo
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
;; The numbers the scorer is tuned with, and the file they are kept in.
|
||||
;;
|
||||
;; - `default-params` are the numbers as (keyscore score) describes them.
|
||||
;; - `param-specs` lists every number by name, with its group and range. The
|
||||
;; file and the GUI both go through it.
|
||||
;; - `current-params` reads `params-file` when there is one, so that every
|
||||
;; program scores with what the GUI saved.
|
||||
;;
|
||||
;; The file has one number per line, `name value`, such as `same-finger 50`
|
||||
;; or `key.q 10`. A line that is empty or starts with ; is skipped. A number
|
||||
;; it does not name keeps its default.
|
||||
;;
|
||||
;; Errors:
|
||||
;; - `load-params` raises on a line it cannot read, or a name it does not know.
|
||||
|
||||
(import (std prelude))
|
||||
(import (keyscore board))
|
||||
(import (keyscore texts))
|
||||
|
||||
(export Params Spec default-params param-specs params-file current-params load-params
|
||||
save-params key-cost)
|
||||
|
||||
;; The fields, by the rules of (keyscore score):
|
||||
;; - corpora: the texts and their weights in the mean.
|
||||
;; - key-weight: what each key cost is multiplied by. key-costs: each key's
|
||||
;; cost, by index in `board`.
|
||||
;; - top-vowel: a vowel's press on the top row.
|
||||
;; - stretch, same-finger, jump, easy-jump, close-keys, adjacent-keys: the
|
||||
;; pair rules.
|
||||
;; - spaced: the share of a pair's cost charged when a space is between.
|
||||
;; - low-share: how much of the roll bonuses a pair with a bottom-row key off
|
||||
;; the index keys earns, and how much of the hand-run cost a triple of them
|
||||
;; on one row is spared. 0 none, 1 all.
|
||||
;; - outward, inward, twist, bottom-index, bottom-other, one-finger: the row
|
||||
;; motion table.
|
||||
;; - hand-run, skip, two-finger: the triple rules.
|
||||
;; - pinky-limit, pinky-cost: the pinky load.
|
||||
;; - distance: what a key width of finger travel costs. 0: only reported.
|
||||
(type (: Params (Record (: corpora (Vec Corpus))
|
||||
(: key-weight double)
|
||||
(: key-costs (Vec double))
|
||||
(: top-vowel double)
|
||||
(: stretch double)
|
||||
(: same-finger double)
|
||||
(: jump double)
|
||||
(: easy-jump double)
|
||||
(: close-keys double)
|
||||
(: adjacent-keys double)
|
||||
(: spaced double)
|
||||
(: low-share double)
|
||||
(: outward double)
|
||||
(: inward double)
|
||||
(: twist double)
|
||||
(: bottom-index double)
|
||||
(: bottom-other double)
|
||||
(: one-finger double)
|
||||
(: hand-run double)
|
||||
(: skip double)
|
||||
(: two-finger double)
|
||||
(: pinky-limit double)
|
||||
(: pinky-cost double)
|
||||
(: distance double))))
|
||||
|
||||
(: Params)
|
||||
(def default-params
|
||||
(Params (corpora default-corpora)
|
||||
(key-weight 2.0)
|
||||
(key-costs (vec-map (fun (k) (cast double (record-ref k cost))) board))
|
||||
(top-vowel 4.0)
|
||||
(stretch 5.0)
|
||||
(same-finger 50.0)
|
||||
(jump 30.0)
|
||||
(easy-jump -20.0)
|
||||
(close-keys -4.0)
|
||||
(adjacent-keys -3.0)
|
||||
(spaced 0.5)
|
||||
(low-share 0.0)
|
||||
(outward 2.0)
|
||||
(inward 4.0)
|
||||
(twist 12.0)
|
||||
(bottom-index 5.0)
|
||||
(bottom-other 12.0)
|
||||
(one-finger 5.0)
|
||||
(hand-run 10.0)
|
||||
(skip 10.0)
|
||||
(two-finger 10.0)
|
||||
(pinky-limit 0.08)
|
||||
(pinky-cost 10.0)
|
||||
(distance 0.0)))
|
||||
|
||||
;; What a press of `k` costs: its cost times the key weight.
|
||||
(: (-> Params Key double))
|
||||
(defun (key-cost p k)
|
||||
(* (record-ref p key-weight) (vec-ref (record-ref p key-costs) (record-ref k index))))
|
||||
|
||||
;; One number of `Params`.
|
||||
;;
|
||||
;; - name: in the file. label and group: in the GUI.
|
||||
;; - help: what the number does, for the GUI's info marks.
|
||||
;; - get and set: read it from, and put it in, a `Params`.
|
||||
;; - minimum, maximum and step: for the GUI's input.
|
||||
(type (: Spec (Record (: name string)
|
||||
(: label string)
|
||||
(: group string)
|
||||
(: help string)
|
||||
(: get (-> Params double))
|
||||
(: set (-> Params double Params))
|
||||
(: minimum double)
|
||||
(: maximum double)
|
||||
(: step double))))
|
||||
|
||||
(: (-> string string string string (-> Params double) (-> Params double Params) double double double Spec))
|
||||
(defun (spec name label group help get set minimum maximum step)
|
||||
(Spec (name name) (label label) (group group) (help help) (get get) (set set)
|
||||
(minimum minimum) (maximum maximum) (step step)))
|
||||
|
||||
;; A spec for a cost or bonus from -100 to 100, in steps of 1.
|
||||
(: (-> string string string string (-> Params double) (-> Params double Params) Spec))
|
||||
(defun (cost-spec name label group help get set) (spec name label group help get set -100.0 100.0 1.0))
|
||||
|
||||
;; The specs of the texts' weights, one for each corpus.
|
||||
(: (Vec Spec))
|
||||
(def corpus-specs
|
||||
(loop (:for c default-corpora) (:for i (range 0 (vec-length default-corpora)))
|
||||
(:let file (option-ref-or (path-filename (corpus-path c)) (corpus-path c)))
|
||||
(:acc out (vecing (spec (str "weight." file) file "Texts"
|
||||
(str "How much " file " counts in the mean score. The weights are relative: "
|
||||
"1 and 1 is the same as 2 and 2. 0 removes the text from the mean.")
|
||||
(fun (p) (corpus-weight (vec-ref (record-ref p corpora) i)))
|
||||
(fun (p x)
|
||||
(def cs (record-ref p corpora))
|
||||
(record-set p (corpora (vec-set cs i (corpus (corpus-path (vec-ref cs i)) x)))))
|
||||
0.0 10.0 0.25)))))
|
||||
|
||||
;; The specs of the key costs, one for each key, named by the key.
|
||||
(: (Vec Spec))
|
||||
(def key-specs
|
||||
(vec-map (fun (k)
|
||||
(def i (record-ref k index))
|
||||
(def label (string-upcase (record-ref k name)))
|
||||
(spec (str "key." (record-ref k name)) label "Key costs"
|
||||
(str "The cost of one press of the key " label " (its name on Swedish QWERTY). "
|
||||
"It is multiplied by the key weight.")
|
||||
(fun (p) (vec-ref (record-ref p key-costs) i))
|
||||
(fun (p x) (record-set p (key-costs (vec-set (record-ref p key-costs) i x))))
|
||||
0.0 100.0 1.0))
|
||||
board))
|
||||
|
||||
;; Every number of `Params`, in the order the GUI shows them.
|
||||
(: (Vec Spec))
|
||||
(def param-specs
|
||||
(vec-append
|
||||
(vec-append
|
||||
corpus-specs
|
||||
[(spec "key-weight" "Key weight" "Keys"
|
||||
"Multiplies every key cost. A press costs its key's cost (the Key costs tab) times this number. 0 ignores the key costs."
|
||||
(fun (p) (record-ref p key-weight))
|
||||
(fun (p x) (record-set p (key-weight x))) 0.0 20.0 0.25)
|
||||
(cost-spec "top-vowel" "Vowel on the top row" "Keys"
|
||||
"Added to each press of a vowel (a e i o u y å ä ö) on the top row. This keeps the vowels on the home and bottom rows."
|
||||
(fun (p) (record-ref p top-vowel))
|
||||
(fun (p x) (record-set p (top-vowel x))))
|
||||
(cost-spec "stretch" "Stretch key" "Pairs"
|
||||
"Added to a pair on one hand for each of its keys that is a stretch key: the centre columns (T G B, Y H) and the right pinky's keys past P and Ö."
|
||||
(fun (p) (record-ref p stretch))
|
||||
(fun (p x) (record-set p (stretch x))))
|
||||
(cost-spec "same-finger" "Same finger" "Pairs"
|
||||
"Added when one finger types two different keys one after the other."
|
||||
(fun (p) (record-ref p same-finger))
|
||||
(fun (p x) (record-set p (same-finger x))))
|
||||
(cost-spec "jump" "Jump, top to bottom" "Pairs"
|
||||
"Added to a pair on one hand with one key on the top row and the other on the bottom row."
|
||||
(fun (p) (record-ref p jump))
|
||||
(fun (p x) (record-set p (jump x))))
|
||||
(cost-spec "easy-jump" "Easy jump" "Pairs"
|
||||
"Added to a jump that is easy to type: VE VW NI NO MI MO CE CW, by QWERTY key, in either order. A negative number is a bonus."
|
||||
(fun (p) (record-ref p easy-jump))
|
||||
(fun (p x) (record-set p (easy-jump x))))
|
||||
(cost-spec "close-keys" "Close keys" "Pairs"
|
||||
"Added when two different fingers of one hand type a pair and neither key is a stretch key. A negative number is a bonus."
|
||||
(fun (p) (record-ref p close-keys))
|
||||
(fun (p x) (record-set p (close-keys x))))
|
||||
(cost-spec "adjacent-keys" "Adjacent keys" "Pairs"
|
||||
"Added when two fingers type neighbouring keys of one row. It is added to the close-keys number. A negative number is a bonus."
|
||||
(fun (p) (record-ref p adjacent-keys))
|
||||
(fun (p x) (record-set p (adjacent-keys x))))
|
||||
(spec "spaced" "Share across a space" "Pairs"
|
||||
"The share of a pair's cost that is charged when a space is between the two presses. 0: free. 1: the full cost."
|
||||
(fun (p) (record-ref p spaced))
|
||||
(fun (p x) (record-set p (spaced x))) 0.0 1.0 0.05)
|
||||
(spec "low-share" "Bottom-row rolls (0 none, 1 as home)" "Pairs"
|
||||
"The share of the close-keys and adjacent-keys bonuses that a pair gets when it has a bottom-row key off the index keys (not C V N M). It also sets how much of the hand-run cost a triple of such keys on one row avoids. 0: no bonus. 1: the same as on the home row."
|
||||
(fun (p) (record-ref p low-share))
|
||||
(fun (p x) (record-set p (low-share x))) 0.0 1.0 0.05)
|
||||
(cost-spec "outward" "Home to top, outer finger up" "Row motion"
|
||||
"A pair on one hand from the home row to the top row, with the outer finger (nearer the pinky) on the top row. The hand keeps its shape."
|
||||
(fun (p) (record-ref p outward))
|
||||
(fun (p x) (record-set p (outward x))))
|
||||
(cost-spec "inward" "Top to home, outer finger up" "Row motion"
|
||||
"A pair on one hand from the top row to the home row, with the outer finger (nearer the pinky) on the top row."
|
||||
(fun (p) (record-ref p inward))
|
||||
(fun (p x) (record-set p (inward x))))
|
||||
(cost-spec "twist" "Home and top, inner finger or pinky up" "Row motion"
|
||||
"A pair on one hand on the home and top rows, in either order, with the inner finger (nearer the thumb) or a pinky on the top row. The hand twists."
|
||||
(fun (p) (record-ref p twist))
|
||||
(fun (p x) (record-set p (twist x))))
|
||||
(cost-spec "bottom-index" "Bottom index and home" "Row motion"
|
||||
"A pair on one hand of a bottom-row index key (C V N M) and a home-row key, in either order."
|
||||
(fun (p) (record-ref p bottom-index))
|
||||
(fun (p x) (record-set p (bottom-index x))))
|
||||
(cost-spec "bottom-other" "Other pairs with the bottom row" "Row motion"
|
||||
"Any other pair on one hand with a key on the bottom row and a key on another row."
|
||||
(fun (p) (record-ref p bottom-other))
|
||||
(fun (p x) (record-set p (bottom-other x))))
|
||||
(cost-spec "one-finger" "One finger on two rows" "Row motion"
|
||||
"The row-motion cost when one finger types keys on two rows. The same-finger cost is added as well."
|
||||
(fun (p) (record-ref p one-finger))
|
||||
(fun (p x) (record-set p (one-finger x))))
|
||||
(cost-spec "hand-run" "Hand run" "Triples"
|
||||
"Added for three presses on one hand with no space between, unless all three keys are on one row."
|
||||
(fun (p) (record-ref p hand-run))
|
||||
(fun (p x) (record-set p (hand-run x))))
|
||||
(cost-spec "skip" "Same-finger skip" "Triples"
|
||||
"Added when the first and third presses of three are two different keys of one finger, such as E, R, D on QWERTY."
|
||||
(fun (p) (record-ref p skip))
|
||||
(fun (p x) (record-set p (skip x))))
|
||||
(cost-spec "two-finger" "Two-finger run" "Triples"
|
||||
"Added for three presses on one hand by only two fingers, such as middle, ring, middle. A double letter is not one."
|
||||
(fun (p) (record-ref p two-finger))
|
||||
(fun (p x) (record-set p (two-finger x))))
|
||||
(spec "pinky-limit" "Pinky limit (share of presses)" "Pinky load"
|
||||
"The share of all presses each pinky can type at no cost. 0.08 is 8%. Spaces are not counted."
|
||||
(fun (p) (record-ref p pinky-limit))
|
||||
(fun (p x) (record-set p (pinky-limit x))) 0.0 0.5 0.01)
|
||||
(cost-spec "pinky-cost" "Cost past the limit" "Pinky load"
|
||||
"The cost of each pinky press over the pinky limit."
|
||||
(fun (p) (record-ref p pinky-cost))
|
||||
(fun (p x) (record-set p (pinky-cost x))))
|
||||
(spec "distance" "Per key width of travel" "Finger distance"
|
||||
"The cost of each key width that a finger moves. A finger moves from its home key, or from the key it pressed just before. After a space it starts at home again. 0: the distance is shown but not scored."
|
||||
(fun (p) (record-ref p distance))
|
||||
(fun (p x) (record-set p (distance x))) 0.0 100.0 0.5)])
|
||||
key-specs))
|
||||
|
||||
(: string)
|
||||
(def params-file "params.txt")
|
||||
|
||||
;; The spec named `name`, if there is one.
|
||||
(: (-> string (Option Spec)))
|
||||
(defun (spec-named name)
|
||||
(: named? (-> Spec bool))
|
||||
(def named? (fun (s) (= (record-ref s name) name)))
|
||||
(find named? param-specs))
|
||||
|
||||
;; `p` with the numbers of the file's `text`. Raises on a line it cannot read.
|
||||
(: (-> Params string Params))
|
||||
(defun (read-params p text)
|
||||
(loop (:for raw (string-split text "\n"))
|
||||
(:let line (string-trim raw))
|
||||
(:when (not (or (= line "") (string-starts-with? line ";"))))
|
||||
(:let fields (vec-filter (fun (f) (not (= f ""))) (string-split line " ")))
|
||||
(:do (when (not (= (vec-length fields) 2))
|
||||
(panic! (str params-file ": cannot read the line " (written line)))))
|
||||
(:let name (vec-ref fields 0))
|
||||
(:let s (match (spec-named name)
|
||||
((Some s) s)
|
||||
(None (panic! (str params-file ": no number is named " (written name))))))
|
||||
(:acc out (folding p ((record-ref s set) out (string->double (vec-ref fields 1)))))))
|
||||
|
||||
;; The numbers of the file at `path`, on top of `default-params`.
|
||||
(: (-> string Params))
|
||||
(defun (load-params path) (read-params default-params (file-read-text path)))
|
||||
|
||||
;; The numbers of `params-file` if there is one, else `default-params`.
|
||||
(: (-> Params))
|
||||
(defun (current-params)
|
||||
(if (file-exists? params-file) (load-params params-file) default-params))
|
||||
|
||||
;; Writes every number of `p` to the file at `path`.
|
||||
(: (-> Params string void))
|
||||
(defun (save-params p path)
|
||||
(def lines (vec-map (fun (s) (str (record-ref s name) " " (displayed ((record-ref s get) p))))
|
||||
param-specs))
|
||||
(file-write-text path (str ";; keyscore's parameters. See src/params.bjo.\n"
|
||||
(string-join lines "\n") "\n")))
|
||||
89
src/saved.bjo
Normal file
89
src/saved.bjo
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
;; Presets and saved layouts: what the GUI keeps between runs.
|
||||
;;
|
||||
;; - A preset is a set of numbers, kept as presets/NAME.txt in the format of
|
||||
;; `params-file`. See (keyscore params).
|
||||
;; - The saved layouts are kept in `layouts-file`, one layout per line: its
|
||||
;; name and its three rows, separated by tabs.
|
||||
;;
|
||||
;; Errors:
|
||||
;; - `save-preset`, `load-preset`, `delete-preset` and `write-saved-layouts`
|
||||
;; raise when the file cannot be read or written.
|
||||
;; - `read-saved-layouts` skips a line it cannot read.
|
||||
|
||||
(import (std prelude))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
|
||||
(export presets-folder layouts-file valid-name? preset-names save-preset load-preset delete-preset
|
||||
read-saved-layouts write-saved-layouts)
|
||||
|
||||
(: string)
|
||||
(def presets-folder "presets")
|
||||
|
||||
(: string)
|
||||
(def layouts-file "saved-layouts.txt")
|
||||
|
||||
;; Whether `name` can name a preset or a saved layout: not empty, no
|
||||
;; surrounding spaces, no tab, line break, / or \, and not starting with a dot.
|
||||
(: (-> string bool))
|
||||
(defun (valid-name? name)
|
||||
(and (not (= name ""))
|
||||
(= name (string-trim name))
|
||||
(not (string-starts-with? name "."))
|
||||
(not (any? (fun (c) (string-contains? name c)) (list "\t" "\n" "\r" "/" "\\")))))
|
||||
|
||||
(: (-> string string))
|
||||
(defun (preset-path name) (path-combine presets-folder (str name ".txt")))
|
||||
|
||||
;; The names of the presets, sorted. Empty when there is no presets folder.
|
||||
(: (-> (Vec string)))
|
||||
(defun (preset-names)
|
||||
(if (directory-exists? presets-folder)
|
||||
(vec-sort (loop (:for path (directory-files presets-folder))
|
||||
(:let file (option-ref-or (path-filename path) path))
|
||||
(:when (string-ends-with? file ".txt"))
|
||||
(:acc out (vecing (string-drop-right file 4)))))
|
||||
[]))
|
||||
|
||||
;; Writes `p` as the preset `name`, replacing one of that name. Returns the
|
||||
;; names of the presets after.
|
||||
(: (-> string Params (Vec string)))
|
||||
(defun (save-preset name p)
|
||||
(when (not (directory-exists? presets-folder)) (directory-create presets-folder))
|
||||
(save-params p (preset-path name))
|
||||
(preset-names))
|
||||
|
||||
;; The numbers of the preset `name`.
|
||||
(: (-> string Params))
|
||||
(defun (load-preset name) (load-params (preset-path name)))
|
||||
|
||||
;; Deletes the preset `name`. Returns the names of the presets after.
|
||||
(: (-> string (Vec string)))
|
||||
(defun (delete-preset name)
|
||||
(file-delete (preset-path name))
|
||||
(preset-names))
|
||||
|
||||
;; The layout of one line of `layouts-file`, if the line holds one.
|
||||
(: (-> string (Option Layout)))
|
||||
(defun (layout-of-line line)
|
||||
(def fields (string-split line "\t"))
|
||||
(if (= (vec-length fields) 4)
|
||||
(result->option (try (make-layout (vec-ref fields 0) (vec-ref fields 1) (vec-ref fields 2)
|
||||
(vec-ref fields 3))
|
||||
#:catch (System.Exception)))
|
||||
None))
|
||||
|
||||
;; The layouts of `layouts-file`, in its order. Empty when there is none.
|
||||
(: (-> (Vec Layout)))
|
||||
(defun (read-saved-layouts)
|
||||
(if (file-exists? layouts-file)
|
||||
(loop (:for line (string-split (file-read-text layouts-file) "\n"))
|
||||
(:let found (layout-of-line (string-trim-right line)))
|
||||
(:acc out (folding [] (match found ((Some l) (vec-add out l)) (None out)))))
|
||||
[]))
|
||||
|
||||
;; Writes `ls` to `layouts-file`, replacing what it held.
|
||||
(: (-> (Vec Layout) void))
|
||||
(defun (write-saved-layouts ls)
|
||||
(def lines (vec-map (fun (l) (string-join (vec-append [(record-ref l name)] (record-ref l rows)) "\t")) ls))
|
||||
(file-write-text layouts-file (string-join (vec-map (fun (s) (str s "\n")) lines) "")))
|
||||
471
src/score.bjo
Normal file
471
src/score.bjo
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
;; Scoring a layout on a text, by Michael Capewell's rules. Higher is worse.
|
||||
;;
|
||||
;; Every number below is a default: (keyscore params) holds the ones scored
|
||||
;; with, by the names in brackets.
|
||||
;;
|
||||
;; - Each key press costs its key's cost times the key weight, 2 (key-weight,
|
||||
;; key.q ...). See (keyscore board).
|
||||
;; - A vowel (a e i o u y å ä ö) typed on the top row costs 4 more per press
|
||||
;; (top-vowel). Not Capewell's.
|
||||
;; - Each pair of consecutive presses on one hand, on two different keys, is
|
||||
;; scored by `rules`. A pair on two hands, or one key pressed twice, scores
|
||||
;; nothing.
|
||||
;; - A pair with a space between costs half (spaced), the thumb's press
|
||||
;; between. A character that is not counted (a digit, a parenthesis, a
|
||||
;; newline) breaks the text: no pair spans it.
|
||||
;;
|
||||
;; The rules, for a pair on one hand:
|
||||
;; - stretch: +5 for each of the two keys that is a stretch key: before and
|
||||
;; after the reach (stretch).
|
||||
;; - row motion: the cost of moving between rows, by direction. Not Capewell's:
|
||||
;; it replaces his +5 for a row change. See below.
|
||||
;; - same finger: +50 when one finger types both keys (same-finger).
|
||||
;; - jump: +30 when one key is on the top row and the other on the bottom
|
||||
;; (jump).
|
||||
;; - easy jump: -20 for a jump Capewell finds easy: VE VW NI NO MI MO, either
|
||||
;; way round, by Swedish QWERTY key (easy-jump). The angle mod puts C under
|
||||
;; the index too, so CE and CW are easy as well.
|
||||
;; - close keys: -4 when two fingers type the keys and neither is a stretch
|
||||
;; (close-keys).
|
||||
;; - adjacent keys: -3 when two fingers type neighbouring keys of one row
|
||||
;; (adjacent-keys). A pair can be both close and adjacent.
|
||||
;; - A pair with a key on the bottom row off its index keys (C V, N M) earns
|
||||
;; none of the two bonuses: rolling along the bottom row earns nothing.
|
||||
;; low-share gives it a share of them. Not Capewell's.
|
||||
;;
|
||||
;; Row motion, for a pair on one hand:
|
||||
;;
|
||||
;; one row 0
|
||||
;; home -> top, the outer finger up (outward) 2
|
||||
;; top -> home, the outer finger up (inward) 4
|
||||
;; home <-> top, the inner finger or a pinky up 12 (twist)
|
||||
;; bottom index <-> home 5 (bottom-index)
|
||||
;; any other pair with the bottom row 12 (bottom-other)
|
||||
;; one finger on two rows 5 (one-finger)
|
||||
;;
|
||||
;; - The outer finger is the one nearer the pinky. With it on the top row the
|
||||
;; hand keeps its shape; with the inner finger up it twists.
|
||||
;; - 12 is Capewell's row change and the old same-hand cost together. Close
|
||||
;; keys take 4 back, so a pair costing 4 or more never beats typing it with
|
||||
;; both hands, and a pair on one row does.
|
||||
;;
|
||||
;; Not Capewell's, for three presses with no space between:
|
||||
;; - hand runs: +10 for three presses in a row on one hand, unless all three
|
||||
;; are on one row (hand-run). A triple on one row with a bottom-row key off
|
||||
;; the index keys is a run too, spared by low-share.
|
||||
;; - same-finger skips: +10 when the first and third keys are two keys of one
|
||||
;; finger (skip). Typing with both hands makes these common: left, right,
|
||||
;; left.
|
||||
;; - two-finger runs: +10 for three presses on one hand by two fingers, such
|
||||
;; as middle, ring, middle (two-finger). A key pressed twice in a row (a
|
||||
;; double letter) is not one.
|
||||
;;
|
||||
;; The pinky load is not Capewell's either. It is scored over the whole text,
|
||||
;; for each pinky on its own:
|
||||
;; - The pinky's share is its presses over all presses (spaces not counted).
|
||||
;; - Each press past 8% of all presses (pinky-limit) costs 10 (pinky-cost):
|
||||
;; the cost of a pinky key off the home row.
|
||||
;; - A pinky at or under the limit costs nothing.
|
||||
;;
|
||||
;; Finger distance: how far the fingers travel, in key widths per press.
|
||||
;; - A finger goes from its home key to the key it presses, unless it pressed
|
||||
;; the key before: then it goes from that key. A double letter travels 0.
|
||||
;; - A space or a break between two presses lets the finger go home.
|
||||
;; - The way back is not counted.
|
||||
;; - It costs 0 per key width (distance): it is reported, not scored.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std mutable map))
|
||||
(import (keyscore board))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
|
||||
(export Counts count-text count-files Rule rules pair-penalty triple-penalty hand-run
|
||||
same-finger-skip two-finger-run pinky-penalty top-vowel home-travel pair-travel
|
||||
Score score-layout pair-costs)
|
||||
|
||||
;; --- counting --------------------------------------------------------------
|
||||
|
||||
;; What a text holds, for the characters counted.
|
||||
;;
|
||||
;; - presses: how often each character is typed.
|
||||
;; - pairs: how often each pair of characters is typed one after the other.
|
||||
;; - spaced: how often each pair is typed with spaces between them.
|
||||
;; - triples: how often each three characters are typed one after the other,
|
||||
;; with no space between.
|
||||
;; - chars: every character of the text, counted or not.
|
||||
(type (: Counts (Record (: presses (MutableMap char int))
|
||||
(: pairs (MutableMap (Tuple char char) int))
|
||||
(: spaced (MutableMap (Tuple char char) int))
|
||||
(: triples (MutableMap (Tuple char char char) int))
|
||||
(: chars int))))
|
||||
|
||||
(: (-> (MutableMap %k int) %k void))
|
||||
(defun (count! m k)
|
||||
(mutablemap-update! m k (fun (n) (+ n 1)) #:default (Some 0)))
|
||||
|
||||
;; The character before, if the run has not been broken, and whether a space
|
||||
;; came after it. `before` is the character before that one, if there was no
|
||||
;; space or break between them.
|
||||
(type (: Prev (Record (: char (Option char)) (: before (Option char)) (: spaced? bool))))
|
||||
|
||||
;; One character of the text: counted, a space, or a break.
|
||||
(: (-> Counts (-> char bool) Prev char Prev))
|
||||
(defun (step counts counted? prev raw)
|
||||
(def c (normalize raw))
|
||||
(cond
|
||||
((counted? c)
|
||||
(count! (record-ref counts presses) c)
|
||||
(def spaced? (record-ref prev spaced?))
|
||||
(when-let (p (record-ref prev char))
|
||||
(count! (if spaced? (record-ref counts spaced) (record-ref counts pairs)) (Tuple p c))
|
||||
(when-let (b (record-ref prev before))
|
||||
(when (not spaced?) (count! (record-ref counts triples) (Tuple b p c)))))
|
||||
(Prev (char (Some c)) (before (if spaced? None (record-ref prev char))) (spaced? #f)))
|
||||
((or (char=? c #\space) (char=? c (int->char 0xA0)))
|
||||
(Prev (char (record-ref prev char)) (before None) (spaced? #t)))
|
||||
(else (Prev (char None) (before None) (spaced? #f)))))
|
||||
|
||||
;; The counts of `text`, for the characters `counted?` holds for. The
|
||||
;; characters are normalized first: see `normalize`.
|
||||
(: (-> string (-> char bool) Counts))
|
||||
(defun (count-text text counted?)
|
||||
(def counts (Counts (presses (mutablemap)) (pairs (mutablemap)) (spaced (mutablemap))
|
||||
(triples (mutablemap)) (chars (string-length text))))
|
||||
(ignore (loop (:for c text)
|
||||
(:acc prev (folding (Prev (char None) (before None) (spaced? #f))
|
||||
(step counts counted? prev c)))))
|
||||
counts)
|
||||
|
||||
;; The counts of each file in `paths`, for the characters every layout in
|
||||
;; `ls` types.
|
||||
(: (-> (Vec Layout) (Vec string) (Vec Counts)))
|
||||
(defun (count-files ls paths)
|
||||
(def counted (->map (map (fun (c) (Tuple c #t)) (common-chars ls))))
|
||||
(vec-map (fun (p) (count-text (file-read-text p) (fun (c) (map-contains? counted c)))) paths))
|
||||
|
||||
;; --- the pinky load ----------------------------------------------------------
|
||||
|
||||
;; The pinky load's penalty per press, for a pinky with `share` of the presses.
|
||||
(: (-> Params double double))
|
||||
(defun (pinky-penalty p share)
|
||||
(* (record-ref p pinky-cost) (max 0.0 (- share (record-ref p pinky-limit)))))
|
||||
|
||||
;; --- vowels on the top row ----------------------------------------------------
|
||||
|
||||
;; What typing `c` on `k` costs besides the key's cost: top-vowel for a vowel
|
||||
;; on the top row, else 0. `c` is normalized.
|
||||
(: (-> Params char Key double))
|
||||
(defun (top-vowel p c k)
|
||||
(if (and (= (record-ref k row) 0) (any? (fun (v) (char=? v c)) (->list "aeiouyåäö")))
|
||||
(record-ref p top-vowel)
|
||||
0.0))
|
||||
|
||||
;; --- finger distance -----------------------------------------------------------
|
||||
|
||||
;; How far `k`'s finger travels from its home key to press it.
|
||||
(: (-> Key double))
|
||||
(defun (home-travel k) (key-distance (home-key k) k))
|
||||
|
||||
;; How much farther `b`'s finger travels pressed right after `a` than from
|
||||
;; home: from `a` instead of from home when one finger types both, else 0.
|
||||
(: (-> Key Key double))
|
||||
(defun (pair-travel a b)
|
||||
(if (and (= (record-ref a left?) (record-ref b left?)) (= (record-ref a finger) (record-ref b finger)))
|
||||
(- (key-distance a b) (home-travel b))
|
||||
0.0))
|
||||
|
||||
;; --- the rules ---------------------------------------------------------------
|
||||
|
||||
(type (: Rule (Record (: name string) (: penalty (-> Params Key Key double)))))
|
||||
|
||||
(: (-> bool double))
|
||||
(defun (one-if b) (if b 1.0 0.0))
|
||||
|
||||
(: (-> Key Key bool))
|
||||
(defun (two-fingers? a b) (not (= (record-ref a finger) (record-ref b finger))))
|
||||
|
||||
(: (-> Key Key bool))
|
||||
(defun (no-stretch? a b) (not (or (record-ref a stretch?) (record-ref b stretch?))))
|
||||
|
||||
(: (-> Key Key bool))
|
||||
(defun (jump? a b)
|
||||
(and (= (+ (record-ref a row) (record-ref b row)) 2)
|
||||
(not (= (record-ref a row) 1))))
|
||||
|
||||
;; The jumps Capewell finds easy, as Swedish QWERTY key names: the index on
|
||||
;; the bottom row and the middle or ring finger on the top row.
|
||||
(def easy-jumps (list "ve" "vw" "ce" "cw" "ni" "no" "mi" "mo"))
|
||||
|
||||
(: (-> Key Key bool))
|
||||
(defun (easy-jump? a b)
|
||||
(def ab (str (record-ref a name) (record-ref b name)))
|
||||
(def ba (str (record-ref b name) (record-ref a name)))
|
||||
(any? (fun (p) (or (= p ab) (= p ba))) easy-jumps))
|
||||
|
||||
;; Whether `k` is on the bottom row and not one of its index keys: C V and
|
||||
;; N M. B is a stretch key and counts as off the index keys.
|
||||
(: (-> Key bool))
|
||||
(defun (low? k)
|
||||
(and (= (record-ref k row) 2)
|
||||
(or (not (= (record-ref k finger) 3)) (record-ref k stretch?))))
|
||||
|
||||
;; The share of the roll bonuses a pair earns: all of them, or low-share
|
||||
;; when a key is `low?`.
|
||||
(: (-> Params Key Key double))
|
||||
(defun (roll-share p a b)
|
||||
(if (or (low? a) (low? b)) (record-ref p low-share) 1.0))
|
||||
|
||||
;; The rules' penalties, for a pair on one hand.
|
||||
|
||||
(: (-> Params Key Key double))
|
||||
(defun (stretch p a b)
|
||||
(* (record-ref p stretch) (+ (one-if (record-ref a stretch?)) (one-if (record-ref b stretch?)))))
|
||||
|
||||
(: (-> Params Key Key double))
|
||||
(defun (same-finger p a b) (* (record-ref p same-finger) (one-if (not (two-fingers? a b)))))
|
||||
|
||||
(: (-> Params Key Key double))
|
||||
(defun (jump p a b) (* (record-ref p jump) (one-if (jump? a b))))
|
||||
|
||||
(: (-> Params Key Key double))
|
||||
(defun (easy-jump p a b) (* (record-ref p easy-jump) (one-if (and (jump? a b) (easy-jump? a b)))))
|
||||
|
||||
(: (-> Params Key Key double))
|
||||
(defun (close-keys p a b)
|
||||
(* (record-ref p close-keys) (roll-share p a b)
|
||||
(one-if (and (two-fingers? a b) (no-stretch? a b)))))
|
||||
|
||||
(: (-> Key bool))
|
||||
(defun (pinky? k) (= (record-ref k finger) 0))
|
||||
|
||||
(: (-> Key bool))
|
||||
(defun (index? k) (= (record-ref k finger) 3))
|
||||
|
||||
;; The row-motion cost of `a` then `b`, by the table in the header.
|
||||
(: (-> Params Key Key double))
|
||||
(defun (row-motion p a b)
|
||||
(def ra (record-ref a row))
|
||||
(def rb (record-ref b row))
|
||||
(cond ((= ra rb) 0.0)
|
||||
((not (two-fingers? a b)) (record-ref p one-finger))
|
||||
((or (= ra 2) (= rb 2))
|
||||
(if (or (and (= ra 2) (= rb 1) (index? a)) (and (= rb 2) (= ra 1) (index? b)))
|
||||
(record-ref p bottom-index)
|
||||
(record-ref p bottom-other)))
|
||||
(else (let ((top (if (= ra 0) a b))
|
||||
(home (if (= ra 0) b a)))
|
||||
(cond ((pinky? top) (record-ref p twist))
|
||||
((< (record-ref top finger) (record-ref home finger))
|
||||
(if (= ra 1) (record-ref p outward) (record-ref p inward)))
|
||||
(else (record-ref p twist)))))))
|
||||
|
||||
(: (-> Params Key Key double))
|
||||
(defun (adjacent-keys p a b)
|
||||
(* (record-ref p adjacent-keys) (roll-share p a b)
|
||||
(one-if (and (two-fingers? a b)
|
||||
(= (record-ref a row) (record-ref b row))
|
||||
(= (abs (- (record-ref a column) (record-ref b column))) 1)))))
|
||||
|
||||
(: (Vec Rule))
|
||||
(def rules
|
||||
[(Rule (name "stretch") (penalty stretch))
|
||||
(Rule (name "row motion") (penalty row-motion))
|
||||
(Rule (name "same finger") (penalty same-finger))
|
||||
(Rule (name "jump") (penalty jump))
|
||||
(Rule (name "easy jump") (penalty easy-jump))
|
||||
(Rule (name "close keys") (penalty close-keys))
|
||||
(Rule (name "adjacent keys") (penalty adjacent-keys))])
|
||||
|
||||
;; Whether the rules score the pair at all: one hand, two keys.
|
||||
(: (-> Key Key bool))
|
||||
(defun (scored-pair? a b)
|
||||
(and (= (record-ref a left?) (record-ref b left?))
|
||||
(not (= (record-ref a name) (record-ref b name)))))
|
||||
|
||||
;; What the rules charge for pressing `a` and then `b`: nothing for two hands
|
||||
;; or one key.
|
||||
(: (-> Params Key Key double))
|
||||
(defun (pair-penalty p a b)
|
||||
(if (scored-pair? a b)
|
||||
(vec-fold (fun (r t) (+ t ((record-ref r penalty) p a b))) 0.0 rules)
|
||||
0.0))
|
||||
|
||||
;; The hand-run rule for pressing `a`, `b` and then `c`: hand-run when all
|
||||
;; three are on one hand. On one row it is nothing, or the share of it
|
||||
;; low-share does not spare when a key is `low?`.
|
||||
(: (-> Params Key Key Key double))
|
||||
(defun (hand-run p a b c)
|
||||
(def left? (record-ref a left?))
|
||||
(def row (record-ref a row))
|
||||
(cond ((not (and (= (record-ref b left?) left?) (= (record-ref c left?) left?))) 0.0)
|
||||
((not (and (= (record-ref b row) row) (= (record-ref c row) row))) (record-ref p hand-run))
|
||||
((or (low? a) (low? b) (low? c)) (* (- 1.0 (record-ref p low-share)) (record-ref p hand-run)))
|
||||
(else 0.0)))
|
||||
|
||||
;; The same-finger-skip rule for `a`, `b` and then `c`: skip when one finger
|
||||
;; types `a` and `c` and they are two keys.
|
||||
(: (-> Params Key Key Key double))
|
||||
(defun (same-finger-skip p a b c)
|
||||
(if (and (= (record-ref a left?) (record-ref c left?))
|
||||
(= (record-ref a finger) (record-ref c finger))
|
||||
(not (= (record-ref a name) (record-ref c name))))
|
||||
(record-ref p skip)
|
||||
0.0))
|
||||
|
||||
;; The two-finger-run rule for `a`, `b` and then `c`: two-finger when all
|
||||
;; three are on one hand, typed by two fingers, and no key is pressed twice
|
||||
;; in a row.
|
||||
(: (-> Params Key Key Key double))
|
||||
(defun (two-finger-run p a b c)
|
||||
(def left? (record-ref a left?))
|
||||
(def fa (record-ref a finger))
|
||||
(def fb (record-ref b finger))
|
||||
(def fc (record-ref c finger))
|
||||
(if (and (= (record-ref b left?) left?) (= (record-ref c left?) left?)
|
||||
(not (= (record-ref a name) (record-ref b name)))
|
||||
(not (= (record-ref b name) (record-ref c name)))
|
||||
(not (and (= fa fb) (= fb fc)))
|
||||
(or (= fa fb) (= fb fc) (= fa fc)))
|
||||
(record-ref p two-finger)
|
||||
0.0))
|
||||
|
||||
;; What the triple rules charge for `a`, `b` and then `c`.
|
||||
(: (-> Params Key Key Key double))
|
||||
(defun (triple-penalty p a b c)
|
||||
(+ (hand-run p a b c) (same-finger-skip p a b c) (two-finger-run p a b c)))
|
||||
|
||||
;; --- scoring -------------------------------------------------------------------
|
||||
|
||||
;; A layout's score on one text. Every total is per key press.
|
||||
;;
|
||||
;; - position: the keys' costs.
|
||||
;; - top-vowels: the cost of vowels on the top row.
|
||||
;; - rules: each rule's share, in the order of `rules`.
|
||||
;; - runs: the hand-run rule's share. skips: the same-finger-skip rule's.
|
||||
;; two-fingers: the two-finger-run rule's.
|
||||
;; - pinkies: the pinky load's penalty, both pinkies together.
|
||||
;; - distance: the finger distance, in key widths. Its cost is distance times
|
||||
;; the distance parameter.
|
||||
;; - total: position, top-vowels, the rules, the triple rules, the pinky load
|
||||
;; and the distance's cost together. Lower is better.
|
||||
;; - home: the share of presses on the home row.
|
||||
;; - alternation: the share of pairs (with no space between) typed on two hands.
|
||||
;; - same-finger: the share of pairs typed by one finger on two keys.
|
||||
;; - run-share, skip-share, two-finger-share: the share of triples each triple
|
||||
;; rule charges.
|
||||
;; - left-hand: the left hand's share of the presses.
|
||||
;; - left-pinky, right-pinky: each pinky's share of the presses.
|
||||
(type (: Score (Record (: presses int)
|
||||
(: position double)
|
||||
(: top-vowels double)
|
||||
(: rules (Vec double))
|
||||
(: runs double)
|
||||
(: skips double)
|
||||
(: two-fingers double)
|
||||
(: pinkies double)
|
||||
(: distance double)
|
||||
(: total double)
|
||||
(: home double)
|
||||
(: alternation double)
|
||||
(: same-finger double)
|
||||
(: run-share double)
|
||||
(: skip-share double)
|
||||
(: two-finger-share double)
|
||||
(: left-hand double)
|
||||
(: left-pinky double)
|
||||
(: right-pinky double))))
|
||||
|
||||
;; The sum of `f` over the pairs of `m`, each weighted by its count.
|
||||
(: (-> (MutableMap (Tuple char char) int) (-> char char double) double))
|
||||
(defun (pair-sum m f)
|
||||
(loop (:for (Tuple pair n) m)
|
||||
(:let (Tuple a b) pair)
|
||||
(:acc t (summing (* (cast double n) (f a b))))))
|
||||
|
||||
;; `layout` scored on `counts` with `p`. Every character counted must be on
|
||||
;; the layout.
|
||||
(: (-> Params Layout Counts Score))
|
||||
(defun (score-layout p layout counts)
|
||||
(def (: key (-> char Key)) (fun (c) (option-ref (layout-key layout c))))
|
||||
(def presses (record-ref counts presses))
|
||||
(def pairs (record-ref counts pairs))
|
||||
(def spaced (record-ref counts spaced))
|
||||
(def n (loop (:for (Tuple _ k) presses) (:acc t (summing k))))
|
||||
(def per-press (fun (x) (/ x (cast double n))))
|
||||
(: press-sum (-> (-> char Key double) double))
|
||||
(def press-sum
|
||||
(fun (f) (loop (:for (Tuple c k) presses)
|
||||
(:acc t (summing (* (cast double k) (f c (key c))))))))
|
||||
(def position (per-press (press-sum (fun (c k) (key-cost p k)))))
|
||||
(def top-vowels (per-press (press-sum (fun (c k) (top-vowel p c k)))))
|
||||
(def rule-totals
|
||||
(->vec (map (fun (r)
|
||||
(def f (fun (a b)
|
||||
(def ka (key a))
|
||||
(def kb (key b))
|
||||
(if (scored-pair? ka kb)
|
||||
((record-ref r penalty) p ka kb)
|
||||
0.0)))
|
||||
(per-press (+ (pair-sum pairs f) (* (record-ref p spaced) (pair-sum spaced f)))))
|
||||
rules)))
|
||||
(: press-share (-> (-> Key bool) double))
|
||||
(def press-share
|
||||
(fun (f) (/ (loop (:for (Tuple c k) presses)
|
||||
(:acc t (summing (if (f (key c)) (cast double k) 0.0))))
|
||||
(cast double n))))
|
||||
(def left-pinky (press-share (fun (k) (and (record-ref k left?) (= (record-ref k finger) 0)))))
|
||||
(def right-pinky (press-share (fun (k) (and (not (record-ref k left?)) (= (record-ref k finger) 0)))))
|
||||
(def pinkies (+ (pinky-penalty p left-pinky) (pinky-penalty p right-pinky)))
|
||||
(def distance
|
||||
(per-press (+ (press-sum (fun (c k) (home-travel k)))
|
||||
(pair-sum pairs (fun (a b) (pair-travel (key a) (key b)))))))
|
||||
(: triple-sum (-> (-> Key Key Key double) double))
|
||||
(def triple-sum
|
||||
(fun (f) (loop (:for (Tuple t k) (record-ref counts triples))
|
||||
(:let (Tuple a b c) t)
|
||||
(:acc s (summing (* (cast double k) (f (key a) (key b) (key c))))))))
|
||||
(def runs (per-press (triple-sum (fun (a b c) (hand-run p a b c)))))
|
||||
(def skips (per-press (triple-sum (fun (a b c) (same-finger-skip p a b c)))))
|
||||
(def two-fingers (per-press (triple-sum (fun (a b c) (two-finger-run p a b c)))))
|
||||
(def triple-count (triple-sum (fun (a b c) 1.0)))
|
||||
(def pair-count (pair-sum pairs (fun (a b) 1.0)))
|
||||
(def share
|
||||
(fun (f) (/ (pair-sum pairs (fun (a b) (if (f (key a) (key b)) 1.0 0.0))) pair-count)))
|
||||
(Score (presses n)
|
||||
(position position)
|
||||
(top-vowels top-vowels)
|
||||
(rules rule-totals)
|
||||
(runs runs)
|
||||
(skips skips)
|
||||
(two-fingers two-fingers)
|
||||
(pinkies pinkies)
|
||||
(distance distance)
|
||||
(total (+ position top-vowels (vec-fold (fun (x y) (+ x y)) 0.0 rule-totals) runs skips
|
||||
two-fingers pinkies (* (record-ref p distance) distance)))
|
||||
(home (press-share (fun (k) (= (record-ref k row) 1))))
|
||||
(left-pinky left-pinky)
|
||||
(right-pinky right-pinky)
|
||||
(alternation (share (fun (a b) (not (= (record-ref a left?) (record-ref b left?))))))
|
||||
(same-finger (share (fun (a b) (and (scored-pair? a b) (not (two-fingers? a b))))))
|
||||
(run-share (/ (triple-sum (fun (a b c) (if (> (hand-run p a b c) 0.0) 1.0 0.0))) triple-count))
|
||||
(skip-share (/ (triple-sum (fun (a b c) (if (> (same-finger-skip p a b c) 0.0) 1.0 0.0))) triple-count))
|
||||
(two-finger-share (/ (triple-sum (fun (a b c) (if (> (two-finger-run p a b c) 0.0) 1.0 0.0))) triple-count))
|
||||
(left-hand (press-share (fun (k) (record-ref k left?))))))
|
||||
|
||||
;; The score of each pair, per key press: what the pair costs `layout` on
|
||||
;; `counts`, by every rule. A pair with spaces between is written "a b".
|
||||
(: (-> Params Layout Counts (List (Tuple string double))))
|
||||
(defun (pair-costs p layout counts)
|
||||
(def (: key (-> char Key)) (fun (c) (option-ref (layout-key layout c))))
|
||||
(def n (cast double (loop (:for (Tuple _ k) (record-ref counts presses)) (:acc t (summing k)))))
|
||||
(: cost (-> char char double))
|
||||
(def cost (fun (a b) (pair-penalty p (key a) (key b))))
|
||||
(: each (-> (MutableMap (Tuple char char) int) string double (List (Tuple string double))))
|
||||
(def each (fun (m between weight)
|
||||
(loop (:for (Tuple pair k) m)
|
||||
(:let (Tuple a b) pair)
|
||||
(:acc out (listing (Tuple (str (char->string a) between (char->string b))
|
||||
(/ (* weight (cast double k) (cost a b)) n)))))))
|
||||
(list-append (each (record-ref counts pairs) "" 1.0)
|
||||
(each (record-ref counts spaced) " " (record-ref p spaced))))
|
||||
350
src/search.bjo
Normal file
350
src/search.bjo
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
;; Searching for a better layout by simulated annealing.
|
||||
;;
|
||||
;; - A unit is a key's character together with its shifted one (, and ;).
|
||||
;; A step swaps the keys of two units. The layout's set of keys stays.
|
||||
;; - The score is (keyscore score)'s with the given `Params`: the weighted
|
||||
;; mean over the texts that weigh something, lower being better.
|
||||
;; - A worse layout is taken with the probability exp(-d / T), where d is how
|
||||
;; much worse it is. T falls geometrically from t-start to `t-end`. A low
|
||||
;; t-start refines the start layout rather than replacing it.
|
||||
;; - The runs run in parallel, on the compute threads of (std parallel).
|
||||
;;
|
||||
;; The scorer here is the full one precomputed: the cost of every unit on
|
||||
;; every key, the penalty of every pair and triple of keys, and the presses,
|
||||
;; pairs and triples of every unit. `check-problem` compares the two.
|
||||
;;
|
||||
;; Errors:
|
||||
;; - `search` raises when vowels-left is asked for and the start layout has
|
||||
;; a vowel on the right hand.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std maths))
|
||||
(import (std random))
|
||||
(import (std mutable map))
|
||||
(import (std parallel))
|
||||
(import (keyscore board))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore score))
|
||||
(import (keyscore texts))
|
||||
|
||||
(export Options Found default-options t-end Problem Text problem-of problem-score
|
||||
mean-score search)
|
||||
|
||||
(: double)
|
||||
(def t-end 0.001)
|
||||
|
||||
;; How to search.
|
||||
;;
|
||||
;; - runs: independent searches, each with its own seed.
|
||||
;; - steps: swaps tried per run.
|
||||
;; - t-start: the starting temperature.
|
||||
;; - vowels-left: the vowels (a e i o u y å ä ö) stay on left-hand keys: a
|
||||
;; swap that would move one to the right hand is not tried.
|
||||
;; - fixed: the characters whose keys do not move, written as in a layout.
|
||||
(type (: Options (Record (: runs int)
|
||||
(: steps int)
|
||||
(: t-start double)
|
||||
(: vowels-left bool)
|
||||
(: fixed string))))
|
||||
|
||||
(: Options)
|
||||
(def default-options
|
||||
(Options (runs 8) (steps 200000) (t-start 0.02) (vowels-left #f) (fixed "")))
|
||||
|
||||
;; A run's best layout: its score by the search's scorer, and its rows, as
|
||||
;; `aligned-rows` writes them.
|
||||
(type (: Found (Record (: score double) (: rows (Vec string)))))
|
||||
|
||||
;; A text, by unit: its weight in the mean, presses, the pairs typed with
|
||||
;; their weights (a pair with spaces between weighs `spaced`) and their
|
||||
;; counts with no space between, and the triples with their counts.
|
||||
(type (: Text (Record (: share double)
|
||||
(: presses double)
|
||||
(: units (Array double))
|
||||
(: first (Array int))
|
||||
(: second (Array int))
|
||||
(: weight (Array double))
|
||||
(: plain (Array double))
|
||||
(: triple-a (Array int))
|
||||
(: triple-b (Array int))
|
||||
(: triple-c (Array int))
|
||||
(: triple-count (Array double)))))
|
||||
|
||||
;; What the search needs.
|
||||
;;
|
||||
;; - params: what it scores with.
|
||||
;; - layout: the start layout. chars: each unit's character, as its rows
|
||||
;; write it. start: each unit's key, by index in `board`, at the start.
|
||||
;; - costs: what a press of each unit costs on each key, at [u * keys + k]:
|
||||
;; the key's cost, `top-vowel` and the travel from home.
|
||||
;; - penalties: the penalty of each pair of keys, at [a * keys + b].
|
||||
;; travels: the distance cost of each pair with no space between, by
|
||||
;; `pair-travel`. triple-penalties: of each triple, at
|
||||
;; [(a * keys + b) * keys + c].
|
||||
;; - left-pinky, right-pinky: whether each key is typed by that pinky.
|
||||
;; - left-keys: whether each key is on the left hand.
|
||||
(type (: Problem (Record (: params Params)
|
||||
(: layout Layout)
|
||||
(: chars (Vec char))
|
||||
(: start (Array int))
|
||||
(: keys int)
|
||||
(: costs (Array double))
|
||||
(: penalties (Array double))
|
||||
(: travels (Array double))
|
||||
(: triple-penalties (Array double))
|
||||
(: left-pinky (Array bool))
|
||||
(: right-pinky (Array bool))
|
||||
(: left-keys (Array bool))
|
||||
(: texts (Vec Text)))))
|
||||
|
||||
(: (-> Layout char int))
|
||||
(defun (key-of l c) (record-ref (option-ref (layout-key l c)) index))
|
||||
|
||||
;; `counts` by unit. `unit-of` is the unit of each character counted.
|
||||
(: (-> Params Counts double (Map char int) int Text))
|
||||
(defun (text-of params counts share unit-of units)
|
||||
(def (: presses (Array double)) (make-array units #:fill 0.0))
|
||||
(loop (:for (Tuple c k) (record-ref counts presses))
|
||||
(:let u (map-ref unit-of c))
|
||||
(:do (array-set! presses u (+ (array-ref presses u) (cast double k)))))
|
||||
;; Each pair of units: its weight, and its count with no space between.
|
||||
(def (: pairs (MutableMap (Tuple int int) (Tuple double double))) (mutablemap))
|
||||
(: add! (-> (MutableMap (Tuple char char) int) double double void))
|
||||
(def add! (fun (m weight plain)
|
||||
(loop (:for (Tuple pair k) m)
|
||||
(:let (Tuple a b) pair)
|
||||
(:let n (cast double k))
|
||||
(:do (mutablemap-update! pairs (Tuple (map-ref unit-of a) (map-ref unit-of b))
|
||||
(fun (w) (Tuple (+ (fst w) (* weight n)) (+ (snd w) (* plain n))))
|
||||
#:default (Some (Tuple 0.0 0.0)))))))
|
||||
(add! (record-ref counts pairs) 1.0 1.0)
|
||||
(add! (record-ref counts spaced) (record-ref params spaced) 0.0)
|
||||
(def entries (->vec pairs))
|
||||
(def (: triples (MutableMap (Tuple int int int) double)) (mutablemap))
|
||||
(loop (:for (Tuple t k) (record-ref counts triples))
|
||||
(:let (Tuple a b c) t)
|
||||
(:do (mutablemap-update! triples (Tuple (map-ref unit-of a) (map-ref unit-of b) (map-ref unit-of c))
|
||||
(fun (w) (+ w (cast double k)))
|
||||
#:default (Some 0.0))))
|
||||
(def (: tris (Vec (Tuple (Tuple int int int) double))) (->vec triples))
|
||||
(: tri-unit (-> int (Array int)))
|
||||
(def tri-unit (fun (i) (vec->array (vec-map (fun (e) (def (Tuple a b c) (fst e))
|
||||
(if (= i 0) a (if (= i 1) b c)))
|
||||
tris))))
|
||||
(Text (share share)
|
||||
(presses (loop (:for i (range 0 units)) (:acc t (summing (array-ref presses i)))))
|
||||
(units presses)
|
||||
(first (vec->array (vec-map (fun (e) (fst (fst e))) entries)))
|
||||
(second (vec->array (vec-map (fun (e) (snd (fst e))) entries)))
|
||||
(weight (vec->array (vec-map (fun (e) (fst (snd e))) entries)))
|
||||
(plain (vec->array (vec-map (fun (e) (snd (snd e))) entries)))
|
||||
(triple-a (tri-unit 0))
|
||||
(triple-b (tri-unit 1))
|
||||
(triple-c (tri-unit 2))
|
||||
(triple-count (vec->array (vec-map (fun (e) (snd e)) tris)))))
|
||||
|
||||
;; An array of `n` * `n` doubles, `f` of the keys a and b at [a * n + b].
|
||||
(: (-> (-> Key Key double) (Array double)))
|
||||
(defun (pair-table f)
|
||||
(def n (vec-length board))
|
||||
(def (: out (Array double)) (make-array (* n n) #:fill 0.0))
|
||||
(loop (:for a board) (:for i (range 0 n))
|
||||
(:let row-start (* i n))
|
||||
(:for b board) (:for j (range 0 n))
|
||||
(:do (array-set! out (+ row-start j) (f a b))))
|
||||
out)
|
||||
|
||||
;; The problem of improving `l` with `params`. `counts` are the counts of the
|
||||
;; texts of `params`, in their order; those that weigh nothing are left out.
|
||||
(: (-> Params Layout (Vec Counts) Problem))
|
||||
(defun (problem-of params l counts)
|
||||
(def chars (list->vec (layout-base-chars l)))
|
||||
(def units (vec-length chars))
|
||||
;; Each key the layout uses holds one unit; every character counted is on
|
||||
;; one of those keys.
|
||||
(def unit-on-key (loop (:for c chars) (:for u (range 0 units))
|
||||
(:acc out (mapping (Tuple (key-of l c) u)))))
|
||||
(def unit-of (loop (:for c (common-chars layouts))
|
||||
(:acc out (mapping (Tuple c (map-ref unit-on-key (key-of l c)))))))
|
||||
(def n (vec-length board))
|
||||
(def distance (record-ref params distance))
|
||||
(def (: costs (Array double)) (make-array (* units n) #:fill 0.0))
|
||||
(loop (:for c chars) (:for u (range 0 units))
|
||||
(:let row-start (* u n))
|
||||
(:let base (normalize c))
|
||||
(:for k board) (:for j (range 0 n))
|
||||
(:do (array-set! costs (+ row-start j)
|
||||
(+ (key-cost params k) (top-vowel params base k) (* distance (home-travel k))))))
|
||||
(def (: triple-penalties (Array double)) (make-array (* n n n) #:fill 0.0))
|
||||
(loop (:for a board) (:for i (range 0 n))
|
||||
(:let ab-start i)
|
||||
(:for b board) (:for j (range 0 n))
|
||||
(:let c-start (* (+ (* ab-start n) j) n))
|
||||
(:for c board) (:for k (range 0 n))
|
||||
(:do (array-set! triple-penalties (+ c-start k) (triple-penalty params a b c))))
|
||||
(: pinky? (-> bool Key bool))
|
||||
(def pinky? (fun (left k) (and (= (record-ref k finger) 0) (= (record-ref k left?) left))))
|
||||
(def corpora (record-ref params corpora))
|
||||
(def total (vec-fold (fun (c t) (+ t (corpus-weight c))) 0.0 corpora))
|
||||
(Problem (params params)
|
||||
(layout l)
|
||||
(chars chars)
|
||||
(start (vec->array (vec-map (fun (c) (key-of l c)) chars)))
|
||||
(keys n)
|
||||
(costs costs)
|
||||
(penalties (pair-table (fun (a b) (pair-penalty params a b))))
|
||||
(travels (pair-table (fun (a b) (* distance (pair-travel a b)))))
|
||||
(triple-penalties triple-penalties)
|
||||
(left-pinky (vec->array (vec-map (fun (k) (pinky? #t k)) board)))
|
||||
(right-pinky (vec->array (vec-map (fun (k) (pinky? #f k)) board)))
|
||||
(left-keys (vec->array (vec-map (fun (k) (record-ref k left?)) board)))
|
||||
(texts (loop (:for cs counts) (:for c corpora)
|
||||
(:when (> (corpus-weight c) 0.0))
|
||||
(:acc out (vecing (text-of params cs (/ (corpus-weight c) total) unit-of units)))))))
|
||||
|
||||
;; The score of the layout that puts unit u on key (array-ref on u).
|
||||
(: (-> Problem (Array int) double))
|
||||
(defun (score p on)
|
||||
(def units (array-length on))
|
||||
(def n (record-ref p keys))
|
||||
(def costs (record-ref p costs))
|
||||
(def penalties (record-ref p penalties))
|
||||
(def travels (record-ref p travels))
|
||||
(def tpen (record-ref p triple-penalties))
|
||||
(def left (record-ref p left-pinky))
|
||||
(def right (record-ref p right-pinky))
|
||||
(def params (record-ref p params))
|
||||
(: one (-> Text double))
|
||||
(def one
|
||||
(fun (t)
|
||||
(def presses (record-ref t units))
|
||||
(def first (record-ref t first))
|
||||
(def second (record-ref t second))
|
||||
(def weight (record-ref t weight))
|
||||
(def plain (record-ref t plain))
|
||||
(def total (record-ref t presses))
|
||||
(def keys-cost
|
||||
(loop (:for u (range 0 units))
|
||||
(:acc s (summing (* (array-ref presses u) (array-ref costs (+ (* u n) (array-ref on u))))))))
|
||||
(def pairs-cost
|
||||
(loop (:for i (range 0 (array-length first)))
|
||||
(:let at (+ (* (array-ref on (array-ref first i)) n) (array-ref on (array-ref second i))))
|
||||
(:acc s (summing (+ (* (array-ref weight i) (array-ref penalties at))
|
||||
(* (array-ref plain i) (array-ref travels at)))))))
|
||||
(def ta (record-ref t triple-a))
|
||||
(def tb (record-ref t triple-b))
|
||||
(def tc (record-ref t triple-c))
|
||||
(def tn (record-ref t triple-count))
|
||||
(def triples-cost
|
||||
(loop (:for i (range 0 (array-length ta)))
|
||||
(:acc s (summing (* (array-ref tn i)
|
||||
(array-ref tpen (+ (* (+ (* (array-ref on (array-ref ta i)) n)
|
||||
(array-ref on (array-ref tb i)))
|
||||
n)
|
||||
(array-ref on (array-ref tc i)))))))))
|
||||
(: share (-> (Array bool) double))
|
||||
(def share (fun (pinky)
|
||||
(/ (loop (:for u (range 0 units))
|
||||
(:acc s (summing (if (array-ref pinky (array-ref on u)) (array-ref presses u) 0.0))))
|
||||
total)))
|
||||
(+ (/ (+ keys-cost pairs-cost triples-cost) total)
|
||||
(pinky-penalty params (share left)) (pinky-penalty params (share right)))))
|
||||
(def ts (record-ref p texts))
|
||||
(vec-fold (fun (t s) (+ s (* (record-ref t share) (one t)))) 0.0 ts))
|
||||
|
||||
;; The start layout's score by the search's scorer.
|
||||
(: (-> Problem double))
|
||||
(defun (problem-score p) (score p (record-ref p start)))
|
||||
|
||||
;; `l`'s score by the full scorer with `params`: the weighted mean of its
|
||||
;; totals on `counts`, the counts of the texts of `params` in their order.
|
||||
(: (-> Params Layout (Vec Counts) double))
|
||||
(defun (mean-score params l counts)
|
||||
(weighted-mean (record-ref params corpora)
|
||||
(vec-map (fun (c) (record-ref (score-layout params l c) total)) counts)))
|
||||
|
||||
(: (-> (Array int) (Array int)))
|
||||
(defun (copy a)
|
||||
(def (: out (Array int)) (make-array (array-length a) #:fill 0))
|
||||
(array-copy! a 0 out 0 (array-length a))
|
||||
out)
|
||||
|
||||
;; The units whose character is in `cs`, compared after `normalize`.
|
||||
(: (-> Problem string (Array bool)))
|
||||
(defun (units-in p cs)
|
||||
(def wanted (->list (map normalize cs)))
|
||||
(vec->array (vec-map (fun (c) (any? (fun (f) (char=? f (normalize c))) wanted))
|
||||
(record-ref p chars))))
|
||||
|
||||
;; One run: the best layout it found, and its score. A unit marked in
|
||||
;; `locked` never leaves the left hand; one marked in `fixed` never moves.
|
||||
(: (-> Problem int int double (Array bool) (Array bool) (Tuple double (Array int))))
|
||||
(defun (anneal p seed steps t-start locked fixed)
|
||||
(def left (record-ref p left-keys))
|
||||
(def rng (make-random/seed64 (cast ulong seed)))
|
||||
(def on (copy (record-ref p start)))
|
||||
(def units (array-length on))
|
||||
(def current (make-box (score p on)))
|
||||
(def best (make-box (Tuple (box-ref current) (copy on))))
|
||||
(def cooling (/ (loge (/ t-end t-start)) (cast double steps)))
|
||||
(loop (:for i (range 0 steps))
|
||||
(:let temperature (* t-start (exp (* cooling (cast double i)))))
|
||||
(:let u (random-int 0 (- units 1) #:rng rng))
|
||||
(:let v (random-int 0 (- units 2) #:rng rng))
|
||||
(:let w (if (>= v u) (+ v 1) v))
|
||||
(:when (not (or (array-ref fixed u) (array-ref fixed w)
|
||||
(and (array-ref locked u) (not (array-ref left (array-ref on w))))
|
||||
(and (array-ref locked w) (not (array-ref left (array-ref on u)))))))
|
||||
(:do (def ku (array-ref on u))
|
||||
(array-set! on u (array-ref on w))
|
||||
(array-set! on w ku)
|
||||
(def s (score p on))
|
||||
(def d (- s (box-ref current)))
|
||||
(if (or (<= d 0.0) (< (random-double #:rng rng) (exp (- (/ d temperature)))))
|
||||
(begin
|
||||
(box-set! current s)
|
||||
(when (< s (fst (box-ref best)))
|
||||
(box-set! best (Tuple s (copy on)))))
|
||||
(begin
|
||||
(array-set! on w (array-ref on u))
|
||||
(array-set! on u ku)))))
|
||||
(box-ref best))
|
||||
|
||||
;; The rows of the start layout, with each unit on the key `on` gives it, as
|
||||
;; `aligned-rows` writes them. Letters are upper case and ' is ’, as layouts
|
||||
;; are written.
|
||||
(: (-> Problem (Array int) (Vec string)))
|
||||
(defun (rows-of p on)
|
||||
(def chars (record-ref p chars))
|
||||
(def (: on-key (Array char)) (make-array (record-ref p keys) #:fill #\space))
|
||||
(loop (:for u (range 0 (array-length on)))
|
||||
(:do (array-set! on-key (array-ref on u) (vec-ref chars u))))
|
||||
(def start (record-ref p start))
|
||||
(def unit-of (loop (:for c chars) (:for u (range 0 (vec-length chars)))
|
||||
(:acc out (mapping (Tuple c u)))))
|
||||
(: shown (-> char char))
|
||||
(def shown (fun (c)
|
||||
(if (char=? c #\space)
|
||||
c
|
||||
(let ((x (array-ref on-key (array-ref start (map-ref unit-of (normalize c))))))
|
||||
(if (char=? x #\') (int->char 0x2019) (char-upcase x))))))
|
||||
(aligned-rows (vec-map (fun (r) (list->string (->list (map shown r))))
|
||||
(record-ref (record-ref p layout) rows))))
|
||||
|
||||
;; The best layout of each of the runs `o` asks for, from the start layout of
|
||||
;; `p`, in run order. Raises when vowels-left is asked for and a vowel of the
|
||||
;; start layout is on the right hand.
|
||||
(: (-> Problem Options (Vec Found)))
|
||||
(defun (search p o)
|
||||
(def locked (units-in p (if (record-ref o vowels-left) "aeiouyåäö" "")))
|
||||
(def fixed (units-in p (record-ref o fixed)))
|
||||
(when (loop (:for u (range 0 (array-length locked)))
|
||||
(:acc any (oring (and (array-ref locked u)
|
||||
(not (array-ref (record-ref p left-keys)
|
||||
(array-ref (record-ref p start) u)))))))
|
||||
(panic! "vowels-left: the start layout has a vowel on the right hand"))
|
||||
(def found (computing-each (record-ref o runs)
|
||||
(fun (k) (anneal p (+ k 1) (record-ref o steps) (record-ref o t-start)
|
||||
locked fixed))))
|
||||
(vec-map (fun (f) (Found (score (fst f)) (rows (rows-of p (snd f))))) found))
|
||||
67
src/swaps.bjo
Normal file
67
src/swaps.bjo
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
;; Tries swapping one key of a layout with each of its other keys.
|
||||
;;
|
||||
;; bjo run src/swaps.bjo [char] [layout]
|
||||
;;
|
||||
;; - char: the character to move. i unless given.
|
||||
;; - layout: a layout's name in (keyscore layouts). The last one unless given.
|
||||
;; - Scores each swap on the texts of (keyscore texts) and prints them best
|
||||
;; first, by the weighted mean, the layout as it is among them. Lower is
|
||||
;; better.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std fmt))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore score))
|
||||
(import (keyscore texts))
|
||||
|
||||
;; The numbers scored with: params.txt when there is one.
|
||||
(: Params)
|
||||
(def params (current-params))
|
||||
|
||||
;; A layout's score on each text.
|
||||
(: (-> (Vec Counts) Layout (Vec double)))
|
||||
(defun (totals counts l) (vec-map (fun (c) (record-ref (score-layout params l c) total)) counts))
|
||||
|
||||
(: (-> (Vec double) double))
|
||||
(defun (mean xs) (weighted-mean (record-ref params corpora) xs))
|
||||
|
||||
|
||||
(: (-> double Block))
|
||||
(defun (fixed x) (numeric x #:precision 2))
|
||||
|
||||
;; The layout named `name`. Raises if there is none.
|
||||
(: (-> string Layout))
|
||||
(defun (layout-named name)
|
||||
(: named? (-> Layout bool))
|
||||
(def named? (fun (l) (= (record-ref l name) name)))
|
||||
(match (find named? layouts)
|
||||
((Some l) l)
|
||||
(None (panic! (str "no layout is named " name)))))
|
||||
|
||||
(defun (main args)
|
||||
(def moved (if (> (length args) 0) (normalize (option-ref (first (ref args 0)))) #\i))
|
||||
(def base (if (> (length args) 1)
|
||||
(layout-named (ref args 1))
|
||||
(vec-ref layouts (- (vec-length layouts) 1))))
|
||||
(def counts (count-files layouts (vec-map (fun (c) (record-ref c path)) (record-ref params corpora))))
|
||||
(def variants
|
||||
(cons (Tuple "as it is" base)
|
||||
(->list (map (fun (c)
|
||||
(Tuple (str (char->string moved) " <-> " (char->string c))
|
||||
(swap-keys base "" moved c)))
|
||||
(filter (fun (c) (not (char=? c moved))) (layout-base-chars base))))))
|
||||
(def scored
|
||||
(vec-sort-by (fun (a b) (compare (mean (snd a)) (mean (snd b))))
|
||||
(->vec (map (fun (v) (Tuple (fst v) (totals counts (snd v)))) variants))))
|
||||
(show [(record-ref base name) ", with " (char->string moved) " swapped with each other key." nl])
|
||||
(show (tabular/rows
|
||||
(->vec (map (fun (s)
|
||||
(: cells (Vec Block))
|
||||
(def cells (vec-append (vec-append [(BStr (fst s))] (vec-map fixed (snd s)))
|
||||
[(fixed (mean (snd s)))]))
|
||||
cells)
|
||||
scored))
|
||||
#:titles ["swap" "sv" "en" "bjolang" "mean"]
|
||||
#:sep " " #:align [AlignLeft AlignRight AlignRight AlignRight AlignRight]))
|
||||
0)
|
||||
43
src/texts.bjo
Normal file
43
src/texts.bjo
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
;; The texts the programs score on, and their weights in the mean.
|
||||
;;
|
||||
;; - sv.txt and en.txt weigh the same: half of what is written is English.
|
||||
;; - bjolang.txt weighs nothing. It is shown, as a curiosity, but it is not in
|
||||
;; the mean, and the optimizer leaves it out.
|
||||
|
||||
(import (std prelude))
|
||||
|
||||
(export Corpus corpus corpus-path corpus-weight default-corpora weighted-mean weights-text)
|
||||
|
||||
(type (: Corpus (Record (: path string) (: weight double))))
|
||||
|
||||
(: (-> string double Corpus))
|
||||
(defun (corpus path weight) (Corpus (path path) (weight weight)))
|
||||
|
||||
(: (-> Corpus string))
|
||||
(defun (corpus-path c) (record-ref c path))
|
||||
|
||||
(: (-> Corpus double))
|
||||
(defun (corpus-weight c) (record-ref c weight))
|
||||
|
||||
(: (Vec Corpus))
|
||||
(def default-corpora
|
||||
[(corpus "corpus/sv.txt" 1.0)
|
||||
(corpus "corpus/en.txt" 1.0)
|
||||
(corpus "corpus/bjolang.txt" 0.0)])
|
||||
|
||||
;; The mean of `xs`, one for each of `cs`, weighted by the corpora's weights.
|
||||
;; Raises if no corpus weighs anything.
|
||||
(: (-> (Vec Corpus) (Vec double) double))
|
||||
(defun (weighted-mean cs xs)
|
||||
(def total (vec-fold (fun (c t) (+ t (record-ref c weight))) 0.0 cs))
|
||||
(when (<= total 0.0) (panic! "no text weighs anything"))
|
||||
(/ (loop (:for c cs) (:for x xs) (:acc t (summing (* (record-ref c weight) x))))
|
||||
total))
|
||||
|
||||
;; The weights, for a report: "sv.txt 1, en.txt 1, bjolang.txt 0".
|
||||
(: (-> (Vec Corpus) string))
|
||||
(defun (weights-text cs)
|
||||
(string-join (vec-map (fun (c) (str (option-ref-or (path-filename (record-ref c path)) (record-ref c path))
|
||||
" " (displayed (record-ref c weight))))
|
||||
cs)
|
||||
", "))
|
||||
91
src/word.bjo
Normal file
91
src/word.bjo
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
;; What a word costs a layout, pair by pair and triple by triple.
|
||||
;;
|
||||
;; bjo run src/word.bjo word [layout]
|
||||
;;
|
||||
;; - layout: by name, the last in (keyscore layouts) unless given.
|
||||
;; - Prints each pair's penalty by rule, each triple's hand-run and
|
||||
;; same-finger-skip penalties, and how often the corpora type each, per
|
||||
;; million key presses.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std maths))
|
||||
(import (std mutable map))
|
||||
(import (only (std fmt) numeric render->string))
|
||||
(import (keyscore board))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore score))
|
||||
(import (keyscore texts))
|
||||
|
||||
;; The key's name, its hand and its finger: "i R middle top".
|
||||
(: (-> Key string))
|
||||
(defun (where k)
|
||||
(def fingers ["pinky" "ring" "middle" "index"])
|
||||
(def rows ["top" "home" "bottom"])
|
||||
(str (record-ref k name) " " (if (record-ref k left?) "L" "R") " "
|
||||
(vec-ref fingers (record-ref k finger)) " " (vec-ref rows (record-ref k row))))
|
||||
|
||||
(: (-> Counts int))
|
||||
(defun (presses-of c) (loop (:for (Tuple _ n) (record-ref c presses)) (:acc t (summing n))))
|
||||
|
||||
(: (-> Counts (Tuple char char) int))
|
||||
(defun (pair-count c p) (option-ref-or (mutablemap-try-ref (record-ref c pairs) p) 0))
|
||||
|
||||
(: (-> Counts (Tuple char char char) int))
|
||||
(defun (triple-count c t) (option-ref-or (mutablemap-try-ref (record-ref c triples) t) 0))
|
||||
|
||||
;; n per million presses of c.
|
||||
(: (-> int Counts string))
|
||||
(defun (per-million n c)
|
||||
(displayed (cast long (/ (* 1000000.0 (cast double n)) (cast double (presses-of c))))))
|
||||
|
||||
(: (-> double string))
|
||||
(defun (num x)
|
||||
(if (= x (floor x)) (displayed (cast long x)) (render->string (numeric x #:precision 2))))
|
||||
|
||||
(defun (main args)
|
||||
(def params (current-params))
|
||||
(def word (->list (map normalize (ref args 0))))
|
||||
(: named? (-> Layout bool))
|
||||
(def named? (fun (l) (= (record-ref l name) (ref args 1))))
|
||||
(def l (if (> (length args) 1)
|
||||
(option-ref (find named? layouts))
|
||||
(vec-ref layouts (- (vec-length layouts) 1))))
|
||||
(def (: key (-> char Key)) (fun (c) (option-ref (layout-key l c))))
|
||||
(def corpora (->vec (filter (fun (c) (> (corpus-weight c) 0.0)) (record-ref params corpora))))
|
||||
(def counts (count-files layouts (vec-map corpus-path corpora)))
|
||||
(def names (string-join (vec-map (fun (c) (option-ref-or (path-filename (corpus-path c)) "")) corpora) ", "))
|
||||
(when (file-exists? params-file) (println (str "Parameters from " params-file ".")))
|
||||
(println (str (record-ref l name) ": " (list->string word)))
|
||||
(loop (:for c word)
|
||||
(:let v (top-vowel params c (key c)))
|
||||
(:do (println (str " " (char->string c) " " (where (key c))
|
||||
" travel " (num (home-travel (key c)))
|
||||
(if (> v 0.0) (str " (top-row vowel " (num v) ")") "")))))
|
||||
(println "")
|
||||
(println (str "Pairs (per million presses in " names "):"))
|
||||
(loop (:for a word) (:for b (list-tail word))
|
||||
(:let ka (key a))
|
||||
(:let kb (key b))
|
||||
(:let parts (loop (:for r rules)
|
||||
(:let p ((record-ref r penalty) params ka kb))
|
||||
(:when (and (not (= p 0.0)) (= (record-ref ka left?) (record-ref kb left?))
|
||||
(not (= (record-ref ka name) (record-ref kb name)))))
|
||||
(:acc out (listing (str (record-ref r name) " " (num p))))))
|
||||
(:let travel (pair-travel ka kb))
|
||||
(:do (println (str " " (char->string a) (char->string b) " " (num (pair-penalty params ka kb))
|
||||
(if (list-empty? parts) "" (str " (" (string-join (list->vec parts) ", ") ")"))
|
||||
(if (= travel 0.0) "" (str " travel " (num travel) " from home"))
|
||||
" typed " (string-join (vec-map (fun (c) (per-million (pair-count c (Tuple a b)) c)) counts) " / ")))))
|
||||
(println "")
|
||||
(println "Triples:")
|
||||
(loop (:for a word) (:for b (list-tail word)) (:for c (list-tail (list-tail word)))
|
||||
(:let ka (key a))
|
||||
(:let kb (key b))
|
||||
(:let kc (key c))
|
||||
(:do (println (str " " (char->string a) (char->string b) (char->string c)
|
||||
" hand run " (num (hand-run params ka kb kc))
|
||||
", same-finger skip " (num (same-finger-skip params ka kb kc))
|
||||
", two-finger run " (num (two-finger-run params ka kb kc))
|
||||
" typed " (string-join (vec-map (fun (x) (per-million (triple-count x (Tuple a b c)) x)) counts) " / ")))))
|
||||
0)
|
||||
176
tests/gui-shots.bjo
Normal file
176
tests/gui-shots.bjo
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
;; Pictures of the GUI's tabs, drawn with no screen.
|
||||
;;
|
||||
;; bjo run tests/gui-shots.bjo [folder]
|
||||
;;
|
||||
;; - Starts (keyscore gui) headless, waits until the texts are read and the
|
||||
;; layouts scored, and saves rules.png, key-costs.png, layout.png and
|
||||
;; search.png in `folder`, the current one unless given.
|
||||
;; - Changes a number first, and checks that the scores follow.
|
||||
;; - Then runs a short search, keeps a result, and saves searched.png.
|
||||
;; - Saves a preset, changes a number, and loads the preset back. Saves
|
||||
;; presets.png, then deletes the preset.
|
||||
;; - Saves a search result and the kept result as layouts, saves
|
||||
;; layout-saved.png, and removes both again.
|
||||
;; - Leaves no presets folder or saved-layouts.txt that was not there before.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std interop))
|
||||
(import (bjogui app))
|
||||
(import (keyscore gui))
|
||||
(import (keyscore layouts))
|
||||
(import (keyscore params))
|
||||
(import (keyscore saved))
|
||||
|
||||
(import/class
|
||||
(Object (: System.Object))
|
||||
(Window (: Avalonia.Controls.Window (-> Window)))
|
||||
(ContentControl (: Avalonia.Controls.ContentControl))
|
||||
(Control (: Avalonia.Controls.Control))
|
||||
(Layoutable (: Avalonia.Layout.Layoutable))
|
||||
(Visual (: Avalonia.Visual))
|
||||
(Size (: Avalonia.Size (-> double double Size)))
|
||||
(Rect (: Avalonia.Rect (-> double double double double Rect)))
|
||||
(PixelSize (: Avalonia.PixelSize (-> int int PixelSize)))
|
||||
(Vector (: Avalonia.Vector (-> double double Vector)))
|
||||
(RenderBitmap (: Avalonia.Media.Imaging.RenderTargetBitmap (-> PixelSize Vector RenderBitmap)))
|
||||
(Bitmap (: Avalonia.Media.Imaging.Bitmap))
|
||||
(Application (: Avalonia.Application))
|
||||
(Styles (: Avalonia.Styling.Styles)))
|
||||
|
||||
(import/extern
|
||||
(measure! (: Avalonia.Layout.Layoutable.Measure (-> Layoutable Size void)))
|
||||
(arrange! (: Avalonia.Layout.Layoutable.Arrange (-> Layoutable Rect void)))
|
||||
(render-into! (: Avalonia.Media.Imaging.RenderTargetBitmap.Render (-> RenderBitmap Visual void)))
|
||||
(save-png! (: Avalonia.Media.Imaging.Bitmap.Save (-> Bitmap string (System.Nullable int) void)))
|
||||
(sleep-ms (: System.Threading.Thread.Sleep (-> int void) #:blocking))
|
||||
(current-app (: Avalonia.Application.Current #:get))
|
||||
(content! (: Avalonia.Controls.ContentControl.Content (-> ContentControl Object void) #:set))
|
||||
(show! (: Avalonia.Controls.Window.Show (-> Window void)))
|
||||
(app-styles (: Avalonia.Application.Styles (-> Application Styles) #:get))
|
||||
(styles-add! (: Avalonia.Styling.Styles.Add (-> Styles IStyle void))))
|
||||
|
||||
;; What `control` shows, laid out at `w` by `h`, saved to `path` at twice the
|
||||
;; pixels.
|
||||
(: (-> Control int int string void))
|
||||
(defun (save-shot control w h path)
|
||||
(measure! (cast Layoutable control) (Size. (cast double w) (cast double h)))
|
||||
(arrange! (cast Layoutable control) (Rect. 0.0 0.0 (cast double w) (cast double h)))
|
||||
(def bitmap (RenderBitmap. (PixelSize. (* 2 w) (* 2 h)) (Vector. 192.0 192.0)))
|
||||
(render-into! bitmap (cast Visual control))
|
||||
(save-png! (cast Bitmap bitmap) path (: (clr-default) (System.Nullable int))))
|
||||
|
||||
;; The name of `l`.
|
||||
(: (-> Layout string))
|
||||
(defun (layout-name-of l) (record-ref l name))
|
||||
|
||||
(defun (main args)
|
||||
(def folder (if (> (vec-length args) 0) (vec-ref args 0) "."))
|
||||
(start-headless!)
|
||||
;; With no window there is no theme, and a control with a template draws nothing.
|
||||
(styles-add! (app-styles (cast Application current-app)) (fluent-theme))
|
||||
(def app (start-app initial gui-update view (fun (c) unit) #:subscriptions subscriptions))
|
||||
;; Runs what the fibers posted until `done?` holds, for two minutes at most.
|
||||
(: (-> (-> Model bool) bool))
|
||||
(defun (wait-for done?)
|
||||
(let go ((tries 0))
|
||||
(app-run-pending! app)
|
||||
(cond ((done? (app-model app)) #t)
|
||||
((> tries 12000) #f)
|
||||
(else (sleep-ms 10) (go (+ tries 1))))))
|
||||
(: scored? (-> Model bool))
|
||||
(def scored? (fun (m) (= (vec-length (.scores m)) (vec-length (.layouts m)))))
|
||||
(when (not (wait-for scored?)) (panic! "the layouts were not scored"))
|
||||
(def before (.generation (app-model app)))
|
||||
(app-dispatch! app (SetParam 3 60.0))
|
||||
(when (not (wait-for (fun (m) (and (> (.generation m) before) (scored? m)))))
|
||||
(panic! "the scores did not follow a change"))
|
||||
;; 3 is the key weight, after the three texts' weights.
|
||||
(app-dispatch! app (SetParam 3 2.0))
|
||||
(ignore (wait-for scored?))
|
||||
;; In a window, so that the theme gives the controls their templates.
|
||||
(def frame (Window.))
|
||||
(content! (cast ContentControl frame) (cast Object (app-control app)))
|
||||
(show! frame)
|
||||
(loop (:for (Tuple t name) (list (Tuple 0 "rules") (Tuple 1 "key-costs") (Tuple 2 "layout") (Tuple 3 "search")))
|
||||
(:do (app-dispatch! app (Tab t))
|
||||
(app-run-pending! app)
|
||||
(save-shot (cast Control frame) 1500 900 (path-combine folder (str name ".png")))))
|
||||
;; A short search, and its results.
|
||||
(app-dispatch! app (SetRuns 2.0))
|
||||
(app-dispatch! app (SetSteps 20000.0))
|
||||
(app-dispatch! app Search)
|
||||
(when (not (wait-for (fun (m) (and (not (.searching m)) (= (vec-length (.results m)) 2)))))
|
||||
(panic! (str "the search did not finish: " (.status (app-model app)))))
|
||||
(app-dispatch! app (Keep 0))
|
||||
(when (not (wait-for (fun (m) (and (= (vec-length (.layouts m)) 17) (scored? m)))))
|
||||
(panic! "a kept layout was not scored"))
|
||||
(app-run-pending! app)
|
||||
(save-shot (cast Control frame) 1500 900 (path-combine folder "searched.png"))
|
||||
|
||||
;; --- presets
|
||||
(def had-presets (directory-exists? presets-folder))
|
||||
(def had-layouts (file-exists? layouts-file))
|
||||
(: weight (-> Model double))
|
||||
(def weight (fun (m) (record-ref (.params m) key-weight)))
|
||||
(app-dispatch! app (SetPresetName "gui-test"))
|
||||
(app-dispatch! app SavePreset)
|
||||
(when (not (wait-for (fun (m) (vec-contains? (.presets m) "gui-test"))))
|
||||
(panic! (str "the preset was not saved: " (.status (app-model app)))))
|
||||
(app-dispatch! app (SetParam 3 7.0))
|
||||
(when (not (wait-for (fun (m) (= (weight m) 7.0)))) (panic! "the key weight did not change"))
|
||||
(app-dispatch! app (LoadPreset "gui-test"))
|
||||
(when (not (wait-for (fun (m) (and (= (weight m) 2.0) (scored? m)))))
|
||||
(panic! (str "the preset was not loaded: " (.status (app-model app)))))
|
||||
(app-dispatch! app (Tab 0))
|
||||
(app-run-pending! app)
|
||||
(save-shot (cast Control frame) 1500 900 (path-combine folder "presets.png"))
|
||||
(app-dispatch! app (DeletePreset "gui-test"))
|
||||
(when (not (wait-for (fun (m) (not (vec-contains? (.presets m) "gui-test")))))
|
||||
(panic! "the preset was not deleted"))
|
||||
|
||||
;; --- saved layouts
|
||||
(: names (-> Model (Vec string)))
|
||||
(def names (fun (m) (vec-map layout-name-of (.layouts m))))
|
||||
(: choose-named (-> string void))
|
||||
(defun (choose-named n)
|
||||
(def m (app-model app))
|
||||
(def r (ranking m))
|
||||
(match (find (fun (pos) (= (layout-name-of (vec-ref (.layouts m) (vec-ref r pos))) n)) (range 0 (vec-length r)))
|
||||
((Some pos) (app-dispatch! app (Choose pos)))
|
||||
(None (panic! (str "no layout is named " n)))))
|
||||
(app-dispatch! app (SetLayoutName "gui test"))
|
||||
(app-dispatch! app (SaveResult 1))
|
||||
(when (not (wait-for (fun (m) (and (= (vec-length (.layouts m)) 18) (scored? m)
|
||||
(= (.status m) (str "Saved the layout gui test to " layouts-file "."))))))
|
||||
(panic! (str "a result was not saved: " (.status (app-model app)))))
|
||||
(when (not (string-contains? (file-read-text layouts-file) "gui test\t"))
|
||||
(panic! "the saved layout is not in the file"))
|
||||
;; The kept result, saved under a name, takes the place of "found 1".
|
||||
(choose-named "found 1")
|
||||
(app-dispatch! app (SetLayoutName "gui kept"))
|
||||
(app-dispatch! app SaveLayout)
|
||||
(when (not (wait-for (fun (m) (and (scored? m) (vec-contains? (.saved m) "gui kept")))))
|
||||
(panic! (str "the kept layout was not saved: " (.status (app-model app)))))
|
||||
(when (or (not (= (vec-length (.layouts (app-model app))) 18))
|
||||
(vec-contains? (names (app-model app)) "found 1"))
|
||||
(panic! "the kept layout was not renamed"))
|
||||
(when (not (wait-for (fun (m) (string-contains? (.status m) "Saved the layout gui kept"))))
|
||||
(panic! "the file was not written"))
|
||||
(app-dispatch! app (Tab 2))
|
||||
(app-run-pending! app)
|
||||
(save-shot (cast Control frame) 1500 900 (path-combine folder "layout-saved.png"))
|
||||
(app-dispatch! app RemoveLayout)
|
||||
(when (not (wait-for (fun (m) (and (= (vec-length (.layouts m)) 17) (scored? m)))))
|
||||
(panic! "the kept layout was not removed"))
|
||||
(choose-named "gui test")
|
||||
(app-dispatch! app RemoveLayout)
|
||||
(when (not (wait-for (fun (m) (and (= (vec-length (.layouts m)) 16) (scored? m)
|
||||
(string-contains? (.status m) "Removed gui test from")))))
|
||||
(panic! (str "the layouts were not removed: " (.status (app-model app)))))
|
||||
(when (string-contains? (file-read-text layouts-file) "gui ")
|
||||
(panic! "a removed layout is still in the file"))
|
||||
(when (not had-layouts) (file-delete layouts-file))
|
||||
(when (and (not had-presets) (= (vec-length (directory-files presets-folder)) 0))
|
||||
(directory-delete presets-folder))
|
||||
(println "gui shots ok")
|
||||
0)
|
||||
Loading…
Add table
Add a link
Reference in a new issue