maia::strength: the strength tables and the choice of a move shared; Android trainer screen
The measured tables (strength → rating input, temperature) and the choice of Maia's move (rare moves dropped) move from the desktop's play.rs into the maia crate; the desktop plays by them. Android: «Learn the opening up to this move» in the move sheet opens the trainer over the game (tasks bar, wrong move lit for 400 ms, «Show the move» after three mistakes, the result card). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2528138135
commit
5911750506
18 changed files with 745 additions and 101 deletions
|
|
@ -35,6 +35,12 @@ class ChessPenguinApp : Application() {
|
|||
/// The app's own updates (android-ui.md §25).
|
||||
val updates by lazy { AppUpdates(this, scope, engineFiles) }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// The opening trainer's runs (android-play.md §32.3).
|
||||
uniffi.mobile_api.trainerSetFile(java.io.File(filesDir, "training.json").path)
|
||||
}
|
||||
|
||||
/// The games shown on the list of each database (after a search), for paging
|
||||
/// games from the game screen: database id → game numbers.
|
||||
val shown = HashMap<String, List<UInt>>()
|
||||
|
|
|
|||
|
|
@ -188,6 +188,8 @@ fun Board(
|
|||
check: Boolean = false,
|
||||
animated: Boolean = true,
|
||||
input: BoardInput? = null,
|
||||
/// Two squares lit red: a wrong move of the trainer, shown for a moment (§32.2).
|
||||
alert: Pair<String, String>? = null,
|
||||
) {
|
||||
val colors = LocalChessColors.current
|
||||
val context = LocalContext.current
|
||||
|
|
@ -303,6 +305,9 @@ fun Board(
|
|||
if (image == null) drawRect(if (light) theme.light else theme.dark, cell(i), Size(sq, sq))
|
||||
if (i == from || i == to) drawRect(colors.lastMove, cell(i), Size(sq, sq))
|
||||
}
|
||||
alert?.let { (a, b) ->
|
||||
for (sqName in listOf(a, b)) squareIndex(sqName)?.let { drawRect(Color(220, 40, 40, 115), cell(it), Size(sq, sq)) }
|
||||
}
|
||||
val chosen = selected
|
||||
if (chosen != null) drawRect(colors.lastMove.copy(alpha = 0.5f), cell(chosen), Size(sq, sq))
|
||||
for (m in marks) {
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ import androidx.compose.material.icons.outlined.Memory
|
|||
import androidx.compose.material.icons.rounded.ChevronLeft
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Save
|
||||
import androidx.compose.material.icons.rounded.School
|
||||
import androidx.compose.material.icons.rounded.VerticalAlignTop
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Download
|
||||
|
|
@ -90,6 +91,7 @@ import androidx.compose.ui.input.pointer.pointerInput
|
|||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
|
|
@ -148,6 +150,14 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
|
|||
var game by held.data
|
||||
var edit by held.session
|
||||
val newGame = db == NEW_GAME
|
||||
// Learning the opening of this game: its own screen over the game (§32).
|
||||
held.trainer.value?.let { t ->
|
||||
TrainScreen(t, held.trainPly, held.trainFlipped, onPly = { held.trainPly = it }, onExit = {
|
||||
held.trainer.value = null
|
||||
t.close()
|
||||
})
|
||||
return
|
||||
}
|
||||
var failed by remember { mutableStateOf(false) }
|
||||
var current by rememberSaveable(place) { mutableIntStateOf(0) }
|
||||
var flipped by rememberSaveable { mutableStateOf(false) }
|
||||
|
|
@ -927,6 +937,17 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
|
|||
MoveSheet(
|
||||
label = AnnotatedString(if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san),
|
||||
inVariation = g.nodes[n.parent!!.toInt()].children.firstOrNull()?.toInt() != sheetMove,
|
||||
runs = remember(sheetMove) { edit?.trainingRuns(sheetMove.toUInt())?.toInt() },
|
||||
canTrain = !n.nullMove,
|
||||
onTrain = {
|
||||
moveSheet = null
|
||||
edit?.trainer(sheetMove.toUInt())?.let { t ->
|
||||
preview = null
|
||||
held.trainPly = 0
|
||||
held.trainFlipped = flipped
|
||||
held.trainer.value = t
|
||||
}
|
||||
},
|
||||
onMakeMain = {
|
||||
moveSheet = null
|
||||
runCatching { edit?.makeMain(sheetMove.toUInt()) }.getOrNull()?.let { apply(it) }
|
||||
|
|
@ -1202,23 +1223,42 @@ private fun Live(content: @Composable () -> Unit) = content()
|
|||
/// one (in a variation), remove it with what follows.
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun MoveSheet(label: AnnotatedString, inVariation: Boolean, onMakeMain: () -> Unit, onDelete: () -> Unit, onDismiss: () -> Unit) {
|
||||
private fun MoveSheet(
|
||||
label: AnnotatedString,
|
||||
inVariation: Boolean,
|
||||
runs: Int?,
|
||||
canTrain: Boolean,
|
||||
onMakeMain: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onTrain: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {
|
||||
Text(label, style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp))
|
||||
if (inVariation) SheetAction(Icons.Rounded.VerticalAlignTop, stringResource(R.string.make_main), onMakeMain)
|
||||
SheetAction(Icons.Rounded.Close, stringResource(R.string.delete_move), onDelete)
|
||||
if (inVariation) SheetAction(Icons.Rounded.VerticalAlignTop, stringResource(R.string.make_main), onClick = onMakeMain)
|
||||
SheetAction(Icons.Rounded.Close, stringResource(R.string.delete_move), onClick = onDelete)
|
||||
HorizontalDivider(Modifier.padding(vertical = 4.dp), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
SheetAction(
|
||||
Icons.Rounded.School,
|
||||
stringResource(R.string.train_learn),
|
||||
trailing = runs?.takeIf { it > 0 }?.let { pluralStringResource(R.plurals.train_runs, it, it) },
|
||||
enabled = canTrain,
|
||||
onClick = onTrain,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SheetAction(icon: ImageVector, text: String, onClick: () -> Unit) {
|
||||
private fun SheetAction(icon: ImageVector, text: String, trailing: String? = null, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val alpha = if (enabled) 1f else 0.38f
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(56.dp).clickable(onClick = onClick).padding(horizontal = 24.dp),
|
||||
Modifier.fillMaxWidth().height(56.dp).clickable(enabled = enabled, onClick = onClick).padding(horizontal = 24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(text, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge)
|
||||
Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha))
|
||||
Text(text, Modifier.weight(1f).padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface.copy(alpha = alpha))
|
||||
trailing?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,8 +50,13 @@ class GameEdit : ViewModel() {
|
|||
var notes: List<String> = emptyList()
|
||||
/// Where a new game or a copy was saved: saving again replaces it there.
|
||||
var savedTo: Pair<String, UInt>? = null
|
||||
/// An opening being learned over the game (android-play.md §32), how far, the board's side.
|
||||
val trainer = mutableStateOf<uniffi.mobile_api.Trainer?>(null)
|
||||
var trainPly = 0
|
||||
var trainFlipped = false
|
||||
|
||||
override fun onCleared() {
|
||||
trainer.value?.close()
|
||||
session.value?.close()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,268 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import android.view.HapticFeedbackConstants
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.rounded.Replay
|
||||
import androidx.compose.material.icons.rounded.SwapVert
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import io.github.vrubelroman.chesspenguin.R
|
||||
import kotlinx.coroutines.delay
|
||||
import uniffi.mobile_api.TrainVerdict
|
||||
import uniffi.mobile_api.Trainer
|
||||
|
||||
/// A wrong move of the trainer, on the board for a moment (§32.2).
|
||||
private data class Wrong(val fen: String, val from: String, val to: String)
|
||||
|
||||
/// Learning an opening (android-play.md §32): the user plays the moves of both sides
|
||||
/// of the line from memory; a wrong move shows for 400 ms and is taken back.
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun TrainScreen(trainer: Trainer, ply0: Int, startFlipped: Boolean, onPly: (Int) -> Unit, onExit: () -> Unit) {
|
||||
val app = app()
|
||||
val prefs by app.settings.prefs.collectAsState()
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val pieces = remember { Pieces(context) }
|
||||
val view = LocalView.current
|
||||
val lang = uiLanguage()
|
||||
val san = remember(prefs.notation, lang) { { s: String -> displaySan(s, prefs.notation, lang) } }
|
||||
var ply by remember { mutableIntStateOf(ply0) }
|
||||
var flipped by remember { mutableStateOf(startFlipped) }
|
||||
var wrong by remember { mutableStateOf<Wrong?>(null) }
|
||||
// Said after a wrong move until the right one.
|
||||
var missed by remember { mutableStateOf(false) }
|
||||
var changes by remember { mutableIntStateOf(0) }
|
||||
val st = remember(ply, changes) { trainer.state(ply.toUInt()) }
|
||||
BackHandler(onBack = onExit)
|
||||
LaunchedEffect(wrong) {
|
||||
if (wrong != null) {
|
||||
delay(400)
|
||||
wrong = null
|
||||
}
|
||||
}
|
||||
fun buzz(reject: Boolean) {
|
||||
if (prefs.vibration) view.performHapticFeedback(if (reject) HapticFeedbackConstants.REJECT else HapticFeedbackConstants.CLOCK_TICK)
|
||||
}
|
||||
fun move(uci: String) {
|
||||
when (trainer.judge(ply.toUInt(), uci)) {
|
||||
TrainVerdict.RIGHT, TrainVerdict.FINISHED -> {
|
||||
missed = false
|
||||
ply += 1
|
||||
onPly(ply)
|
||||
buzz(false)
|
||||
}
|
||||
TrainVerdict.WRONG -> {
|
||||
trainer.fenAfter(ply.toUInt(), uci)?.let { wrong = Wrong(it, uci.substring(0, 2), uci.substring(2, 4)) }
|
||||
missed = true
|
||||
changes++
|
||||
buzz(true)
|
||||
}
|
||||
TrainVerdict.DONE -> {}
|
||||
}
|
||||
}
|
||||
val sub = listOfNotNull(trainer.game(), stringResource(R.string.train_up_to, san(trainer.upTo()).text)).joinToString(" · ")
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onExit) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.train_title), style = MaterialTheme.typography.titleMedium)
|
||||
Text(sub, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Column {
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly) {
|
||||
IconButton(onClick = { flipped = !flipped }) { Icon(Icons.Rounded.SwapVert, stringResource(R.string.flip)) }
|
||||
TextButton(enabled = ply > 0 || st.done, onClick = {
|
||||
trainer.again()
|
||||
ply = 0
|
||||
onPly(0)
|
||||
missed = false
|
||||
wrong = null
|
||||
changes++
|
||||
}) {
|
||||
Icon(Icons.Rounded.Replay, null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.train_restart))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.fillMaxSize().padding(padding)) {
|
||||
if (!st.done) {
|
||||
// The task: which move, whose turn, how far.
|
||||
val whiteToMove = st.fen.substringAfter(' ').startsWith("w")
|
||||
Column(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalArrangement = Arrangement.Center) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.train_move_of, (ply + 1).toString(), st.length.toString()), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge)
|
||||
Text(stringResource(if (whiteToMove) R.string.train_white else R.string.train_black), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
LinearProgressIndicator(progress = { ply.toFloat() / st.length.toInt().coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth().padding(top = 4.dp))
|
||||
}
|
||||
}
|
||||
val w = wrong
|
||||
Board(
|
||||
fen = w?.fen ?: st.fen,
|
||||
flipped = flipped,
|
||||
lastFrom = w?.from ?: st.fromSquare,
|
||||
lastTo = w?.to ?: st.toSquare,
|
||||
pieces = pieces,
|
||||
theme = prefs.board,
|
||||
set = prefs.pieces,
|
||||
description = stringResource(R.string.train_title),
|
||||
arrows = st.hint?.let { listOf(BoardArrow(it[0], it[1], EngineArrow)) } ?: emptyList(),
|
||||
animated = prefs.animation,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
input = if (st.done || w != null) null else BoardInput(
|
||||
remember(ply, changes) { trainer.legalMoves(ply.toUInt()) },
|
||||
onMove = ::move,
|
||||
// The line's own piece where it promotes; a queen otherwise (§29.4).
|
||||
promotion = { pair -> trainer.promotionAt(ply.toUInt())?.takeIf { it.startsWith(pair) }?.last() },
|
||||
),
|
||||
alert = w?.let { it.from to it.to },
|
||||
)
|
||||
if (!st.done) {
|
||||
// You: the mistakes of this run, or before the first move what was before.
|
||||
Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
val text = when {
|
||||
st.hint != null -> stringResource(R.string.train_arrow)
|
||||
missed -> stringResource(R.string.train_wrong)
|
||||
ply == 0 && st.mistakes == 0u -> history(st.before)
|
||||
else -> stringResource(R.string.train_mistakes, st.mistakes.toString())
|
||||
}
|
||||
Text(
|
||||
text,
|
||||
Modifier.weight(1f),
|
||||
color = if (missed && st.hint == null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (st.mayShow && st.hint == null) {
|
||||
TextButton(onClick = {
|
||||
trainer.show(ply.toUInt())
|
||||
changes++
|
||||
}) { Text(stringResource(R.string.train_show)) }
|
||||
} else if (ply > 0 || st.mistakes > 0u) {
|
||||
Text(
|
||||
stringResource(R.string.train_run, (st.before.runs + 1u).toString()),
|
||||
Modifier.padding(end = 12.dp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
if (st.done) Result(st, onAgain = {
|
||||
trainer.again()
|
||||
ply = 0
|
||||
onPly(0)
|
||||
missed = false
|
||||
changes++
|
||||
}, onExit = onExit)
|
||||
// The moves played so far, two to a row.
|
||||
st.played.chunked(2).forEachIndexed { i, pair ->
|
||||
Row(Modifier.fillMaxWidth().height(40.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("${i + 1}", Modifier.width(32.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(san(pair[0]), Modifier.weight(1f), fontWeight = FontWeight.Medium)
|
||||
Text(pair.getOrNull(1)?.let { san(it) } ?: androidx.compose.ui.text.AnnotatedString(""), Modifier.weight(1f), fontWeight = FontWeight.Medium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// «Last time: 2 · best: 0», «Not done before».
|
||||
@Composable
|
||||
private fun history(s: uniffi.mobile_api.TrainStats): String = when {
|
||||
s.runs == 0u -> stringResource(R.string.train_not_done)
|
||||
s.cleanStreak >= 2u -> stringResource(R.string.train_last_streak, (s.last ?: 0u).toString(), s.cleanStreak.toString())
|
||||
else -> stringResource(R.string.train_last_best, (s.last ?: 0u).toString(), s.best?.toString() ?: "–")
|
||||
}
|
||||
|
||||
/// The end of a run (§32.3): how it went, the line's runs, again or back to the game.
|
||||
@Composable
|
||||
private fun Result(st: uniffi.mobile_api.TrainState, onAgain: () -> Unit, onExit: () -> Unit) {
|
||||
val after = st.after ?: st.before
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp)
|
||||
.background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(16.dp))
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(
|
||||
when {
|
||||
st.hinted -> stringResource(R.string.train_done_hint, st.mistakes.toString())
|
||||
st.mistakes == 0u -> stringResource(R.string.train_done_clean)
|
||||
else -> stringResource(R.string.train_done, st.mistakes.toString())
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
val line = buildList {
|
||||
add(stringResource(R.string.train_run_best, after.runs.toString(), after.best?.toString() ?: "–"))
|
||||
if (after.cleanStreak >= 2u) add(stringResource(R.string.train_streak, after.cleanStreak.toString()))
|
||||
}.joinToString(" · ")
|
||||
Text(line, style = MaterialTheme.typography.bodyMedium)
|
||||
if (after.recentMistakes.size > 1) {
|
||||
val runs = after.recentMistakes.zip(after.recentHinted).joinToString(" · ") { (m, h) -> if (h) "$m*" else "$m" }
|
||||
Text(stringResource(R.string.train_recent, runs), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = onAgain, modifier = Modifier.weight(1f).height(48.dp)) { Text(stringResource(R.string.train_again)) }
|
||||
OutlinedButton(onClick = onExit, modifier = Modifier.weight(1f).height(48.dp)) { Text(stringResource(R.string.train_back)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -433,4 +433,31 @@
|
|||
<string name="keep_editing">Weiter bearbeiten</string>
|
||||
<string name="edit">Bearbeiten</string>
|
||||
<string name="next">Weiter</string>
|
||||
<string name="train_title">Eröffnung lernen</string>
|
||||
<string name="train_up_to">bis %1$s</string>
|
||||
<string name="train_learn">Eröffnung bis zu diesem Zug lernen</string>
|
||||
<string name="train_move_of">Zug %1$s von %2$s</string>
|
||||
<string name="train_white">♔ Weiß am Zug</string>
|
||||
<string name="train_black">♚ Schwarz am Zug</string>
|
||||
<string name="train_mistakes">Fehler: %1$s</string>
|
||||
<string name="train_run">Durchgang %1$s</string>
|
||||
<string name="train_wrong">× In der Partie folgt hier ein anderer Zug</string>
|
||||
<string name="train_show">Zug zeigen</string>
|
||||
<string name="train_not_done">Diese Linie noch nicht geübt</string>
|
||||
<string name="train_last_streak">Zuletzt: %1$s · fehlerfrei in Folge: %2$s</string>
|
||||
<string name="train_last_best">Zuletzt: %1$s · Bestwert: %2$s</string>
|
||||
<string name="train_done_clean">Fehlerfrei geschafft</string>
|
||||
<string name="train_done_hint">Mit Hinweis geschafft · Fehler: %1$s</string>
|
||||
<string name="train_done">Geschafft · Fehler: %1$s</string>
|
||||
<string name="train_run_best">Durchgang %1$s · Bestwert: %2$s</string>
|
||||
<string name="train_streak">fehlerfrei in Folge: %1$s</string>
|
||||
<string name="train_recent">Letzte: %1$s</string>
|
||||
<string name="train_arrow">Spielen Sie den Zug des Pfeils</string>
|
||||
<string name="train_again">↻ Noch einmal</string>
|
||||
<string name="train_back">⬅ Zurück zur Partie</string>
|
||||
<string name="train_restart">Von vorn</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d Durchgang</item>
|
||||
<item quantity="other">%1$d Durchgänge</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -440,4 +440,32 @@
|
|||
<string name="keep_editing">Seguir editando</string>
|
||||
<string name="edit">Editar</string>
|
||||
<string name="next">Siguiente</string>
|
||||
<string name="train_title">Aprendiendo la apertura</string>
|
||||
<string name="train_up_to">hasta %1$s</string>
|
||||
<string name="train_learn">Aprender la apertura hasta esta jugada</string>
|
||||
<string name="train_move_of">Jugada %1$s de %2$s</string>
|
||||
<string name="train_white">♔ Juegan blancas</string>
|
||||
<string name="train_black">♚ Juegan negras</string>
|
||||
<string name="train_mistakes">Errores: %1$s</string>
|
||||
<string name="train_run">Repaso %1$s</string>
|
||||
<string name="train_wrong">× En la partida hay otra jugada aquí</string>
|
||||
<string name="train_show">Mostrar la jugada</string>
|
||||
<string name="train_not_done">Línea aún no repasada</string>
|
||||
<string name="train_last_streak">La última vez: %1$s · sin errores seguidos: %2$s</string>
|
||||
<string name="train_last_best">La última vez: %1$s · mejor: %2$s</string>
|
||||
<string name="train_done_clean">Completado sin errores</string>
|
||||
<string name="train_done_hint">Completado con pista · errores: %1$s</string>
|
||||
<string name="train_done">Completado · errores: %1$s</string>
|
||||
<string name="train_run_best">Repaso %1$s · mejor: %2$s</string>
|
||||
<string name="train_streak">sin errores seguidos: %1$s</string>
|
||||
<string name="train_recent">Recientes: %1$s</string>
|
||||
<string name="train_arrow">Juega la jugada de la flecha</string>
|
||||
<string name="train_again">↻ Otra vez</string>
|
||||
<string name="train_back">⬅ Volver a la partida</string>
|
||||
<string name="train_restart">Desde el principio</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d repaso</item>
|
||||
<item quantity="many">%1$d repasos</item>
|
||||
<item quantity="other">%1$d repasos</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -440,4 +440,32 @@
|
|||
<string name="keep_editing">Continuer</string>
|
||||
<string name="edit">Modifier</string>
|
||||
<string name="next">Suivant</string>
|
||||
<string name="train_title">Apprentissage de l\'ouverture</string>
|
||||
<string name="train_up_to">jusqu\'à %1$s</string>
|
||||
<string name="train_learn">Apprendre l\'ouverture jusqu\'à ce coup</string>
|
||||
<string name="train_move_of">Coup %1$s sur %2$s</string>
|
||||
<string name="train_white">♔ Trait aux Blancs</string>
|
||||
<string name="train_black">♚ Trait aux Noirs</string>
|
||||
<string name="train_mistakes">Erreurs : %1$s</string>
|
||||
<string name="train_run">Passage %1$s</string>
|
||||
<string name="train_wrong">× La partie a un autre coup ici</string>
|
||||
<string name="train_show">Montrer le coup</string>
|
||||
<string name="train_not_done">Ligne jamais parcourue</string>
|
||||
<string name="train_last_streak">La dernière fois : %1$s · sans erreur d\'affilée : %2$s</string>
|
||||
<string name="train_last_best">La dernière fois : %1$s · meilleur : %2$s</string>
|
||||
<string name="train_done_clean">Terminé sans erreur</string>
|
||||
<string name="train_done_hint">Terminé avec un indice · erreurs : %1$s</string>
|
||||
<string name="train_done">Terminé · erreurs : %1$s</string>
|
||||
<string name="train_run_best">Passage %1$s · meilleur : %2$s</string>
|
||||
<string name="train_streak">sans erreur d\'affilée : %1$s</string>
|
||||
<string name="train_recent">Récents : %1$s</string>
|
||||
<string name="train_arrow">Jouez le coup indiqué par la flèche</string>
|
||||
<string name="train_again">↻ Encore</string>
|
||||
<string name="train_back">⬅ Retour à la partie</string>
|
||||
<string name="train_restart">Recommencer</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d passage</item>
|
||||
<item quantity="many">%1$d passages</item>
|
||||
<item quantity="other">%1$d passages</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -440,4 +440,32 @@
|
|||
<string name="keep_editing">Continua a modificare</string>
|
||||
<string name="edit">Modifica</string>
|
||||
<string name="next">Avanti</string>
|
||||
<string name="train_title">Studio dell\'apertura</string>
|
||||
<string name="train_up_to">fino a %1$s</string>
|
||||
<string name="train_learn">Studia l\'apertura fino a questa mossa</string>
|
||||
<string name="train_move_of">Mossa %1$s di %2$s</string>
|
||||
<string name="train_white">♔ Muove il Bianco</string>
|
||||
<string name="train_black">♚ Muove il Nero</string>
|
||||
<string name="train_mistakes">Errori: %1$s</string>
|
||||
<string name="train_run">Giro %1$s</string>
|
||||
<string name="train_wrong">× Nella partita qui c\'è un\'altra mossa</string>
|
||||
<string name="train_show">Mostra la mossa</string>
|
||||
<string name="train_not_done">Linea mai ripassata</string>
|
||||
<string name="train_last_streak">L\'ultima volta: %1$s · senza errori di fila: %2$s</string>
|
||||
<string name="train_last_best">L\'ultima volta: %1$s · migliore: %2$s</string>
|
||||
<string name="train_done_clean">Completato senza errori</string>
|
||||
<string name="train_done_hint">Completato con un aiuto · errori: %1$s</string>
|
||||
<string name="train_done">Completato · errori: %1$s</string>
|
||||
<string name="train_run_best">Giro %1$s · migliore: %2$s</string>
|
||||
<string name="train_streak">senza errori di fila: %1$s</string>
|
||||
<string name="train_recent">Recenti: %1$s</string>
|
||||
<string name="train_arrow">Gioca la mossa indicata dalla freccia</string>
|
||||
<string name="train_again">↻ Ancora</string>
|
||||
<string name="train_back">⬅ Torna alla partita</string>
|
||||
<string name="train_restart">Da capo</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d ripasso</item>
|
||||
<item quantity="many">%1$d ripassi</item>
|
||||
<item quantity="other">%1$d ripassi</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -434,4 +434,31 @@
|
|||
<string name="keep_editing">Өңдеуді жалғастыру</string>
|
||||
<string name="edit">Өзгерту</string>
|
||||
<string name="next">Келесі</string>
|
||||
<string name="train_title">Дебютті үйрену</string>
|
||||
<string name="train_up_to">%1$s дейін</string>
|
||||
<string name="train_learn">Дебютті осы жүріске дейін үйрену</string>
|
||||
<string name="train_move_of">Жүріс %1$s / %2$s</string>
|
||||
<string name="train_white">♔ Ақтар жүреді</string>
|
||||
<string name="train_black">♚ Қаралар жүреді</string>
|
||||
<string name="train_mistakes">Қателер: %1$s</string>
|
||||
<string name="train_run">Әрекет %1$s</string>
|
||||
<string name="train_wrong">× Партияда мұнда басқа жүріс</string>
|
||||
<string name="train_show">Жүрісті көрсету</string>
|
||||
<string name="train_not_done">Бұл линия әлі өтілмеген</string>
|
||||
<string name="train_last_streak">Соңғы рет: %1$s · қатарынан қатесіз: %2$s</string>
|
||||
<string name="train_last_best">Соңғы рет: %1$s · ең үздігі: %2$s</string>
|
||||
<string name="train_done_clean">Қатесіз өтілді</string>
|
||||
<string name="train_done_hint">Көмекпен өтілді · қателер: %1$s</string>
|
||||
<string name="train_done">Өтілді · қателер: %1$s</string>
|
||||
<string name="train_run_best">Әрекет %1$s · ең үздігі: %2$s</string>
|
||||
<string name="train_streak">қатарынан қатесіз: %1$s</string>
|
||||
<string name="train_recent">Соңғылары: %1$s</string>
|
||||
<string name="train_arrow">Көрсеткідегі жүрісті жасаңыз</string>
|
||||
<string name="train_again">↻ Қайталау</string>
|
||||
<string name="train_back">⬅ Партияға оралу</string>
|
||||
<string name="train_restart">Басынан</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d рет</item>
|
||||
<item quantity="other">%1$d рет</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -441,4 +441,32 @@
|
|||
<string name="keep_editing">Continuar editando</string>
|
||||
<string name="edit">Editar</string>
|
||||
<string name="next">Avançar</string>
|
||||
<string name="train_title">Aprendendo a abertura</string>
|
||||
<string name="train_up_to">até %1$s</string>
|
||||
<string name="train_learn">Aprender a abertura até este lance</string>
|
||||
<string name="train_move_of">Lance %1$s de %2$s</string>
|
||||
<string name="train_white">♔ Brancas jogam</string>
|
||||
<string name="train_black">♚ Pretas jogam</string>
|
||||
<string name="train_mistakes">Erros: %1$s</string>
|
||||
<string name="train_run">Rodada %1$s</string>
|
||||
<string name="train_wrong">× Na partida há outro lance aqui</string>
|
||||
<string name="train_show">Mostrar o lance</string>
|
||||
<string name="train_not_done">Linha ainda não treinada</string>
|
||||
<string name="train_last_streak">Última vez: %1$s · sem erros seguidos: %2$s</string>
|
||||
<string name="train_last_best">Última vez: %1$s · melhor: %2$s</string>
|
||||
<string name="train_done_clean">Concluído sem erros</string>
|
||||
<string name="train_done_hint">Concluído com dica · erros: %1$s</string>
|
||||
<string name="train_done">Concluído · erros: %1$s</string>
|
||||
<string name="train_run_best">Rodada %1$s · melhor: %2$s</string>
|
||||
<string name="train_streak">sem erros seguidos: %1$s</string>
|
||||
<string name="train_recent">Recentes: %1$s</string>
|
||||
<string name="train_arrow">Jogue o lance da seta</string>
|
||||
<string name="train_again">↻ De novo</string>
|
||||
<string name="train_back">⬅ Voltar à partida</string>
|
||||
<string name="train_restart">Do início</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d passagem</item>
|
||||
<item quantity="many">%1$d passagens</item>
|
||||
<item quantity="other">%1$d passagens</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -447,4 +447,33 @@
|
|||
<string name="keep_editing">Продолжить правку</string>
|
||||
<string name="edit">Изменить</string>
|
||||
<string name="next">Далее</string>
|
||||
<string name="train_title">Учим дебют</string>
|
||||
<string name="train_up_to">до %1$s</string>
|
||||
<string name="train_learn">Учить дебют до этого хода</string>
|
||||
<string name="train_move_of">Ход %1$s из %2$s</string>
|
||||
<string name="train_white">♔ ход белых</string>
|
||||
<string name="train_black">♚ ход чёрных</string>
|
||||
<string name="train_mistakes">Ошибок: %1$s</string>
|
||||
<string name="train_run">Прохождение %1$s</string>
|
||||
<string name="train_wrong">× В партии — другой ход</string>
|
||||
<string name="train_show">Показать ход</string>
|
||||
<string name="train_not_done">Эту линию ещё не проходили</string>
|
||||
<string name="train_last_streak">Прошлое: %1$s · без ошибок подряд: %2$s</string>
|
||||
<string name="train_last_best">Прошлое: %1$s · лучшее: %2$s</string>
|
||||
<string name="train_done_clean">Пройдено без ошибок</string>
|
||||
<string name="train_done_hint">Пройдено с подсказкой · ошибок: %1$s</string>
|
||||
<string name="train_done">Пройдено · ошибок: %1$s</string>
|
||||
<string name="train_run_best">Прохождение %1$s · лучшее: %2$s</string>
|
||||
<string name="train_streak">без ошибок подряд: %1$s</string>
|
||||
<string name="train_recent">Последние: %1$s</string>
|
||||
<string name="train_arrow">Сделайте ход со стрелки</string>
|
||||
<string name="train_again">↻ Повторить</string>
|
||||
<string name="train_back">⬅ К партии</string>
|
||||
<string name="train_restart">Сначала</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">прохождений: %1$d</item>
|
||||
<item quantity="few">прохождений: %1$d</item>
|
||||
<item quantity="many">прохождений: %1$d</item>
|
||||
<item quantity="other">прохождений: %1$d</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -432,4 +432,31 @@
|
|||
<string name="keep_editing">Tahrirlashni davom ettirish</string>
|
||||
<string name="edit">Tahrirlash</string>
|
||||
<string name="next">Keyingi</string>
|
||||
<string name="train_title">Debyutni o‘rganish</string>
|
||||
<string name="train_up_to">%1$s gacha</string>
|
||||
<string name="train_learn">Debyutni shu yurishgacha o‘rganish</string>
|
||||
<string name="train_move_of">Yurish %1$s / %2$s</string>
|
||||
<string name="train_white">♔ Oqlar yuradi</string>
|
||||
<string name="train_black">♚ Qoralar yuradi</string>
|
||||
<string name="train_mistakes">Xatolar: %1$s</string>
|
||||
<string name="train_run">Urinish %1$s</string>
|
||||
<string name="train_wrong">× Partiyada bu yerda boshqa yurish</string>
|
||||
<string name="train_show">Yurishni ko‘rsatish</string>
|
||||
<string name="train_not_done">Bu liniya hali o‘tilmagan</string>
|
||||
<string name="train_last_streak">Oxirgi marta: %1$s · ketma-ket xatosiz: %2$s</string>
|
||||
<string name="train_last_best">Oxirgi marta: %1$s · eng yaxshi: %2$s</string>
|
||||
<string name="train_done_clean">Xatosiz o‘tildi</string>
|
||||
<string name="train_done_hint">Yordam bilan o‘tildi · xatolar: %1$s</string>
|
||||
<string name="train_done">O‘tildi · xatolar: %1$s</string>
|
||||
<string name="train_run_best">Urinish %1$s · eng yaxshi: %2$s</string>
|
||||
<string name="train_streak">ketma-ket xatosiz: %1$s</string>
|
||||
<string name="train_recent">So‘nggilari: %1$s</string>
|
||||
<string name="train_arrow">Strelkadagi yurishni qiling</string>
|
||||
<string name="train_again">↻ Yana</string>
|
||||
<string name="train_back">⬅ Partiyaga qaytish</string>
|
||||
<string name="train_restart">Boshidan</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d marta</item>
|
||||
<item quantity="other">%1$d marta</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -437,4 +437,31 @@
|
|||
<string name="keep_editing">Keep editing</string>
|
||||
<string name="edit">Edit</string>
|
||||
<string name="next">Next</string>
|
||||
<string name="train_title">Learning the opening</string>
|
||||
<string name="train_up_to">up to %1$s</string>
|
||||
<string name="train_learn">Learn the opening up to this move</string>
|
||||
<string name="train_move_of">Move %1$s of %2$s</string>
|
||||
<string name="train_white">♔ White to move</string>
|
||||
<string name="train_black">♚ Black to move</string>
|
||||
<string name="train_mistakes">Mistakes: %1$s</string>
|
||||
<string name="train_run">Run %1$s</string>
|
||||
<string name="train_wrong">× The game has another move here</string>
|
||||
<string name="train_show">Show the move</string>
|
||||
<string name="train_not_done">Not done before</string>
|
||||
<string name="train_last_streak">Last time: %1$s · clean in a row: %2$s</string>
|
||||
<string name="train_last_best">Last time: %1$s · best: %2$s</string>
|
||||
<string name="train_done_clean">Done without mistakes</string>
|
||||
<string name="train_done_hint">Done with a hint · mistakes: %1$s</string>
|
||||
<string name="train_done">Done · mistakes: %1$s</string>
|
||||
<string name="train_run_best">Run %1$s · best: %2$s</string>
|
||||
<string name="train_streak">clean in a row: %1$s</string>
|
||||
<string name="train_recent">Recent: %1$s</string>
|
||||
<string name="train_arrow">Play the move on the arrow</string>
|
||||
<string name="train_again">↻ Again</string>
|
||||
<string name="train_back">⬅ Back to the game</string>
|
||||
<string name="train_restart">From the start</string>
|
||||
<plurals name="train_runs">
|
||||
<item quantity="one">%1$d run</item>
|
||||
<item quantity="other">%1$d runs</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -11,16 +11,18 @@ use std::sync::{Arc, Mutex};
|
|||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// The published models.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Model {
|
||||
/// 5M parameters: plays up to about 1800.
|
||||
Small,
|
||||
/// 79M parameters: stronger and closer to people, several times slower.
|
||||
Large,
|
||||
pub use maia::strength::Model;
|
||||
|
||||
/// Where each model is published.
|
||||
pub trait Published {
|
||||
fn repo(self) -> &'static str;
|
||||
fn revision(self) -> &'static str;
|
||||
fn file(self) -> &'static str;
|
||||
fn sha256(self) -> &'static str;
|
||||
fn size(self) -> u64;
|
||||
}
|
||||
|
||||
impl Model {
|
||||
impl Published for Model {
|
||||
fn repo(self) -> &'static str {
|
||||
match self {
|
||||
Model::Small => "Maia3-5M",
|
||||
|
|
@ -49,7 +51,7 @@ impl Model {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn size(self) -> u64 {
|
||||
fn size(self) -> u64 {
|
||||
match self {
|
||||
Model::Small => 20_968_049,
|
||||
Model::Large => 315_651_851,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@ use chess_core::shakmaty::{Chess, Color, EnPassantMode, Move, Position};
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::i18n::tr;
|
||||
use crate::maia_download::Model;
|
||||
use crate::maia_download::Published;
|
||||
use maia::strength::Model;
|
||||
|
||||
// ----- time controls --------------------------------------------------------------------
|
||||
|
||||
|
|
@ -157,82 +158,7 @@ pub const STRENGTH_MAX: u32 = 2100;
|
|||
|
||||
// ----- Maia's strength ----------------------------------------------------------------
|
||||
|
||||
/// The strongest the small model plays (with the large one missing).
|
||||
pub const SMALL_MAX: u32 = 1800;
|
||||
|
||||
/// Measured (docs/research/maia-strength.md): Maia's rating input → her strength on
|
||||
/// the Lichess blitz scale, as she plays here (temperature 1, rare moves dropped).
|
||||
const SMALL: &[(u32, u32)] = &[
|
||||
(600, 1043),
|
||||
(800, 1154),
|
||||
(1100, 1333),
|
||||
(1300, 1426),
|
||||
(1500, 1485),
|
||||
(1700, 1563),
|
||||
(1900, 1632),
|
||||
(2100, 1683),
|
||||
(2300, 1737),
|
||||
(2600, 1767),
|
||||
];
|
||||
const LARGE: &[(u32, u32)] = &[
|
||||
(600, 1078),
|
||||
(1100, 1375),
|
||||
(1500, 1605),
|
||||
(1900, 1794),
|
||||
(2300, 1964),
|
||||
(2600, 2000),
|
||||
];
|
||||
|
||||
/// Above what a model plays choosing among the likely moves (temperature 1), it is made
|
||||
/// stronger by choosing more surely: measured strength at its top rating input → the
|
||||
/// temperature (0: always the most likely move).
|
||||
const SMALL_SURE: &[(u32, f32)] = &[(1767, 1.0), (1854, 0.5)];
|
||||
const LARGE_SURE: &[(u32, f32)] = &[(1976, 1.0), (2053, 0.5), (2126, 0.0)];
|
||||
|
||||
/// How surely `model` chooses its move to play at `strength` (1 below its top).
|
||||
pub fn temperature(model: Model, strength: u32) -> f32 {
|
||||
let table = match model {
|
||||
Model::Small => SMALL_SURE,
|
||||
Model::Large => LARGE_SURE,
|
||||
};
|
||||
let (first, last) = (table[0], table[table.len() - 1]);
|
||||
if strength <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
if strength >= last.0 {
|
||||
return last.1;
|
||||
}
|
||||
let i = table
|
||||
.iter()
|
||||
.position(|p| p.0 >= strength)
|
||||
.unwrap_or(table.len() - 1);
|
||||
let ((a_s, a_t), (b_s, b_t)) = (table[i - 1], table[i]);
|
||||
let k = (strength - a_s) as f32 / (b_s - a_s) as f32;
|
||||
a_t + k * (b_t - a_t)
|
||||
}
|
||||
|
||||
/// The rating to give `model` for it to play at `strength` (between the measured
|
||||
/// points, in proportion; outside them, the nearest).
|
||||
pub fn rating_input(model: Model, strength: u32) -> u32 {
|
||||
let table = match model {
|
||||
Model::Small => SMALL,
|
||||
Model::Large => LARGE,
|
||||
};
|
||||
let (first, last) = (table[0], table[table.len() - 1]);
|
||||
if strength <= first.1 {
|
||||
return first.0;
|
||||
}
|
||||
if strength >= last.1 {
|
||||
return last.0;
|
||||
}
|
||||
let i = table
|
||||
.iter()
|
||||
.position(|p| p.1 >= strength)
|
||||
.unwrap_or(table.len() - 1);
|
||||
let ((a_in, a_out), (b_in, b_out)) = (table[i - 1], table[i]);
|
||||
let t = f64::from(strength - a_out) / f64::from(b_out - a_out);
|
||||
(f64::from(a_in) + t * f64::from(b_in - a_in)).round() as u32
|
||||
}
|
||||
pub use maia::strength::{SMALL_MAX, rating_input, temperature};
|
||||
|
||||
/// The model to play at `strength`, with its file: the large one when it is there,
|
||||
/// else the small one up to its ceiling. `Err`: the model to download.
|
||||
|
|
@ -493,13 +419,8 @@ impl Opponent {
|
|||
r = newer;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut p = maia.predict(&r.positions, r.self_elo, r.oppo_elo);
|
||||
// Human mistakes, not accidents: a move less than a tenth as likely as
|
||||
// the most likely one is not played (a 2600 does not hang the queen
|
||||
// one time in five thousand).
|
||||
let top = p.moves.first().map_or(0.0, |(_, pr)| *pr);
|
||||
p.moves.retain(|(_, pr)| *pr >= 0.1 * top);
|
||||
let m = maia::pick(&p, r.temperature, random_unit());
|
||||
let p = maia.predict(&r.positions, r.self_elo, r.oppo_elo);
|
||||
let m = maia::strength::choose(&p, r.temperature, random_unit());
|
||||
let rest = r.pause.saturating_sub(started.elapsed());
|
||||
std::thread::sleep(rest);
|
||||
// Her clock: the pause, or the computing when it took longer (a slow
|
||||
|
|
@ -606,7 +527,7 @@ pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Dur
|
|||
mod tests {
|
||||
#[test]
|
||||
fn strength_to_rating_input() {
|
||||
use crate::maia_download::Model;
|
||||
use maia::strength::Model;
|
||||
// The measured points themselves, in proportion between them, the ends held.
|
||||
assert_eq!(rating_input(Model::Large, 1605), 1500);
|
||||
assert_eq!(rating_input(Model::Large, 2000), 2600);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
|
||||
mod checkpoint;
|
||||
mod net;
|
||||
pub mod strength;
|
||||
mod weights;
|
||||
|
||||
pub use net::Prediction;
|
||||
|
|
|
|||
147
crates/maia/src/strength.rs
Normal file
147
crates/maia/src/strength.rs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
//! How strong Maia plays (docs/research/maia-strength.md): the measured tables of the
|
||||
//! published models, from a strength on the Lichess blitz scale to the rating to give
|
||||
//! the network and how surely to choose, and the choice of the move itself. The desktop
|
||||
//! and the Android apps play by these.
|
||||
|
||||
use shakmaty::Move;
|
||||
|
||||
use crate::{Prediction, pick};
|
||||
|
||||
/// The published models.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Model {
|
||||
/// 5M parameters: plays up to about 1800.
|
||||
Small,
|
||||
/// 79M parameters: stronger and closer to people, several times slower.
|
||||
Large,
|
||||
}
|
||||
|
||||
/// The strongest the small model plays (with the large one missing).
|
||||
pub const SMALL_MAX: u32 = 1800;
|
||||
|
||||
/// Measured (docs/research/maia-strength.md): Maia's rating input → her strength on
|
||||
/// the Lichess blitz scale, as she plays here (temperature 1, rare moves dropped).
|
||||
const SMALL: &[(u32, u32)] = &[
|
||||
(600, 1043),
|
||||
(800, 1154),
|
||||
(1100, 1333),
|
||||
(1300, 1426),
|
||||
(1500, 1485),
|
||||
(1700, 1563),
|
||||
(1900, 1632),
|
||||
(2100, 1683),
|
||||
(2300, 1737),
|
||||
(2600, 1767),
|
||||
];
|
||||
const LARGE: &[(u32, u32)] = &[
|
||||
(600, 1078),
|
||||
(1100, 1375),
|
||||
(1500, 1605),
|
||||
(1900, 1794),
|
||||
(2300, 1964),
|
||||
(2600, 2000),
|
||||
];
|
||||
|
||||
/// Above what a model plays choosing among the likely moves (temperature 1), it is made
|
||||
/// stronger by choosing more surely: measured strength at its top rating input → the
|
||||
/// temperature (0: always the most likely move).
|
||||
const SMALL_SURE: &[(u32, f32)] = &[(1767, 1.0), (1854, 0.5)];
|
||||
const LARGE_SURE: &[(u32, f32)] = &[(1976, 1.0), (2053, 0.5), (2126, 0.0)];
|
||||
|
||||
/// How surely `model` chooses its move to play at `strength` (1 below its top).
|
||||
pub fn temperature(model: Model, strength: u32) -> f32 {
|
||||
let table = match model {
|
||||
Model::Small => SMALL_SURE,
|
||||
Model::Large => LARGE_SURE,
|
||||
};
|
||||
let (first, last) = (table[0], table[table.len() - 1]);
|
||||
if strength <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
if strength >= last.0 {
|
||||
return last.1;
|
||||
}
|
||||
let i = table
|
||||
.iter()
|
||||
.position(|p| p.0 >= strength)
|
||||
.unwrap_or(table.len() - 1);
|
||||
let ((a_s, a_t), (b_s, b_t)) = (table[i - 1], table[i]);
|
||||
let k = (strength - a_s) as f32 / (b_s - a_s) as f32;
|
||||
a_t + k * (b_t - a_t)
|
||||
}
|
||||
|
||||
/// The rating to give `model` for it to play at `strength` (between the measured
|
||||
/// points, in proportion; outside them, the nearest).
|
||||
pub fn rating_input(model: Model, strength: u32) -> u32 {
|
||||
let table = match model {
|
||||
Model::Small => SMALL,
|
||||
Model::Large => LARGE,
|
||||
};
|
||||
let (first, last) = (table[0], table[table.len() - 1]);
|
||||
if strength <= first.1 {
|
||||
return first.0;
|
||||
}
|
||||
if strength >= last.1 {
|
||||
return last.0;
|
||||
}
|
||||
let i = table
|
||||
.iter()
|
||||
.position(|p| p.1 >= strength)
|
||||
.unwrap_or(table.len() - 1);
|
||||
let ((a_in, a_out), (b_in, b_out)) = (table[i - 1], table[i]);
|
||||
let t = f64::from(strength - a_out) / f64::from(b_out - a_out);
|
||||
(f64::from(a_in) + t * f64::from(b_in - a_in)).round() as u32
|
||||
}
|
||||
|
||||
/// The move to play from a prediction: a move less than a tenth as likely as the most
|
||||
/// likely one is not played (human mistakes, not accidents: a 2600 does not hang the
|
||||
/// queen one time in five thousand), the rest drawn at `temperature`. `random` is in
|
||||
/// [0, 1).
|
||||
pub fn choose(prediction: &Prediction, temperature: f32, random: f32) -> Option<Move> {
|
||||
let top = prediction.moves.first().map_or(0.0, |(_, p)| *p);
|
||||
let likely = Prediction {
|
||||
moves: prediction
|
||||
.moves
|
||||
.iter()
|
||||
.filter(|(_, p)| *p >= 0.1 * top)
|
||||
.cloned()
|
||||
.collect(),
|
||||
wdl: prediction.wdl,
|
||||
};
|
||||
pick(&likely, temperature, random)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn strength_turns_into_the_rating_to_give() {
|
||||
// The measured points themselves, in proportion between them, the ends held.
|
||||
assert_eq!(rating_input(Model::Large, 1605), 1500);
|
||||
assert_eq!(rating_input(Model::Large, 2000), 2600);
|
||||
assert_eq!(rating_input(Model::Small, 1485), 1500);
|
||||
assert_eq!(rating_input(Model::Small, SMALL_MAX), 2600);
|
||||
assert_eq!(rating_input(Model::Small, 900), 600);
|
||||
// Above the top input: surer choices, down to the most likely move.
|
||||
assert_eq!(temperature(Model::Large, 1900), 1.0);
|
||||
assert!((temperature(Model::Large, 2053) - 0.5).abs() < 1e-6);
|
||||
assert_eq!(temperature(Model::Large, 2200), 0.0);
|
||||
assert!(temperature(Model::Small, SMALL_MAX) < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rare_moves_are_not_chosen() {
|
||||
use shakmaty::{Chess, Position};
|
||||
let pos = Chess::default();
|
||||
let moves = pos.legal_moves();
|
||||
let p = Prediction {
|
||||
moves: vec![(moves[0], 0.9), (moves[1], 0.05)],
|
||||
wdl: [0.0; 3],
|
||||
};
|
||||
// Whatever the draw: under a tenth of the best is never played.
|
||||
for r in [0.0, 0.5, 0.99] {
|
||||
assert_eq!(choose(&p, 5.0, r), Some(moves[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue