init
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .flake8 +4 -0
- .gitattributes +7 -0
- .github/ISSUE_TEMPLATE/issue.md +22 -0
- .github/actions/get-version/action.yml +17 -0
- .github/actions/setup-python-uv/action.yml +35 -0
- .github/workflows/stale.yml +21 -0
- .github/workflows/test_and_build.yaml +218 -0
- .gitignore +158 -0
- .python_version +1 -0
- .vscode/launch.json +15 -0
- .vscode/settings.json +5 -0
- CONTRIBUTIONS.md +79 -0
- ENGINE.md +74 -0
- INSTALL.md +161 -0
- LICENSE +40 -0
- QA.txt +63 -0
- README.md +253 -0
- THEMES.md +96 -0
- i18n.py +125 -0
- katrain.py +4 -0
- katrain/KataGo/OpenCL.dll +3 -0
- katrain/KataGo/__init__.py +0 -0
- katrain/KataGo/analysis_config.cfg +240 -0
- katrain/KataGo/cacert.pem +0 -0
- katrain/KataGo/contribute_config.cfg +94 -0
- katrain/KataGo/katago +3 -0
- katrain/KataGo/katago.exe +3 -0
- katrain/KataGo/libcrypto-1_1-x64.dll +3 -0
- katrain/KataGo/libcrypto-3-x64.dll +3 -0
- katrain/KataGo/libssl-1_1-x64.dll +3 -0
- katrain/KataGo/libssl-3-x64.dll +3 -0
- katrain/KataGo/libz.dll +3 -0
- katrain/KataGo/libzip.dll +3 -0
- katrain/KataGo/msvcp140.dll +3 -0
- katrain/KataGo/msvcp140_1.dll +3 -0
- katrain/KataGo/msvcp140_2.dll +3 -0
- katrain/KataGo/msvcp140_atomic_wait.dll +3 -0
- katrain/KataGo/msvcp140_codecvt_ids.dll +3 -0
- katrain/KataGo/vcruntime140.dll +3 -0
- katrain/KataGo/vcruntime140_1.dll +3 -0
- katrain/__init__.py +0 -0
- katrain/__main__.py +984 -0
- katrain/config.json +242 -0
- katrain/core/__init__.py +0 -0
- katrain/core/ai.py +1460 -0
- katrain/core/base_katrain.py +189 -0
- katrain/core/constants.py +280 -0
- katrain/core/contribute_engine.py +302 -0
- katrain/core/engine.py +471 -0
- katrain/core/game.py +803 -0
.flake8
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[flake8]
|
| 2 |
+
# line length, space before binary op, line break before binary op, import not at top
|
| 3 |
+
ignore = E501, E203, W503, E402
|
| 4 |
+
exclude = .git,__pycache__,build,dist
|
.gitattributes
CHANGED
|
@@ -1,4 +1,11 @@
|
|
| 1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
katrain/KataGo/katago filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.exe filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.dll filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.icns filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.otf filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ttf filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.ico filter=lfs diff=lfs merge=lfs -text
|
| 9 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 10 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 11 |
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
.github/ISSUE_TEMPLATE/issue.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: Issue
|
| 3 |
+
about: Standard issue template
|
| 4 |
+
title: ''
|
| 5 |
+
labels: ''
|
| 6 |
+
assignees: ''
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
Please read and fill in the appropriate template
|
| 11 |
+
|
| 12 |
+
# I have a question about using the program, or need technical assistance
|
| 13 |
+
|
| 14 |
+
Please use the Computer Go Community Discord (#gui) : http://discord.gg/AjTPFpN
|
| 15 |
+
|
| 16 |
+
# I have a bug report
|
| 17 |
+
|
| 18 |
+
Please include details of the settings you use, steps to reproduce the problem, and console output.
|
| 19 |
+
|
| 20 |
+
# I have a feature request
|
| 21 |
+
|
| 22 |
+
Go ahead, but keep in mind that the program is mostly in maintenance mode, and big changes are unlikely.
|
.github/actions/get-version/action.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: 'Get KaTrain Version'
|
| 2 |
+
description: 'Extract version from katrain.core.constants'
|
| 3 |
+
outputs:
|
| 4 |
+
version:
|
| 5 |
+
description: 'The version string'
|
| 6 |
+
value: ${{ steps.version.outputs.version }}
|
| 7 |
+
|
| 8 |
+
runs:
|
| 9 |
+
using: 'composite'
|
| 10 |
+
steps:
|
| 11 |
+
- name: Get app version
|
| 12 |
+
id: version
|
| 13 |
+
shell: bash
|
| 14 |
+
run: |
|
| 15 |
+
version=$(python -c 'from katrain.core.constants import VERSION; print(VERSION)')
|
| 16 |
+
echo "version=$version" >> "$GITHUB_OUTPUT"
|
| 17 |
+
echo "KATRAIN_VERSION=$version" >> "$GITHUB_ENV"
|
.github/actions/setup-python-uv/action.yml
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: 'Setup Python and uv'
|
| 2 |
+
description: 'Common setup for Python, uv, and dependencies'
|
| 3 |
+
inputs:
|
| 4 |
+
python-version:
|
| 5 |
+
description: 'Python version to set up'
|
| 6 |
+
required: false
|
| 7 |
+
default: '3.11'
|
| 8 |
+
sync-groups:
|
| 9 |
+
description: 'uv sync groups'
|
| 10 |
+
required: false
|
| 11 |
+
default: ''
|
| 12 |
+
|
| 13 |
+
runs:
|
| 14 |
+
using: 'composite'
|
| 15 |
+
steps:
|
| 16 |
+
- uses: actions/checkout@v4
|
| 17 |
+
|
| 18 |
+
- name: Set up Python
|
| 19 |
+
uses: actions/setup-python@v5
|
| 20 |
+
with:
|
| 21 |
+
python-version: ${{ inputs.python-version }}
|
| 22 |
+
|
| 23 |
+
- name: Install uv
|
| 24 |
+
uses: astral-sh/setup-uv@v5
|
| 25 |
+
with:
|
| 26 |
+
version: "0.7.8"
|
| 27 |
+
|
| 28 |
+
- name: Install dependencies
|
| 29 |
+
shell: bash
|
| 30 |
+
run: |
|
| 31 |
+
if [ -n "${{ inputs.sync-groups }}" ]; then
|
| 32 |
+
uv sync --group ${{ inputs.sync-groups }}
|
| 33 |
+
else
|
| 34 |
+
uv sync
|
| 35 |
+
fi
|
.github/workflows/stale.yml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "Close stale issues and PRs"
|
| 2 |
+
on:
|
| 3 |
+
schedule:
|
| 4 |
+
- cron: "30 1 * * *"
|
| 5 |
+
|
| 6 |
+
jobs:
|
| 7 |
+
stale:
|
| 8 |
+
runs-on: ubuntu-latest
|
| 9 |
+
permissions:
|
| 10 |
+
pull-requests: write
|
| 11 |
+
issues: write
|
| 12 |
+
steps:
|
| 13 |
+
- uses: actions/stale@v8
|
| 14 |
+
with:
|
| 15 |
+
operations-per-run: 200
|
| 16 |
+
stale-issue-message: "This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 10 days."
|
| 17 |
+
close-issue-message: "This issue was closed because it has been stalled for 30 days with no activity."
|
| 18 |
+
days-before-stale: 90
|
| 19 |
+
days-before-close: 30
|
| 20 |
+
stale-pr-message: "This PR is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 10 days."
|
| 21 |
+
close-pr-message: "This PR was closed because it has been stalled for 30 days with no activity."
|
.github/workflows/test_and_build.yaml
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# .github/workflows/test_and_build.yml
|
| 2 |
+
|
| 3 |
+
name: Test, Build, and Release
|
| 4 |
+
|
| 5 |
+
on:
|
| 6 |
+
pull_request:
|
| 7 |
+
workflow_dispatch:
|
| 8 |
+
inputs:
|
| 9 |
+
create_release:
|
| 10 |
+
description: 'Create draft release'
|
| 11 |
+
required: true
|
| 12 |
+
default: false
|
| 13 |
+
type: boolean
|
| 14 |
+
publish_pypi:
|
| 15 |
+
description: 'Publish to PyPI'
|
| 16 |
+
required: true
|
| 17 |
+
default: false
|
| 18 |
+
type: boolean
|
| 19 |
+
|
| 20 |
+
concurrency:
|
| 21 |
+
group: ${{ github.workflow }}-${{ github.ref }}
|
| 22 |
+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
| 23 |
+
|
| 24 |
+
jobs:
|
| 25 |
+
# This job runs first to prepare shared information for other jobs.
|
| 26 |
+
prepare:
|
| 27 |
+
runs-on: ubuntu-latest
|
| 28 |
+
outputs:
|
| 29 |
+
version: ${{ steps.version.outputs.version }}
|
| 30 |
+
steps:
|
| 31 |
+
- name: Checkout code
|
| 32 |
+
uses: actions/checkout@v4
|
| 33 |
+
|
| 34 |
+
- name: Get project version
|
| 35 |
+
id: version
|
| 36 |
+
uses: ./.github/actions/get-version
|
| 37 |
+
|
| 38 |
+
test:
|
| 39 |
+
needs: prepare
|
| 40 |
+
runs-on: ubuntu-latest
|
| 41 |
+
strategy:
|
| 42 |
+
fail-fast: false
|
| 43 |
+
matrix:
|
| 44 |
+
python-version: ['3.9', '3.12', '3.13']
|
| 45 |
+
steps:
|
| 46 |
+
- name: Checkout code
|
| 47 |
+
uses: actions/checkout@v4
|
| 48 |
+
|
| 49 |
+
- name: Setup Python and uv
|
| 50 |
+
uses: ./.github/actions/setup-python-uv
|
| 51 |
+
with:
|
| 52 |
+
python-version: ${{ matrix.python-version }}
|
| 53 |
+
sync-groups: dev
|
| 54 |
+
|
| 55 |
+
- name: Run tests
|
| 56 |
+
run: uv run pytest tests
|
| 57 |
+
|
| 58 |
+
- name: Check I18N conversion
|
| 59 |
+
run: uv run python i18n.py -todo
|
| 60 |
+
|
| 61 |
+
- name: Check package can be built
|
| 62 |
+
run: uv build
|
| 63 |
+
|
| 64 |
+
build-windows:
|
| 65 |
+
needs: [prepare, test]
|
| 66 |
+
runs-on: windows-latest
|
| 67 |
+
env:
|
| 68 |
+
KATRAIN_VERSION: ${{ needs.prepare.outputs.version }}
|
| 69 |
+
steps:
|
| 70 |
+
- name: Checkout code
|
| 71 |
+
uses: actions/checkout@v4
|
| 72 |
+
|
| 73 |
+
- name: Setup Python, uv
|
| 74 |
+
uses: ./.github/actions/setup-python-uv
|
| 75 |
+
|
| 76 |
+
- name: Build executables with PyInstaller
|
| 77 |
+
run: uv run pyinstaller spec/katrain.spec --clean --noconfirm
|
| 78 |
+
shell: powershell
|
| 79 |
+
|
| 80 |
+
- name: Create archives
|
| 81 |
+
run: |
|
| 82 |
+
New-Item -ItemType Directory -Path "windows_exe" -Force
|
| 83 |
+
|
| 84 |
+
# Copy the standalone KaTrain.exe
|
| 85 |
+
if (Test-Path "dist/KaTrain.exe") {
|
| 86 |
+
Copy-Item "dist/KaTrain.exe" "windows_exe/KaTrain.exe"
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
# Create KaTrain.zip with debug executable inside
|
| 90 |
+
if (Test-Path "dist/KaTrain") {
|
| 91 |
+
# Copy the debug executable into the main KaTrain folder
|
| 92 |
+
if (Test-Path "dist/DebugKaTrain/KaTrain.exe") {
|
| 93 |
+
Copy-Item "dist/DebugKaTrain/KaTrain.exe" "dist/KaTrain/debugkatrain.exe"
|
| 94 |
+
}
|
| 95 |
+
# Create the zip file
|
| 96 |
+
Compress-Archive -Path "dist/KaTrain" -DestinationPath "windows_exe/KaTrain.zip"
|
| 97 |
+
}
|
| 98 |
+
shell: powershell
|
| 99 |
+
|
| 100 |
+
- name: Upload Windows artifacts
|
| 101 |
+
uses: actions/upload-artifact@v4
|
| 102 |
+
with:
|
| 103 |
+
name: KaTrainWindows-${{ env.KATRAIN_VERSION }}
|
| 104 |
+
path: windows_exe
|
| 105 |
+
|
| 106 |
+
build-macos:
|
| 107 |
+
needs: [prepare, test]
|
| 108 |
+
runs-on: macos-latest
|
| 109 |
+
env:
|
| 110 |
+
KATRAIN_VERSION: ${{ needs.prepare.outputs.version }}
|
| 111 |
+
steps:
|
| 112 |
+
- name: Checkout code
|
| 113 |
+
uses: actions/checkout@v4
|
| 114 |
+
|
| 115 |
+
- name: Setup Python, uv, and PyInstaller
|
| 116 |
+
uses: ./.github/actions/setup-python-uv
|
| 117 |
+
with:
|
| 118 |
+
install-pyinstaller: 'true'
|
| 119 |
+
|
| 120 |
+
- name: Install macOS dependencies
|
| 121 |
+
run: |
|
| 122 |
+
brew update
|
| 123 |
+
brew install libzip
|
| 124 |
+
brew install --build-from-source sdl2 sdl2_image sdl2_ttf sdl2_mixer
|
| 125 |
+
|
| 126 |
+
- name: Build KataGo
|
| 127 |
+
run: |
|
| 128 |
+
rm -f katrain/KataGo/katago katrain/KataGo/*.dll katrain/KataGo/katago.exe
|
| 129 |
+
git clone --depth 1 --branch stable https://github.com/lightvector/KataGo.git ../KataGo
|
| 130 |
+
pushd ../KataGo/cpp
|
| 131 |
+
cmake . -DUSE_BACKEND=OPENCL -DBUILD_DISTRIBUTED=1
|
| 132 |
+
make -j$(sysctl -n hw.ncpu)
|
| 133 |
+
cp katago ../../katrain/katrain/KataGo/katago-osx
|
| 134 |
+
popd
|
| 135 |
+
|
| 136 |
+
- name: Build app with PyInstaller
|
| 137 |
+
env:
|
| 138 |
+
KIVY_HEADLESS: 1
|
| 139 |
+
KIVY_NO_WINDOW: 1
|
| 140 |
+
KIVY_GL_BACKEND: mock
|
| 141 |
+
run: uv run pyinstaller spec/katrain.spec --clean --noconfirm
|
| 142 |
+
|
| 143 |
+
- name: Sign the app (ad-hoc)
|
| 144 |
+
run: codesign --force --deep --sign - dist/KaTrain.app
|
| 145 |
+
|
| 146 |
+
- name: Create DMG
|
| 147 |
+
run: |
|
| 148 |
+
mkdir -p dmg_temp
|
| 149 |
+
cp -R dist/KaTrain.app dmg_temp/
|
| 150 |
+
ln -s /Applications dmg_temp/Applications
|
| 151 |
+
hdiutil create -volname "KaTrain ${{ env.KATRAIN_VERSION }}" \
|
| 152 |
+
-srcfolder dmg_temp \
|
| 153 |
+
-ov \
|
| 154 |
+
-format UDZO \
|
| 155 |
+
"KaTrain-${{ env.KATRAIN_VERSION }}.dmg"
|
| 156 |
+
mkdir -p osx_app
|
| 157 |
+
mv "KaTrain-${{ env.KATRAIN_VERSION }}.dmg" osx_app/
|
| 158 |
+
|
| 159 |
+
- name: Upload macOS artifacts
|
| 160 |
+
uses: actions/upload-artifact@v4
|
| 161 |
+
with:
|
| 162 |
+
name: KaTrainMacOS-${{ env.KATRAIN_VERSION }}
|
| 163 |
+
path: osx_app
|
| 164 |
+
|
| 165 |
+
# This job publishes the package to PyPI.
|
| 166 |
+
publish-pypi:
|
| 167 |
+
needs: test
|
| 168 |
+
runs-on: ubuntu-latest
|
| 169 |
+
if: github.event_name == 'workflow_dispatch' && github.event.inputs.publish_pypi == 'true'
|
| 170 |
+
steps:
|
| 171 |
+
- name: Checkout code
|
| 172 |
+
uses: actions/checkout@v4
|
| 173 |
+
|
| 174 |
+
- name: Setup Python and uv
|
| 175 |
+
uses: ./.github/actions/setup-python-uv
|
| 176 |
+
with:
|
| 177 |
+
sync-groups: dev
|
| 178 |
+
|
| 179 |
+
- name: Finalize I18N for publishing
|
| 180 |
+
run: uv run python i18n.py
|
| 181 |
+
|
| 182 |
+
- name: Build and publish to PyPI
|
| 183 |
+
env:
|
| 184 |
+
UV_PUBLISH_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
| 185 |
+
run: |
|
| 186 |
+
uv build
|
| 187 |
+
uv publish --verbose
|
| 188 |
+
|
| 189 |
+
# This job creates a draft release on GitHub.
|
| 190 |
+
create-release:
|
| 191 |
+
needs: [prepare, build-windows, build-macos]
|
| 192 |
+
runs-on: ubuntu-latest
|
| 193 |
+
if: github.event_name == 'workflow_dispatch' && github.event.inputs.create_release == 'true'
|
| 194 |
+
permissions:
|
| 195 |
+
contents: write # Required for softprops/action-gh-release
|
| 196 |
+
steps:
|
| 197 |
+
- name: Download all build artifacts
|
| 198 |
+
uses: actions/download-artifact@v4
|
| 199 |
+
with:
|
| 200 |
+
path: ./artifacts
|
| 201 |
+
pattern: KaTrain*
|
| 202 |
+
merge-multiple: true
|
| 203 |
+
|
| 204 |
+
- name: Create Draft Release
|
| 205 |
+
uses: softprops/action-gh-release@v2
|
| 206 |
+
with:
|
| 207 |
+
tag_name: "v${{ needs.prepare.outputs.version }}"
|
| 208 |
+
name: "KaTrain v${{ needs.prepare.outputs.version }}"
|
| 209 |
+
body: |
|
| 210 |
+
## KaTrain v${{ needs.prepare.outputs.version }}
|
| 211 |
+
Auto-generated draft release from the latest main branch.
|
| 212 |
+
|
| 213 |
+
### Downloads
|
| 214 |
+
- **Windows**: Download the `.exe` files or `.zip` folders.
|
| 215 |
+
- **macOS**: Download the `.dmg` file.
|
| 216 |
+
files: ./artifacts/*
|
| 217 |
+
draft: true
|
| 218 |
+
prerelease: false
|
.gitignore
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
dist_sgf
|
| 2 |
+
sgftest
|
| 3 |
+
|
| 4 |
+
# additions
|
| 5 |
+
KataGoData
|
| 6 |
+
katrain/KataGo/KataGoData
|
| 7 |
+
experiments
|
| 8 |
+
.idea
|
| 9 |
+
.buildozer
|
| 10 |
+
bin
|
| 11 |
+
gtp.log
|
| 12 |
+
log.txt
|
| 13 |
+
sgfout
|
| 14 |
+
sgf_selfplay
|
| 15 |
+
sgf_ogs
|
| 16 |
+
log*
|
| 17 |
+
tmp.pickle
|
| 18 |
+
my
|
| 19 |
+
logs
|
| 20 |
+
callgrind.*
|
| 21 |
+
profile*
|
| 22 |
+
cpp/out
|
| 23 |
+
.vs
|
| 24 |
+
dist_sgf
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# debug
|
| 28 |
+
outdated_log.txt
|
| 29 |
+
|
| 30 |
+
# too big
|
| 31 |
+
models/*.bin.gz
|
| 32 |
+
|
| 33 |
+
# standard python ignore
|
| 34 |
+
# Byte-compiled / optimized / DLL files
|
| 35 |
+
__pycache__/
|
| 36 |
+
*.py[cod]
|
| 37 |
+
*$py.class
|
| 38 |
+
|
| 39 |
+
# C extensions
|
| 40 |
+
*.so
|
| 41 |
+
|
| 42 |
+
# Distribution / packaging
|
| 43 |
+
.Python
|
| 44 |
+
build/
|
| 45 |
+
develop-eggs/
|
| 46 |
+
dist/
|
| 47 |
+
downloads/
|
| 48 |
+
eggs/
|
| 49 |
+
.eggs/
|
| 50 |
+
lib/
|
| 51 |
+
lib64/
|
| 52 |
+
parts/
|
| 53 |
+
sdist/
|
| 54 |
+
var/
|
| 55 |
+
wheels/
|
| 56 |
+
pip-wheel-metadata/
|
| 57 |
+
share/python-wheels/
|
| 58 |
+
*.egg-info/
|
| 59 |
+
.installed.cfg
|
| 60 |
+
*.egg
|
| 61 |
+
MANIFEST
|
| 62 |
+
|
| 63 |
+
# PyInstaller
|
| 64 |
+
# Usually these files are written by a python script from a template
|
| 65 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 66 |
+
*.manifest
|
| 67 |
+
# *.spec
|
| 68 |
+
|
| 69 |
+
# Installer logs
|
| 70 |
+
pip-log.txt
|
| 71 |
+
pip-delete-this-directory.txt
|
| 72 |
+
|
| 73 |
+
# Unit test / coverage reports
|
| 74 |
+
htmlcov/
|
| 75 |
+
.tox/
|
| 76 |
+
.nox/
|
| 77 |
+
.coverage
|
| 78 |
+
.coverage.*
|
| 79 |
+
.cache
|
| 80 |
+
nosetests.xml
|
| 81 |
+
coverage.xml
|
| 82 |
+
*.cover
|
| 83 |
+
*.py,cover
|
| 84 |
+
.hypothesis/
|
| 85 |
+
.pytest_cache/
|
| 86 |
+
|
| 87 |
+
# Django stuff:
|
| 88 |
+
*.log
|
| 89 |
+
local_settings.py
|
| 90 |
+
db.sqlite3
|
| 91 |
+
db.sqlite3-journal
|
| 92 |
+
|
| 93 |
+
# Flask stuff:
|
| 94 |
+
instance/
|
| 95 |
+
.webassets-cache
|
| 96 |
+
|
| 97 |
+
# Scrapy stuff:
|
| 98 |
+
.scrapy
|
| 99 |
+
|
| 100 |
+
# Sphinx documentation
|
| 101 |
+
docs/_build/
|
| 102 |
+
|
| 103 |
+
# PyBuilder
|
| 104 |
+
target/
|
| 105 |
+
|
| 106 |
+
# Jupyter Notebook
|
| 107 |
+
.ipynb_checkpoints
|
| 108 |
+
|
| 109 |
+
# IPython
|
| 110 |
+
profile_default/
|
| 111 |
+
ipython_config.py
|
| 112 |
+
|
| 113 |
+
# pyenv
|
| 114 |
+
.python-version
|
| 115 |
+
|
| 116 |
+
# pipenv
|
| 117 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 118 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 119 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 120 |
+
# install all needed dependencies.
|
| 121 |
+
#Pipfile.lock
|
| 122 |
+
|
| 123 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
| 124 |
+
__pypackages__/
|
| 125 |
+
|
| 126 |
+
# Celery stuff
|
| 127 |
+
celerybeat-schedule
|
| 128 |
+
celerybeat.pid
|
| 129 |
+
|
| 130 |
+
# SageMath parsed files
|
| 131 |
+
*.sage.py
|
| 132 |
+
|
| 133 |
+
# Environments
|
| 134 |
+
.env
|
| 135 |
+
.venv
|
| 136 |
+
env/
|
| 137 |
+
venv/
|
| 138 |
+
ENV/
|
| 139 |
+
env.bak/
|
| 140 |
+
venv.bak/
|
| 141 |
+
|
| 142 |
+
# Spyder project settings
|
| 143 |
+
.spyderproject
|
| 144 |
+
.spyproject
|
| 145 |
+
|
| 146 |
+
# Rope project settings
|
| 147 |
+
.ropeproject
|
| 148 |
+
|
| 149 |
+
# mkdocs documentation
|
| 150 |
+
/site
|
| 151 |
+
|
| 152 |
+
# mypy
|
| 153 |
+
.mypy_cache/
|
| 154 |
+
.dmypy.json
|
| 155 |
+
dmypy.json
|
| 156 |
+
|
| 157 |
+
# Pyre type checker
|
| 158 |
+
.pyre/
|
.python_version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.12
|
.vscode/launch.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
// Use IntelliSense to learn about possible attributes.
|
| 3 |
+
// Hover to view descriptions of existing attributes.
|
| 4 |
+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
| 5 |
+
"version": "0.2.0",
|
| 6 |
+
"configurations": [
|
| 7 |
+
{
|
| 8 |
+
"name": "Python Debugger: Current File",
|
| 9 |
+
"type": "debugpy",
|
| 10 |
+
"request": "launch",
|
| 11 |
+
"program": "${file}",
|
| 12 |
+
"console": "integratedTerminal"
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
.vscode/settings.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"python-envs.defaultEnvManager": "ms-python.python:conda",
|
| 3 |
+
"python-envs.defaultPackageManager": "ms-python.python:conda",
|
| 4 |
+
"python-envs.pythonProjects": []
|
| 5 |
+
}
|
CONTRIBUTIONS.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing
|
| 2 |
+
|
| 3 |
+
If you are a new contributor wanting to make a larger contribution,
|
| 4 |
+
please first discuss the change you wish to make via
|
| 5 |
+
an issue, reddit or discord before making a pull request.
|
| 6 |
+
|
| 7 |
+
## Python contributions
|
| 8 |
+
|
| 9 |
+
Python code is formatted using [black](https://github.com/psf/black) with the settings `-l 120`.
|
| 10 |
+
This is not enforced, and contributions with incorrect formatting will be accepted, but formatting this way is appreciated.
|
| 11 |
+
|
| 12 |
+
## Translations
|
| 13 |
+
|
| 14 |
+
### Contributing to an existing translation
|
| 15 |
+
|
| 16 |
+
* Go [here](https://github.com/sanderland/katrain/blob/master/katrain/i18n/locales/) and locate the `.po` file for your language.
|
| 17 |
+
* Alternatively, find the same file in the branch for the next version.
|
| 18 |
+
* Correct the relevant `msgstr` entries.
|
| 19 |
+
|
| 20 |
+
### Adding a translation
|
| 21 |
+
|
| 22 |
+
Adding a translation requires making a new `.po` file with entries for that languages.
|
| 23 |
+
|
| 24 |
+
* Copy the [English .po file](https://github.com/sanderland/katrain/blob/master/katrain/i18n/locales/en/LC_MESSAGES/katrain.po)
|
| 25 |
+
* Change all the `msgstr` entries to your target language.
|
| 26 |
+
* Note that anything between `{}` should be left as-is.
|
| 27 |
+
* The information at the top of the file should also not be translated.
|
| 28 |
+
|
| 29 |
+
You can send me the resulting `.po` file, and I will integrate it into the program.
|
| 30 |
+
|
| 31 |
+
# Contributors
|
| 32 |
+
|
| 33 |
+
## Primary author and project maintainer:
|
| 34 |
+
|
| 35 |
+
[Sander Land](https://github.com/sanderland/)
|
| 36 |
+
|
| 37 |
+
## Contributors
|
| 38 |
+
|
| 39 |
+
Many thanks to these additional authors:
|
| 40 |
+
|
| 41 |
+
* Matthew Allred ("Kameone") for design of the v1.1 UI, macOS installation instructions, and working on promotion and YouTube videos.
|
| 42 |
+
* "bale-go" for development and continued work on the 'calibrated rank' AI and rank estimation algorithm.
|
| 43 |
+
* "Dontbtme" for detailed feedback and early testing of v1.0+.
|
| 44 |
+
* "nowoowoo" for a fix to the parser for SGF files with extra line breaks.
|
| 45 |
+
* "nimets123" for the timer sound effects and board/stone graphics.
|
| 46 |
+
* Jordan Seaward for the stone sound effects.
|
| 47 |
+
* "fohristiwhirl" for the Gibo and NGF formats parsing code.
|
| 48 |
+
* "kaorahi" for bug fixes, SGF parser improvements, and tsumego frame code.
|
| 49 |
+
* "ajkenny84" for the red-green colourblind theme.
|
| 50 |
+
* Lukasz Wierzbowski for the ability to paste urls for sgfs and helping fix alt-gr issues.
|
| 51 |
+
* Carton He for contributions to sgf parsing and handling.
|
| 52 |
+
* "blamarche" for adding the board coordinates toggle.
|
| 53 |
+
* "pdeblanc" for adding the ancient chinese scoring option, fixing a bug in query termination, and high precision score display.
|
| 54 |
+
* "LiamHz" for adding the 'back to main branch' keyboard shortcut.
|
| 55 |
+
* "xiaoyifang" for adding the reset analysis option, feature to save options on the loading screen, and scrolling through variations.
|
| 56 |
+
* "electricRGB" for help with adding configurable keyboard shortcuts.
|
| 57 |
+
* "milescrawford" for work on restyling the territory estimate.
|
| 58 |
+
* "Funkenschlag1" for capturing stones sound and implementation, and board rotation.
|
| 59 |
+
* "waltheri" for one of the wooden board textures.
|
| 60 |
+
* Jacob Minsky ("jacobm-tech") for various contributions including analysis move range and improvements to territory display.
|
| 61 |
+
|
| 62 |
+
## Translators
|
| 63 |
+
|
| 64 |
+
Many thanks to the following contributors for translations.
|
| 65 |
+
|
| 66 |
+
* French: "Dontbtme" with contributions from "wonderingabout"
|
| 67 |
+
* Korean: "isty2e"
|
| 68 |
+
* German: "nimets123", "trohde", "Harleqin" and "Sovereign"
|
| 69 |
+
* Spanish: Sergio Villegas ("serpiente") with contributions from the Spanish OGS community
|
| 70 |
+
* Russian: Dmitry Ivankov and Alexander Kiselev
|
| 71 |
+
* Simplified Chinese: Qing Mu with contributions from "Medwin" and Viktor Lin
|
| 72 |
+
* Japanese: "kaorahi"
|
| 73 |
+
* Traditional Chinese: "Tony-Liou" with contributions from Ching-yu Lin
|
| 74 |
+
|
| 75 |
+
## Additional thanks to
|
| 76 |
+
|
| 77 |
+
* David Wu ("lightvector") for creating KataGo and providing assistance with making the most of KataGo's amazing capabilities.
|
| 78 |
+
* "세븐틴" for including KaTrain in the Baduk Megapack and making explanatory YouTube videos in Korean.
|
| 79 |
+
|
ENGINE.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# KataGo troubleshooting
|
| 2 |
+
|
| 3 |
+
This page lists common ways in which the provided KataGo fails to work out of the box, and how to resolve these issues.
|
| 4 |
+
If you find your problem is not in here, you can ask on the [Leela Zero & Friends Discord](http://discord.gg/AjTPFpN) (use the #gui channel),
|
| 5 |
+
providing detailed information about your error.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
* [General](#General)
|
| 9 |
+
* [GPU vs CPU](#CPU)
|
| 10 |
+
* [Windows specific help](#Windows)
|
| 11 |
+
* [MacOS specific help](#Mac)
|
| 12 |
+
* [Linux specific help](#Linux)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
## <a name="General"></a> General
|
| 17 |
+
|
| 18 |
+
### <a name="CPU"></a> GPU vs CPU
|
| 19 |
+
|
| 20 |
+
The standard executables assume you have a compatible graphics card (GPU).
|
| 21 |
+
If you don't, KataGo will fail to start in ways that are difficult for KaTrain to pick up.
|
| 22 |
+
|
| 23 |
+
On Windows and Linux, you should be able to resolve this by:
|
| 24 |
+
|
| 25 |
+
* Going to general and engine settings (F8)
|
| 26 |
+
* Click 'download katago versions' and wait for downloads to finish.
|
| 27 |
+
* Select a CPU based KataGo version (named 'Eigen' after the library it uses).
|
| 28 |
+
|
| 29 |
+
Keep in mind that a CPU based engine can be significantly slower, and you may want to set your maximum number of
|
| 30 |
+
visits to a lower number to compensate for this.
|
| 31 |
+
|
| 32 |
+
### <a name="Models"></a> KataGo model versions
|
| 33 |
+
|
| 34 |
+
KataGo models have changed over time, and selecting an older executable with a newer model can lead to errors.
|
| 35 |
+
Of the provided binaries, this is typically the case for the 1.6.1 'bigger boards' binary, which should
|
| 36 |
+
only be used with the standard 15/20/30/40 block models, and not the newer distributed training models.
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
## <a name="Mac"></a><img src="https://upload.wikimedia.org/wikipedia/commons/8/8a/Apple_Logo.svg" alt="macOs" height="35"/> For macOS users
|
| 40 |
+
|
| 41 |
+
### Running from source
|
| 42 |
+
|
| 43 |
+
Make sure you `brew install katago` or set the engine path to your own KataGo binary, as there is no executable included.
|
| 44 |
+
|
| 45 |
+
### New Macs with M1 architecture
|
| 46 |
+
|
| 47 |
+
Make sure you `brew install katago` as the provided executable does not work on rosetta.
|
| 48 |
+
|
| 49 |
+
### Getting more information about errors
|
| 50 |
+
|
| 51 |
+
On macOS, the .app distributable will not show a console, so you will need install using `pip` to see the console window.
|
| 52 |
+
|
| 53 |
+
## <a name="Windows"></a><img src="https://upload.wikimedia.org/wikipedia/commons/5/5f/Windows_logo_-_2012.svg" alt="Windows" height="35"/> For Windows users
|
| 54 |
+
|
| 55 |
+
### Getting more information about errors
|
| 56 |
+
|
| 57 |
+
Run DebugKaTrain.exe, which is released in the .zip file distributable in releases. This will show a console window
|
| 58 |
+
which typically tells you more.
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
## <a name="Linux"></a><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Linux_Logo_in_Linux_Libertine_Font.svg" alt="Linux" height="35"/> For Linux users
|
| 62 |
+
|
| 63 |
+
### libzip compatibility
|
| 64 |
+
|
| 65 |
+
The most common KataGo issue relates to incompatible library versions, leading to an "Error 127".
|
| 66 |
+
|
| 67 |
+
* A good alternative is to go [here](https://github.com/lightvector/KataGo) and compile KataGo yourself.
|
| 68 |
+
* Installing dependencies mentioned [here](INSTALL.md#LinuxTrouble) may also resolve certain issues with KataGo or the gui.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
### Getting more information about errors
|
| 72 |
+
|
| 73 |
+
* Check the terminal output around startup time.
|
| 74 |
+
* Start KataGo by itself using `katrain/KataGo/katago` when running from source and check output.
|
INSTALL.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# KaTrain Installation
|
| 2 |
+
|
| 3 |
+
* [Quick install guide for MacOS](#MacQuick)
|
| 4 |
+
* [Troubleshooting and installation from sources](#MacSources)
|
| 5 |
+
* [Quick install guide for Windows](#WindowsQuick)
|
| 6 |
+
* [Troubleshooting and installation from sources](#WindowsSources)
|
| 7 |
+
* [Quick install guide for Linux](#LinuxQuick)
|
| 8 |
+
* [Troubleshooting and installation from sources](#LinuxSources)
|
| 9 |
+
* [Configuring Multiple GPUS](#GPU)
|
| 10 |
+
* [Troubleshooting KataGo](#KataGo)
|
| 11 |
+
|
| 12 |
+
## <img src="https://upload.wikimedia.org/wikipedia/commons/8/8a/Apple_Logo.svg" alt="macOs" height="35"/> Installation for macOS users
|
| 13 |
+
|
| 14 |
+
### <a name="MacQuick"></a>Quick install guide
|
| 15 |
+
|
| 16 |
+
The easiest way to install is probably [brew](https://brew.sh/). Simply run `brew install katrain` and it will download and install the latest pre-built .app, and also install katago if needed.
|
| 17 |
+
|
| 18 |
+
You can also find downloadable .app files for macOS [here](https://github.com/sanderland/katrain/releases).
|
| 19 |
+
Simply download, unzip the file, mount the .dmg and drag the .app file to your application folder, everything is included.
|
| 20 |
+
The first time launching the application you may need to [control-click in finder to give permission for the 'unidentified' app to launch](https://support.apple.com/guide/mac-help/open-a-mac-app-from-an-unidentified-developer-mh40616/mac). This is simply a result of Apple charging $99/year to developers to be 'identified'.
|
| 21 |
+
|
| 22 |
+
Users with the last generation M1 macs with different architecture should then `brew install katago` in addition to this. KaTrain will automatically detect this KataGo binary.
|
| 23 |
+
|
| 24 |
+
### <a name="MacCommand"></a>Command line install guide
|
| 25 |
+
|
| 26 |
+
[Open a terminal](https://support.apple.com/guide/terminal/open-or-quit-terminal-apd5265185d-f365-44cb-8b09-71a064a42125/mac) and enter the following commands:
|
| 27 |
+
```bash
|
| 28 |
+
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
|
| 29 |
+
brew install python3
|
| 30 |
+
brew install katago
|
| 31 |
+
pip3 install katrain
|
| 32 |
+
```
|
| 33 |
+
Now you can start KaTrain by simply typing `katrain` in a terminal after adding it to your path.
|
| 34 |
+
|
| 35 |
+
These commands install [Homebrew](https://brew.sh), which simplifies installing packages,
|
| 36 |
+
followed by the programming language Python, the KataGo AI, and KaTrain itself.
|
| 37 |
+
|
| 38 |
+
To upgrade to a newer version, simply run `pip3 install -U katrain`
|
| 39 |
+
|
| 40 |
+
### <a name="MacSources"></a>Troubleshooting and Installation from sources
|
| 41 |
+
|
| 42 |
+
Installation from sources is essentially the same as for Linux, see [here](#LinuxSources),
|
| 43 |
+
note that you will still need to install your own KataGo, using brew or otherwise.
|
| 44 |
+
|
| 45 |
+
If you encounter SSL errors on downloading model files, you may need to follow [these](https://stackoverflow.com/questions/52805115/certificate-verify-failed-unable-to-get-local-issuer-certificate) instructions to fix your certificates.
|
| 46 |
+
|
| 47 |
+
## <img src="https://upload.wikimedia.org/wikipedia/commons/5/5f/Windows_logo_-_2012.svg" alt="Windows" height="35"/> Installation for Windows users
|
| 48 |
+
|
| 49 |
+
### <a name="WindowsQuick"></a>Quick install guide
|
| 50 |
+
|
| 51 |
+
You can find downloadable .exe files for windows [here](https://github.com/sanderland/katrain/releases).
|
| 52 |
+
Simply download and run, everything is included.
|
| 53 |
+
|
| 54 |
+
### <a name="WindowsSources"></a>Installation from sources
|
| 55 |
+
|
| 56 |
+
* Download the repository by clicking the green *Clone or download* on this page and *Download zip*. Extract the contents.
|
| 57 |
+
* Make sure you have a python installation, I will assume Anaconda (Python 3.9 or later), available [here](https://www.anaconda.com/products/individual#download-section).
|
| 58 |
+
* Open 'Anaconda prompt' from the start menu and navigate to where you extracted the zip file using the `cd <folder>` command.
|
| 59 |
+
* Execute the command `pip3 install .`
|
| 60 |
+
* Start the app by running `katrain` in the command prompt.
|
| 61 |
+
|
| 62 |
+
## <img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Linux_Logo_in_Linux_Libertine_Font.svg" alt="Linux" height="35"/> Installation for Linux users
|
| 63 |
+
|
| 64 |
+
### <a name="LinuxQuick"></a>Quick install guide
|
| 65 |
+
|
| 66 |
+
If you have a working Python 3.9 or later available, you should be able to simply:
|
| 67 |
+
|
| 68 |
+
* Run `pip3 install -U katrain` to install or upgrade.
|
| 69 |
+
* Run the program by executing `katrain` in a terminal.
|
| 70 |
+
|
| 71 |
+
### <a name="LinuxSources"></a>Installation from sources
|
| 72 |
+
|
| 73 |
+
This section describes how to install KaTrain from sources,
|
| 74 |
+
in case you want to run it in a local directory or have more control over the process.
|
| 75 |
+
It assumes you have a working Python 3.9+ installation.
|
| 76 |
+
|
| 77 |
+
* Open a terminal.
|
| 78 |
+
* Run the command `git clone https://github.com/sanderland/katrain.git` to download the repository and
|
| 79 |
+
change directory using `cd katrain`
|
| 80 |
+
* Run the command `pip3 install .` to install the package globally, or use `--user` to install locally.
|
| 81 |
+
* Run the program by typing `katrain` in the terminal.
|
| 82 |
+
* If you prefer not to install, run without installing using `python3 -m katrain` after installing the
|
| 83 |
+
dependencies from `poetry.lock` with `poetry install`.
|
| 84 |
+
|
| 85 |
+
A binary for KataGo is included, but if you have compiled your own, press F8 to open general settings and change the
|
| 86 |
+
KataGo executable path to the relevant KataGo v1.4+ binary.
|
| 87 |
+
|
| 88 |
+
### <a name="LinuxTrouble"></a>Troubleshooting and advanced installation from sources
|
| 89 |
+
|
| 90 |
+
You can try to manually install dependencies to resolve some issues relating to missing dependencies,
|
| 91 |
+
e.g. the binary 'wheel' is not provided, KataGo is not starting, or sounds are not working.
|
| 92 |
+
You can also follow these instructions if you don't want to install KaTrain, and just run it locally.
|
| 93 |
+
|
| 94 |
+
First install the following packages, which are either required for building Kivy,
|
| 95 |
+
or may help resolve missing dependencies for Kivy or KataGo.
|
| 96 |
+
```bash
|
| 97 |
+
sudo apt-get install python3-pip build-essential git python3 python3-dev ffmpeg libsdl2-dev libsdl2-image-dev\
|
| 98 |
+
libsdl2-mixer-dev libsdl2-ttf-dev libportmidi-dev libswscale-dev libavformat-dev libavcodec-dev zlib1g-dev\
|
| 99 |
+
libgstreamer1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good libpulse\
|
| 100 |
+
pkg-config libgl-dev opencl-headers ocl-icd-opencl-dev libzip-dev
|
| 101 |
+
```
|
| 102 |
+
Then, try installing python package dependencies using:
|
| 103 |
+
```bash
|
| 104 |
+
pip3 install poetry
|
| 105 |
+
poetry install
|
| 106 |
+
pip3 install screeninfo # Skip on MacOS, not working
|
| 107 |
+
```
|
| 108 |
+
In case the sound is not working, or there is no available wheel for your OS or Python version, try building kivy locally using:
|
| 109 |
+
```bash
|
| 110 |
+
pip3 uninstall kivy
|
| 111 |
+
pip3 install kivy --no-binary kivy
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
You can now start KaTrain by running `python3 -m katrain`
|
| 115 |
+
|
| 116 |
+
In case KataGo does not start, an alternative is to go [here](https://github.com/lightvector/KataGo) and compile KataGo yourself.
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
## <a name="GPU"></a> Configuring the GPU(s) KataGo uses
|
| 121 |
+
|
| 122 |
+
In most cases KataGo detects your configuration correctly, automatically searching for OpenCL devices and select the highest scoring device.
|
| 123 |
+
However, if you have multiple GPUs or want to force a specific device you will need to edit the 'analysis_config.cfg' file in the KataGo folder.
|
| 124 |
+
|
| 125 |
+
To see what devices are available and which one KataGo is using. Look for the following lines in the terminal after starting KaTrain:
|
| 126 |
+
```
|
| 127 |
+
Found 3 device(s) on platform 0 with type CPU or GPU or Accelerator
|
| 128 |
+
Found OpenCL Device 0: Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz (Intel) (score 102)
|
| 129 |
+
Found OpenCL Device 1: Intel(R) UHD Graphics 630 (Intel Inc.) (score 6000102)
|
| 130 |
+
Found OpenCL Device 2: AMD Radeon Pro 5500M Compute Engine (AMD) (score 11000102)
|
| 131 |
+
Using OpenCL Device 2: AMD Radeon Pro 5500M Compute Engine (AMD) OpenCL 1.2
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
The above devices were found on a 2019 MacBook Pro with both an on-motherboard graphics chip, and a separate AMD Radeon Pro video card.
|
| 135 |
+
As you can see it scores about twice as high as the Intel UHD chip and KataGo has selected
|
| 136 |
+
it as it's sole device. You can configure KataGo to use *both* the AMD and the Intel devices to get the best performance out of the system.
|
| 137 |
+
|
| 138 |
+
* Open the 'analysis_config.cfg' file in the `katrain/KataGo` folder in your python packages, or local sources.
|
| 139 |
+
If you can't find it, turn on `debug_level=1` in general settings and look for the command that is used to start KataGo.
|
| 140 |
+
* Search for `numNNServerThreadsPerModel` (~line 108), uncomment the line by deleting the # and set the value to 2. The line should read `numNNServerThreadsPerModel = 2`.
|
| 141 |
+
* Search for `openclDeviceToUseThread` (~line 164), uncomment by deleting the # and set the values to the device ID numbers identified in the terminal.
|
| 142 |
+
From the example above, we would want to use devices 1 and 2, for the Intel and AMD GPUs, but not device 0 (the CPU). In our case, the lines should read:
|
| 143 |
+
```
|
| 144 |
+
openclDeviceToUseThread0 = 1
|
| 145 |
+
openclDeviceToUseThread1 = 2
|
| 146 |
+
```
|
| 147 |
+
* Run `katrain` and confirm that KataGo is now using both devices, by
|
| 148 |
+
checking the output from the terminal, which should indicate two devices being used. For example:
|
| 149 |
+
```
|
| 150 |
+
Found 3 device(s) on platform 0 with type CPU or GPU or Accelerator
|
| 151 |
+
Found OpenCL Device 0: Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz (Intel) (score 102)
|
| 152 |
+
Found OpenCL Device 1: Intel(R) UHD Graphics 630 (Intel Inc.) (score 6000102)
|
| 153 |
+
Found OpenCL Device 2: AMD Radeon Pro 5500M Compute Engine (AMD) (score 11000102)
|
| 154 |
+
Using OpenCL Device 1: Intel(R) UHD Graphics 630 (Intel Inc.) OpenCL 1.2
|
| 155 |
+
Using OpenCL Device 2: AMD Radeon Pro 5500M Compute Engine (AMD) OpenCL 1.2
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
## <a name="KataGo"></a> Troubleshooting and advanced KataGo settings
|
| 160 |
+
|
| 161 |
+
See [here](ENGINE.md) for an overview of how to resolve various issues with KataGo.
|
LICENSE
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This repository includes:
|
| 2 |
+
|
| 3 |
+
1. Binaries for 'KataGo', which is Copyright David J Wu et al.
|
| 4 |
+
For on related licenses for these binaries and libraries see https://github.com/lightvector/KataGo
|
| 5 |
+
|
| 6 |
+
2. Icons from www.flaticon.com, used with permission with the following attributions:
|
| 7 |
+
- Equalize icon and Thrash Icon: derived from work by bqlqn from www.flaticon.com
|
| 8 |
+
- Other Menu icons, Finish, Collaboration and Flag icons: derived from work by Freepik from www.flaticon.com
|
| 9 |
+
- Collapse branch icon: derived from work by Kirill Kazachek from www.flaticon.com
|
| 10 |
+
- Prune icon: derived from work by Pixelmeetup from www.flaticon.com
|
| 11 |
+
- Reset icon: derived from work by Pixel Perfect from www.flaticon.com
|
| 12 |
+
- Rotate icon: derived from work by Frey Wazza from www.flaticon.com
|
| 13 |
+
|
| 14 |
+
3. The True Type Font DIGITAL-7 version 1.02 by Sizenko Alexander, which is free for non-commercial use.
|
| 15 |
+
|
| 16 |
+
4. The Noto Sans fonts from google which are covered by the SIL open font license v1.1 included in the katrain/fonts directory.
|
| 17 |
+
|
| 18 |
+
-----------------------------------------------------------------------------------------
|
| 19 |
+
Aside from the above, the license for all other content in this repository is as follows:
|
| 20 |
+
-----------------------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
Copyright 2020 Sander Land and/or other authors of the content in this repository.
|
| 23 |
+
(See 'CONTRIBUTIONS.md' file for a list of authors as well as other indirect contributors).
|
| 24 |
+
|
| 25 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
| 26 |
+
associated documentation files (the "Software"), to deal in the Software without restriction,
|
| 27 |
+
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
| 28 |
+
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
| 29 |
+
furnished to do so, subject to the following conditions:
|
| 30 |
+
|
| 31 |
+
The above copyright notice and this permission notice shall be included in all copies or
|
| 32 |
+
substantial portions of the Software.
|
| 33 |
+
|
| 34 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
| 35 |
+
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 36 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
| 37 |
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 38 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 39 |
+
|
| 40 |
+
-----------------------------------------------------------------------------------------
|
QA.txt
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
根据项目文件分析,这个 KaTrain 项目使用了现代的 Python 包管理工具 **uv**,以下是安装依赖的几种方法:
|
| 3 |
+
|
| 4 |
+
## 推荐方法:使用 uv(现代包管理器)
|
| 5 |
+
|
| 6 |
+
由于项目包含 `uv.lock` 文件和在 `pyproject.toml` 中配置了 uv,推荐使用 uv 来管理依赖:
|
| 7 |
+
|
| 8 |
+
```bash
|
| 9 |
+
# 安装 uv(如果还没有安装)
|
| 10 |
+
pip install uv
|
| 11 |
+
|
| 12 |
+
# 安装项目依赖(包括开发依赖)
|
| 13 |
+
uv sync
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
或者如果只需要运行时依赖:
|
| 17 |
+
```bash
|
| 18 |
+
uv sync --no-dev
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## 传统方法:使用 pip
|
| 22 |
+
|
| 23 |
+
如果你更喜欢使用传统的 pip:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
# 安装项目及其依赖
|
| 27 |
+
pip install .
|
| 28 |
+
|
| 29 |
+
# 或者安装开发依赖
|
| 30 |
+
pip install -e ".[dev]"
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
## 直接从 PyPI 安装
|
| 34 |
+
|
| 35 |
+
如果你只是想使用 KaTrain 而不是开发它:
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
pip install katrain
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## 项目依赖说明
|
| 42 |
+
|
| 43 |
+
根据 `pyproject.toml` 文件,主要依赖包括:
|
| 44 |
+
- **kivy** (>=2.3.1) - GUI 框架
|
| 45 |
+
- **kivymd** (==0.104.1) - Material Design 组件
|
| 46 |
+
- **pygame** - 游戏开发库(仅 macOS)
|
| 47 |
+
- **screeninfo** - 屏幕信息(非 macOS)
|
| 48 |
+
- **chardet**, **docutils**, **ffpyplayer**, **urllib3** - 其他工具库
|
| 49 |
+
|
| 50 |
+
开发依赖包括:
|
| 51 |
+
- **black** - 代码格式化
|
| 52 |
+
- **pytest** - 测试框架
|
| 53 |
+
- **pyinstaller** - 打包工具
|
| 54 |
+
- **polib** - 国际化工具
|
| 55 |
+
|
| 56 |
+
## 注意事项
|
| 57 |
+
|
| 58 |
+
1. **Python 版本要求**:需要 Python 3.9 到 3.13
|
| 59 |
+
2. **KataGo 引擎**:项目包含了 KataGo 二进制文件,但在某些平台可能需要单独安装
|
| 60 |
+
3. **系统依赖**:在 Linux 上可能需要安装额外的系统库(详见 INSTALL.md)
|
| 61 |
+
|
| 62 |
+
推荐使用 `uv sync` 命令,因为它能更好地处理依赖锁定和环境隔离。
|
| 63 |
+
|
README.md
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# <a name="manual"></a> KaTrain
|
| 2 |
+
|
| 3 |
+
[](http://github.com/sanderland/katrain/releases)
|
| 4 |
+
[](http://en.wikipedia.org/wiki/MIT_License)
|
| 5 |
+
[](http://github.com/sanderland/katrain/releases)
|
| 6 |
+
[](http://pepy.tech/project/katrain)
|
| 7 |
+
[](http://discord.com/channels/417022162348802048/629446365688365067)
|
| 8 |
+
|
| 9 |
+
KaTrain is a tool for analyzing games and playing go with AI feedback from KataGo:
|
| 10 |
+
|
| 11 |
+
* Review your games to find the moves that were most costly in terms of points lost.
|
| 12 |
+
* Play against AI and get immediate feedback on mistakes with option to retry.
|
| 13 |
+
* Play against a wide range of weakened versions of AI with various styles.
|
| 14 |
+
* Automatically generate focused SGF reviews which show your biggest mistakes.
|
| 15 |
+
|
| 16 |
+
## Manual
|
| 17 |
+
|
| 18 |
+
<table>
|
| 19 |
+
<td>
|
| 20 |
+
|
| 21 |
+
- [ KaTrain](#-katrain)
|
| 22 |
+
- [Manual](#manual)
|
| 23 |
+
- [ Preview and Youtube Videos](#--preview-and-youtube-videos)
|
| 24 |
+
- [ Installation](#-installation)
|
| 25 |
+
- [ Configuring KataGo](#--configuring-katago)
|
| 26 |
+
- [ Play against AI](#-play-against-ai)
|
| 27 |
+
- [Instant feedback](#instant-feedback)
|
| 28 |
+
- [AIs](#ais)
|
| 29 |
+
- [ Analysis](#-analysis)
|
| 30 |
+
- [ Keyboard and mouse shortcuts](#-keyboard-and-mouse-shortcuts)
|
| 31 |
+
- [ Contributing to distributed training](#-contributing-to-distributed-training)
|
| 32 |
+
- [ Themes](#-themes)
|
| 33 |
+
- [ FAQ](#-faq)
|
| 34 |
+
- [ Support / Contribute](#-support--contribute)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
<td>
|
| 38 |
+
|
| 39 |
+
<a href="http://github.com/sanderland/katrain/blob/master/README.md"><img alt="English" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-uk.png" width=50></a>
|
| 40 |
+
<a href="http://translate.google.com/translate?sl=en&tl=de&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="German" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-de.png" width=50></a>
|
| 41 |
+
<a href="http://translate.google.com/translate?sl=en&tl=fr&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="French" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-fr.png" width=50></a>
|
| 42 |
+
<a href="http://translate.google.com/translate?sl=en&tl=uk&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Ukrainian" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-ua.png" width=50></a>
|
| 43 |
+
<a href="http://translate.google.com/translate?sl=en&tl=ru&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Russian" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-ru.png" width=50></a>
|
| 44 |
+
<br/>
|
| 45 |
+
<a href="http://translate.google.com/translate?sl=en&tl=tr&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Turkish" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-tr.png" width=50></a>
|
| 46 |
+
<a href="http://translate.google.com/translate?sl=en&tl=zh-CN&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Simplified Chinese" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-cn.png" width=50></a>
|
| 47 |
+
<a href="http://translate.google.com/translate?sl=en&tl=zh-TW&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Traditional Chinese" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-tw.png" width=50></a>
|
| 48 |
+
<a href="http://translate.google.com/translate?sl=en&tl=ko&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Korean" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-ko.png" width=50></a>
|
| 49 |
+
<a href="http://translate.google.com/translate?sl=en&tl=ja&u=https%3A%2F%2Fgithub.com%2Fsanderland%2Fkatrain%2Fblob%2Fmaster%2FREADME.md"><img alt="Japanese" src="https://github.com/sanderland/katrain/blob/master/katrain/img/flags/flag-jp.png" width=50></a>
|
| 50 |
+
|
| 51 |
+
</td>
|
| 52 |
+
</table>
|
| 53 |
+
|
| 54 |
+
## <a name="preview"></a> Preview and Youtube Videos
|
| 55 |
+
|
| 56 |
+
<img alt="screenshot" src="https://raw.githubusercontent.com/sanderland/katrain/master/screenshots/analysis.png" width="550">
|
| 57 |
+
|
| 58 |
+
| **Local Joseki Analysis** | **Analysis Tutorial** | **Teaching Game Tutorial** |
|
| 59 |
+
|:-----------------------------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------:|
|
| 60 |
+
| [](https://www.youtube.com/watch?v=tXniX57KtKk) | [](http://www.youtube.com/watch?v=qjxkcKgrsbU) | [](http://www.youtube.com/watch?v=wFl4Bab_eGM) |
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
## <a name="install"></a> Installation
|
| 65 |
+
* See the [releases page](http://github.com/sanderland/katrain/releases) for downloadable executables for Windows and macOS.
|
| 66 |
+
* Alternatively use `pipx install katrain` to install the latest version from PyPI on any 64-bit OS in an isolated environment.
|
| 67 |
+
* On macOS, you can also use `brew install katrain` to install the app.
|
| 68 |
+
* [This page](https://github.com/sanderland/katrain/blob/master/INSTALL.md) has detailed instructions for Window, Linux and macOS,
|
| 69 |
+
as well as troubleshooting and setting up KataGo to use multiple GPUs.
|
| 70 |
+
|
| 71 |
+
## <a name="kata"></a> Configuring KataGo
|
| 72 |
+
|
| 73 |
+
KaTrain comes pre-packaged with a working KataGo (OpenCL version) for Windows, Linux, and pre-M1 Mac operating systems, and the rather old 15 block model.
|
| 74 |
+
|
| 75 |
+
To change the model, open 'General and Engine settings' in the application and 'Download models'. You can then select the model you want from the dropdown menu.
|
| 76 |
+
|
| 77 |
+
To change the katago binary, e.g. to the Eigen/CPU version if you don't have a GPU, click 'Download KataGo versions'.
|
| 78 |
+
You can then select the KataGo binary from the dropdown menu.
|
| 79 |
+
There are also CUDA and TensorRT versions available on [the KataGo release site](https://github.com/lightvector/KataGo/releases). Particularly the latter may offer much better performance on NVIDIA GPUs, but will be harder to
|
| 80 |
+
set up: [see here for more details](https://github.com/lightvector/KataGo#opencl-vs-cuda-vs-tensorrt-vs-eigen).
|
| 81 |
+
|
| 82 |
+
Finally, you can override the entire command used to start the analysis engine, which
|
| 83 |
+
can be useful for connecting to a remote server. Do keep in mind that KaTrain uses the *analysis engine*
|
| 84 |
+
of KataGo, and not the GTP engine.
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
## <a name="ai"></a> Play against AI
|
| 88 |
+
|
| 89 |
+
* Select the players in the main menu, or under 'New Game'.
|
| 90 |
+
* In a teaching game, KaTrain will analyze your moves and automatically undo those that are sufficiently bad.
|
| 91 |
+
* When playing against AI, note that the "Undo" button will undo both the AI's last move and yours.
|
| 92 |
+
|
| 93 |
+
### Instant feedback
|
| 94 |
+
|
| 95 |
+
The dots on the move indicate how many points were lost by that move.
|
| 96 |
+
|
| 97 |
+
* The colour indicates the size of the mistake according to KataGo
|
| 98 |
+
* The size indicates if the mistake was actually punished. Going from fully punished at maximal size,
|
| 99 |
+
to no actual effect on the score at minimal size.
|
| 100 |
+
|
| 101 |
+
In short, if you are a weaker player you should mostly focus on large dots that are red or purple,
|
| 102 |
+
while stronger players can pay more attention to smaller mistakes. If you want to hide some colours
|
| 103 |
+
on the board, or not output details for them in SGFs,you can do so under 'Configure Teacher'.
|
| 104 |
+
|
| 105 |
+
### AIs
|
| 106 |
+
|
| 107 |
+
This section describes the available AIs.
|
| 108 |
+
|
| 109 |
+
In the 'AI settings', settings which have been tested and calibrated are at the top and have a lighter color,
|
| 110 |
+
changing these will show an estimate of rank.
|
| 111 |
+
This estimate should be reasonably accurate as long as you have not changed the other settings.
|
| 112 |
+
|
| 113 |
+
* Recommended options for serious play include:
|
| 114 |
+
* **KataGo** is full KataGo, above professional level. The analysis and feedback given is always based on this full strength KataGo AI.
|
| 115 |
+
* **Calibrated Rank Bot** was calibrated on various bots (e.g. GnuGo and Pachi at different strength settings) to play a balanced
|
| 116 |
+
game from the opening to the endgame without making serious (DDK) blunders. Further discussion can be found
|
| 117 |
+
[here](http://github.com/sanderland/katrain/issues/44) and [here](http://github.com/sanderland/katrain/issues/74).
|
| 118 |
+
* **Simple Style** Prefers moves that solidify both player's territory, leading to relatively simpler moves.
|
| 119 |
+
* Legacy options which were developed earlier include:
|
| 120 |
+
* **ScoreLoss** is KataGo analyzing as usual, but
|
| 121 |
+
choosing from potential moves depending on the expected score loss, leading to a varied style with mostly small mistakes.
|
| 122 |
+
* **Policy** uses the top move from the policy network (it's 'shape sense' without reading).
|
| 123 |
+
* **Policy Weighted** picks a random move weighted by the policy, leading to a varied style with mostly small mistakes, and occasional blunders due to a lack of reading.
|
| 124 |
+
* **Blinded Policy** picks a number of moves at random and play the best move among them, being effectively 'blind' to part of the board each turn. Calibrated rank is based on the same idea, and recommended over this option.
|
| 125 |
+
* Options that are more on the 'fun and experimental' side include:
|
| 126 |
+
* Variants of **Blinded Policy**, which use the same basic strategy, but with a twist:
|
| 127 |
+
* **Local Style** will consider mostly moves close to the last move.
|
| 128 |
+
* **Tenuki Style** will consider mostly moves away from the last move.
|
| 129 |
+
* **Influential Style** will consider mostly 4th+ line moves, leading to a center-oriented style.
|
| 130 |
+
* **Territory Style** is biased in the opposite way, towards 1-3rd line moves.
|
| 131 |
+
* **KataJigo** is KataGo attempting to win by 0.5 points, typically by responding to your mistakes with an immediate mistake of it's own.
|
| 132 |
+
* **KataAntiMirror** is KataGo assuming you are playing mirror go and attempting to break out of it with profit as long as you are.
|
| 133 |
+
|
| 134 |
+
The Engine based AIs (KataGo, ScoreLoss, KataJigo) are affected by both the model and choice of visits and maximum time,
|
| 135 |
+
while the policy net based AIs are affected by the choice of model file, but work identically with 1 visit.
|
| 136 |
+
|
| 137 |
+
Further technical details and discussion on some of these AIs can be found on [this](http://lifein19x19.com/viewtopic.php?f=10&t=17488&sid=b11e42c005bb6f4f48c83771e6a27eff) thread at the life in 19x19 forums.
|
| 138 |
+
|
| 139 |
+
## <a name="analysis"></a> Analysis
|
| 140 |
+
|
| 141 |
+
Analysis options in KaTrain allow you to explore variations and request more in-depth analysis from the engine at any point in the game.
|
| 142 |
+
|
| 143 |
+
| Key | Short Description | Details |
|
| 144 |
+
| -------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| 145 |
+
| <kbd>Tab</kbd> | Switch between analysis and play modes | AI moves, teaching mode and timers are suspended in analysis mode. The state of the analysis options and right-hand side panels and options is saved independently for 'play' and 'analyze', allowing you to quickly switch between a more minimalistic 'play' mode and more complex 'analysis' mode. |
|
| 146 |
+
|
| 147 |
+
The checkboxes at the top of the screen:
|
| 148 |
+
|
| 149 |
+
| Key | Short Description | Details |
|
| 150 |
+
| ------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| 151 |
+
| <kbd>q</kbd> | Child moves are shown | On by default, can turn it off to avoid obscuring other information or when wanting to guess the next move. |
|
| 152 |
+
| <kbd>w</kbd> | Show all dots | Toggles showing coloured evaluation 'dots' on the last few moves or not. You can configure the thresholds, along with how many of the last moves they are shown for under 'Teaching/Analysis Settings'. |
|
| 153 |
+
| <kbd>e</kbd> | Top moves | Show the next moves KataGo considered, colored by their expected point loss. Small/faint dots indicate high uncertainty and never show text (lower than your 'fast visits' setting). Hover over any of them to see the principal variation. |
|
| 154 |
+
| <kbd>r</kbd> | Policy moves | Show KataGo's policy network evaluation, i.e. where it thinks the best next move is purely from the position, and in the absence of any 'reading'. This turns off the 'top moves' setting as the overlap is often not useful. |
|
| 155 |
+
| <kbd>t</kbd> | Expected territory | Show expected ownership of each intersection. |
|
| 156 |
+
|
| 157 |
+
The analysis options available under the 'Analysis' button are used for deeper evaluation of the position:
|
| 158 |
+
|
| 159 |
+
| Key | Short Description | Details |
|
| 160 |
+
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| 161 |
+
| <kbd>a</kbd> | Deeper analysis | Re-evaluate the position using more visits, usually resulting in a more accurate evaluation. |
|
| 162 |
+
| <kbd>s</kbd> | Equalize visits | Re-evaluate all currently shown next moves with the same visits as the current top move. Useful to increase confidence in the suggestions with high uncertainty. |
|
| 163 |
+
| <kbd>d</kbd> | Analyze all moves | Evaluate all possible next moves. This can take a bit of time even though 'fast_visits' is used, but can be useful to see how many reasonable next moves are available. |
|
| 164 |
+
| <kbd>f</kbd> | Find alternatives | Increases analysis of current candidate moves to at least the 'fast visits' level, and request a new query that excludes all current candidate moves. |
|
| 165 |
+
| <kbd>g</kbd> | Select area of interest | Set an area and search only for moves in this box. Good for solving tsumegos. Note that some results may appear outside the box due to establishing a baseline for the best move, and the opponent can tenuki in variations. |
|
| 166 |
+
| <kbd>h</kbd> | Reset analysis | This reverts the analysis to what the engine returns after a normal query, removing any additional exploration. |
|
| 167 |
+
| <kbd>i</kbd> | Start insertion mode | Allows you to insert moves, to improve analysis when both players ignore an important exchange or life and death situation. Press again to stop inserting and copy the rest of the branch. |
|
| 168 |
+
| <kbd>l</kbd> | Play out the game until the end and add as a collapsed branch, to visualize the potential effect of mistakes | This is done in the background, and can be started at several nodes at once when comparing the results at different starting positions. |
|
| 169 |
+
| <kbd>Space</kbd> | Turn continuous analysis on/off. | This will continuously improve analysis of the current position, similar to Lizzie's 'pondering', but only when there are no other queries going on. |
|
| 170 |
+
| <kbd>Shift</kbd> + <kbd>Space</kbd> | As above, but does not turn 'top moves' hints on when it is off. | |
|
| 171 |
+
| <kbd>Enter</kbd> | AI move | Makes the AI move for the current player regardless of current player selection. |
|
| 172 |
+
| <kbd>F2</kbd> | Deeper full game analysis | Analyze the entire game to a higher number of visits. |
|
| 173 |
+
| <kbd>F3</kbd> | Performance report | Show an overview of performance statistics for both players. |
|
| 174 |
+
| <kbd>F10</kbd> | Tsumego Frame | After placing a life and death problem in a corner/side, use this to fill up the rest of the board to improve AI's ability in solving life and death problems. |
|
| 175 |
+
|
| 176 |
+
## <a name="keyboard"></a> Keyboard and mouse shortcuts
|
| 177 |
+
|
| 178 |
+
In addition to shortcuts mentioned above and those shown in the main menu:
|
| 179 |
+
|
| 180 |
+
| Key | Short Description | Details |
|
| 181 |
+
| ---------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
|
| 182 |
+
| <kbd>Alt</kbd> | Open the main menu | |
|
| 183 |
+
| <kbd>~</kbd> or <kbd>`</kbd> or <kbd>F12</kbd> | Cycles through more minimalistic UI modes | |
|
| 184 |
+
| <kbd>k</kbd> | Toggle display of board coordinates | |
|
| 185 |
+
| <kbd>p</kbd> | Pass | |
|
| 186 |
+
| <kbd>Pause</kbd> | Pause/Resume timer | |
|
| 187 |
+
| <kbd>←</kbd> or <kbd>z</kbd> | Undo move | Hold shift for 10 moves at a time, or ctrl to skip to the start. |
|
| 188 |
+
| <kbd>→</kbd> or <kbd>x</kbd> | Redo move | Hold shift for 10 moves at a time, or ctrl to skip to the end. |
|
| 189 |
+
| <kbd>↑</kbd>/<kbd>↓</kbd> | Switch branch | As would be expected from the move tree. |
|
| 190 |
+
| <kbd>Home</kbd>/<kbd>End</kbd> | Go to the beginning/end of the game | |
|
| 191 |
+
| <kbd>PageUp</kbd> | Make the currently selected node the main branch | |
|
| 192 |
+
| <kbd>Ctrl</kbd> + <kbd>Delete</kbd> | Delete current node | |
|
| 193 |
+
| <kbd>c</kbd> | Collapse/Uncollapse the branch from the current node to the previous branching point | |
|
| 194 |
+
| <kbd>b</kbd> | Go back to the previous branching point | |
|
| 195 |
+
| <kbd>Shift</kbd> + <kbd>b</kbd> | Go back the main branch | |
|
| 196 |
+
| <kbd>n</kbd> | Go to one move before the next mistake (orange or worse) by a human player | As in clicking the forward red arrow |
|
| 197 |
+
| <kbd>Shift</kbd> + <kbd>n</kbd> | Go to one move before the previous mistake | As in clicking the backward red arrow |
|
| 198 |
+
| Scroll Mouse | Redo/Undo move or Scroll through principal variation | When hovering the cursor over the right panel: Redo/Undo move. When hovering over a candidate move: Scroll through principal variation. |
|
| 199 |
+
| Middle Scroll Wheel Click | Add principal variation to the move tree | When scrolling, only moves up to the point you are viewing are added. |
|
| 200 |
+
| Click on a Move | See detailed statistics for a previous move | Along with expected variation that was best instead of this move |
|
| 201 |
+
| Double Click on a Move | Navigate directly to just before that point in the game | |
|
| 202 |
+
| <kbd>Ctrl</kbd> + <kbd>v</kbd> | Load SGF from the clipboard and do a 'fast' analysis of the game | With a high priority normal analysis for the last move. |
|
| 203 |
+
| <kbd>Ctrl</kbd> + <kbd>c</kbd> | Save SGF to clipboard | |
|
| 204 |
+
| <kbd>Escape</kbd> | Stop all analysis | |
|
| 205 |
+
|
| 206 |
+
## <a name="distributed"></a> Contributing to distributed training
|
| 207 |
+
|
| 208 |
+
Starting in December 2020, KataGo started [distributed training](https://katagotraining.org/).
|
| 209 |
+
This allows people to all help generate self-play games to increase KataGo's strength and train bigger models.
|
| 210 |
+
|
| 211 |
+
KaTrain 1.8.0+ makes it easy to contribute to distributed training: simply select the option from the main menu, register an account, and click run.
|
| 212 |
+
During this mode you can do little more than watch games.
|
| 213 |
+
|
| 214 |
+
Keep in mind that partial games are not uploaded,
|
| 215 |
+
so it is best to plan to keep it running for at least an hour, if not several, for the most effective contribution.
|
| 216 |
+
|
| 217 |
+
A few keyboard shortcuts have special functions in this mode:
|
| 218 |
+
|
| 219 |
+
| Key | Short Description | Details |
|
| 220 |
+
| ----------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
| 221 |
+
| <kbd>Space</kbd> | Switch between manually navigating the current game | And automatically advancing it. |
|
| 222 |
+
| <kbd>Escape</kbd> | Sends the `quit` command to KataGo | Which starts a slow shutdown, finishing partial games but not starting new ones. Only works on v1.11+. |
|
| 223 |
+
| <kbd>Pause</kbd> | Pauses/resumes contributions via the `pause` and `resume` commands | Introduced in KataGo v1.11 |
|
| 224 |
+
|
| 225 |
+
## <a name="themes"></a> Themes
|
| 226 |
+
|
| 227 |
+
See [these instructions](THEMES.md) for how to modify the look of any graphics or colours, and creating or install themes.
|
| 228 |
+
|
| 229 |
+
## <a name="faq"></a> FAQ
|
| 230 |
+
|
| 231 |
+
* The program is running too slowly. How can I speed it up?
|
| 232 |
+
* Adjust the number of visits or maximum time allowed in the settings.
|
| 233 |
+
* KataGo crashes with "out of memory" errors, how can I prevent this?
|
| 234 |
+
* Try using a lower number for `nnMaxBatchSize` in `KataGo/analysis_config.cfg`, and avoid using versions compiled with large board sizes.
|
| 235 |
+
* If still encountering problems, please start KataGo by itself to check for any errors it gives.
|
| 236 |
+
* Note that if you don't have a GPU, or your GPU does not support OpenCL, you should use the 'eigen' binaries which run on CPU only.
|
| 237 |
+
* The font size is too small
|
| 238 |
+
* On some ultra-high resolution monitors, dialogs and other elements with text can appear too small. Please see [these](https://github.com/sanderland/katrain/issues/359#issuecomment-784096271) instructions to adjust them.
|
| 239 |
+
* The app crashes with an error about "unable to find any valuable cutbuffer provider"
|
| 240 |
+
* Install xclip using `sudo apt-get install xclip`
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
## <a name="support"></a> Support / Contribute
|
| 244 |
+
|
| 245 |
+
[](http://github.com/sanderland/katrain/issues)
|
| 246 |
+
[](CONTRIBUTIONS.md)
|
| 247 |
+
|
| 248 |
+
* Ideas, feedback, and contributions to code or translations are all very welcome.
|
| 249 |
+
* For suggestions and planned improvements, see [open issues](http://github.com/sanderland/katrain/issues) on github to check if the functionality is already planned.
|
| 250 |
+
* You can join the [Computer Go Community Discord (formerly Leela Zero & Friends)](http://discord.gg/AjTPFpN) (use the #gui channel) to get help, discuss improvements, or simply show your appreciation. Please do not use github issues to ask for technical help, this is only for bugs, suggestions and discussing contributions.
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
|
THEMES.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Themes
|
| 2 |
+
|
| 3 |
+
Version 1.7 brings basic support for themes, and 1.9 extends it to include keyboard shortcuts and support for multiple theme files.
|
| 4 |
+
|
| 5 |
+
## Creating and editing themes
|
| 6 |
+
|
| 7 |
+
* Look at the `Theme` class in [`katrain/gui/theme.py`](https://github.com/sanderland/katrain/blob/master/katrain/gui/theme.py).
|
| 8 |
+
* Make a `theme-<yourthemename>.json` file in your `<home dir>/.katrain` directory and specify any variables from the above class you want to override, e.g.
|
| 9 |
+
```json
|
| 10 |
+
{
|
| 11 |
+
"BACKGROUND_COLOR": [1,0,0,1],
|
| 12 |
+
"KEY_STOP_ANALYSIS": "f10",
|
| 13 |
+
"MISTAKE_SOUNDS": ["jeff.wav","what.wav"]
|
| 14 |
+
}
|
| 15 |
+
```
|
| 16 |
+
* All resources (including icons, which can not be renamed for now) will be looked up in `<home dir>/.katrain` first, so files with identical names there can be used to override sounds and images.
|
| 17 |
+
* If variables are specified in multiple theme files, the *latest* alphabetically takes precedence. That is, each later theme file overwrites the settings from any previous one.
|
| 18 |
+
|
| 19 |
+
## Expected territory options
|
| 20 |
+
|
| 21 |
+
* KaTrain supports different styles of display of expected territory:
|
| 22 |
+
* Blended style colors the board with an intensity proportional to the likelihood of a player controlling that territory at the end of the game.
|
| 23 |
+
* Shaded style behaves the same as Blended, but uses square shades similar to
|
| 24 |
+
the Katago paper.
|
| 25 |
+
* In the Marks style, each point of the board is marked with a square of size which is proportional to ownership likelihood.
|
| 26 |
+
* The Blocks style divides the whole board into black, white, and neutral territory, based on a likelihood threshold. This style is appropriate as a counting aid, but may be misleading before endgame if much of the territory is unsettled.
|
| 27 |
+
* Marks can also appear on stones to indicate the likelihood of these stones living at the end of the game. Three styles are supported:
|
| 28 |
+
* All stones can be marked, with the color of the mark indicating the expected ownership and the size of the mark indicating certainty.
|
| 29 |
+
* Weak stones only - marks will appear only on stones which are over 50% likely to die before the end of the game.
|
| 30 |
+
* No stone marks.
|
| 31 |
+
* Stones can also be made transparent based on their strength.
|
| 32 |
+
|
| 33 |
+
| <img src="./themes/blended-all.png" width="400"/> <br> Blended style, all stones marked| <img src="./themes/shaded-all.png" width="400"/> <br> Shaded style, all stones marked |
|
| 34 |
+
| --- | ---|
|
| 35 |
+
| <img src="./themes/blocks-none.png" width="400"/> <br> Territory blocks, no stones marked | <img src="./themes/blended-weak.png" width="400"/> <br> Blended territory, weak stones marked |
|
| 36 |
+
| <img src="./themes/marks-weak.png" width="400"/> <br> Marks on intersections, weak stones marked | <img src="./themes/shaded-no-alpha.png" width="400"/> <br> Shaded, no stone alpha |
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
<sup>The game used in the screenshots is [Albert Yen vs. Eric Yoder](https://www.usgo.org/news/2022/03/members-edition-midwest-open-round-2-the-broken-ladder-game).</sup>
|
| 40 |
+
|
| 41 |
+
The stone marks, transparency, and territory style are independent; the table above presents a collection of possible variants.
|
| 42 |
+
The relevant variables are:
|
| 43 |
+
```
|
| 44 |
+
{
|
| 45 |
+
"TERRITORY_DISPLAY" : "blended" | "shaded" | "marks" | "blocks",
|
| 46 |
+
"STONE_MARKS" : "all" | "weak" | "none",
|
| 47 |
+
"OWNERSHIP_COLORS" : {"B": [0.0, 0.0, 0.10, 0.75], "W": [0.92, 0.92, 1.0, 0.800]},
|
| 48 |
+
"BLOCKS_THRESHOLD" : 0.6,
|
| 49 |
+
"MARK_SIZE" : 0.42, # as fraction of stone size
|
| 50 |
+
"STONE_MIN_ALPHA" : 0.5
|
| 51 |
+
}
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
The colors are specified as RGB values and a maximum alpha transparency.
|
| 55 |
+
|
| 56 |
+
## Installation
|
| 57 |
+
|
| 58 |
+
* To install a theme, simply unzip the theme.zip to your .katrain folder.
|
| 59 |
+
* On Windows you can find it in C:\Users\you\\.katrain and on linux in ~/.katrain.
|
| 60 |
+
* When in doubt, the general settings dialog will also show the location.
|
| 61 |
+
* To uninstall a theme, remove theme.json and all relevant images from that folder.
|
| 62 |
+
|
| 63 |
+
## Available themes
|
| 64 |
+
|
| 65 |
+
### Alternate board/stones theme by "koast"
|
| 66 |
+
|
| 67 |
+
[Download](https://github.com/sanderland/katrain/blob/master/themes/koast-theme.zip)
|
| 68 |
+
|
| 69 |
+
<img src="https://raw.githubusercontent.com/sanderland/katrain/master/themes/koast.png" width="500">
|
| 70 |
+
|
| 71 |
+
### Lizzie-like theme
|
| 72 |
+
|
| 73 |
+
* Theme created by Eric W, includes modified board, stones
|
| 74 |
+
* Images taken from [Lizzie](https://github.com/featurecat/lizzie/) by featurecat and contributors.
|
| 75 |
+
* Hides hints for low visit/uncertain moves instead of showing small dots.
|
| 76 |
+
|
| 77 |
+
[Download](https://github.com/sanderland/katrain/blob/master/themes/eric-lizzie-look.zip)
|
| 78 |
+
|
| 79 |
+
<img src="https://raw.githubusercontent.com/sanderland/katrain/master/themes/eric-lizzie.png" width="500">
|
| 80 |
+
|
| 81 |
+
### Milos Theme
|
| 82 |
+
* Clean and crisp display.
|
| 83 |
+
* Blocks for territory, textureless evaluation markers, no dots/alpha/etc with redundant ownership/strength info.
|
| 84 |
+
* Resembles AI Sensei's design.
|
| 85 |
+
|
| 86 |
+
[Download](themes/theme-milos.zip)
|
| 87 |
+
|
| 88 |
+
<img src="themes/milos.png" width="500">
|
| 89 |
+
|
| 90 |
+
### Jeff sounds
|
| 91 |
+
|
| 92 |
+
* This theme makes Jeff comment `Ahhh?` and `What?!` when you make mistakes.
|
| 93 |
+
* Sounds provided by Mikkgo.
|
| 94 |
+
|
| 95 |
+
[Download](https://github.com/sanderland/katrain/blob/master/themes/jeff-sounds.zip)
|
| 96 |
+
|
i18n.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import glob
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
|
| 8 |
+
import polib
|
| 9 |
+
|
| 10 |
+
localedir = "katrain/i18n/locales"
|
| 11 |
+
locales = set(os.listdir(localedir))
|
| 12 |
+
print("locales found:", locales)
|
| 13 |
+
|
| 14 |
+
strings_to_langs = defaultdict(dict)
|
| 15 |
+
strings_to_keys = defaultdict(dict)
|
| 16 |
+
lang_to_strings = defaultdict(set)
|
| 17 |
+
|
| 18 |
+
DEFAULT_LANG = "en"
|
| 19 |
+
INACTIVE_LANGS = ["es"]
|
| 20 |
+
errors = False
|
| 21 |
+
|
| 22 |
+
po = {}
|
| 23 |
+
pofile = {}
|
| 24 |
+
todos = defaultdict(list)
|
| 25 |
+
|
| 26 |
+
for lang in locales:
|
| 27 |
+
if lang in INACTIVE_LANGS:
|
| 28 |
+
continue
|
| 29 |
+
pofile[lang] = os.path.join(localedir, lang, "LC_MESSAGES", "katrain.po")
|
| 30 |
+
po[lang] = polib.pofile(pofile[lang])
|
| 31 |
+
for entry in po[lang].translated_entries():
|
| 32 |
+
if "TODO" in entry.comment and "DEPRECATED" not in entry.comment:
|
| 33 |
+
todos[lang].append(entry)
|
| 34 |
+
strings_to_langs[entry.msgid][lang] = entry
|
| 35 |
+
strings_to_keys[entry.msgid][lang] = set(re.findall("{.*?}", entry.msgstr))
|
| 36 |
+
if entry.msgid in lang_to_strings[lang]:
|
| 37 |
+
print("duplicate", entry.msgid, "in", lang, "--> deleting", entry.msgstr)
|
| 38 |
+
errors = True
|
| 39 |
+
po[lang].remove(entry)
|
| 40 |
+
else:
|
| 41 |
+
lang_to_strings[lang].add(entry.msgid)
|
| 42 |
+
if todos[lang] and any("todo" in a for a in sys.argv):
|
| 43 |
+
print(f"========== {lang} has {len(todos[lang])} TODO entries ========== ")
|
| 44 |
+
for item in todos[lang]:
|
| 45 |
+
print(item)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
for lang in locales:
|
| 49 |
+
if lang in INACTIVE_LANGS:
|
| 50 |
+
continue
|
| 51 |
+
if lang != DEFAULT_LANG:
|
| 52 |
+
for msgid in lang_to_strings[lang]:
|
| 53 |
+
if (
|
| 54 |
+
DEFAULT_LANG in strings_to_keys[msgid]
|
| 55 |
+
and strings_to_keys[msgid][lang] != strings_to_keys[msgid][DEFAULT_LANG]
|
| 56 |
+
):
|
| 57 |
+
print(
|
| 58 |
+
f"{msgid} has inconstent formatting keys for {lang}: ",
|
| 59 |
+
strings_to_keys[msgid][lang],
|
| 60 |
+
"is different from default",
|
| 61 |
+
strings_to_keys[msgid][DEFAULT_LANG],
|
| 62 |
+
)
|
| 63 |
+
errors = True
|
| 64 |
+
|
| 65 |
+
for msgid in strings_to_langs.keys() - lang_to_strings[lang]:
|
| 66 |
+
if lang == DEFAULT_LANG:
|
| 67 |
+
print("Message id", msgid, "found as ", strings_to_langs[msgid], "but missing in default", DEFAULT_LANG)
|
| 68 |
+
errors = True
|
| 69 |
+
elif DEFAULT_LANG in strings_to_langs[msgid]:
|
| 70 |
+
copied_entry = copy.copy(strings_to_langs[msgid][DEFAULT_LANG])
|
| 71 |
+
print("Message id", msgid, "missing in ", lang, "-> Adding it from", DEFAULT_LANG)
|
| 72 |
+
if copied_entry.comment:
|
| 73 |
+
copied_entry.comment = f"TODO - {copied_entry.comment}"
|
| 74 |
+
else:
|
| 75 |
+
copied_entry.comment = "TODO"
|
| 76 |
+
po[lang].append(copied_entry)
|
| 77 |
+
errors = True
|
| 78 |
+
else:
|
| 79 |
+
print(f"MISSING IN DEFAULT AND {lang}", msgid)
|
| 80 |
+
errors = True
|
| 81 |
+
|
| 82 |
+
for msgid, lang_entries in strings_to_langs.items():
|
| 83 |
+
if lang in lang_entries and "TODO" in lang_entries[lang].comment:
|
| 84 |
+
if any(e.msgstr == lang_entries[lang].msgstr for ll, e in lang_entries.items() if ll != lang):
|
| 85 |
+
if lang_entries.get(DEFAULT_LANG):
|
| 86 |
+
todo_comment = (
|
| 87 |
+
f"TODO - {lang_entries[DEFAULT_LANG].comment}" if lang_entries[DEFAULT_LANG].comment else "TODO"
|
| 88 |
+
) # update todo
|
| 89 |
+
if (
|
| 90 |
+
lang_entries[lang].msgstr != lang_entries[DEFAULT_LANG].msgstr
|
| 91 |
+
or lang_entries[lang].comment.replace("\n", " ") != todo_comment
|
| 92 |
+
):
|
| 93 |
+
print(
|
| 94 |
+
[
|
| 95 |
+
lang_entries[lang].msgstr,
|
| 96 |
+
lang_entries[DEFAULT_LANG].msgstr,
|
| 97 |
+
lang_entries[lang].comment,
|
| 98 |
+
todo_comment,
|
| 99 |
+
]
|
| 100 |
+
)
|
| 101 |
+
lang_entries[lang].msgstr = lang_entries[DEFAULT_LANG].msgstr # update
|
| 102 |
+
lang_entries[lang].comment = todo_comment
|
| 103 |
+
print(f"{lang}/{msgid} todo entry updated")
|
| 104 |
+
|
| 105 |
+
po[lang].save(pofile[lang])
|
| 106 |
+
mofile = pofile[lang].replace(".po", ".mo")
|
| 107 |
+
po[lang].save_as_mofile(mofile)
|
| 108 |
+
print("Fixed", pofile[lang], "and converted ->", mofile)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
for ext in ["py", "kv"]:
|
| 112 |
+
lc = 0
|
| 113 |
+
for file in glob.glob(f"katrain/*.{ext}") + glob.glob(f"katrain/**/*.{ext}"):
|
| 114 |
+
with open(file, "r") as f:
|
| 115 |
+
for i, line in enumerate(f.readlines()):
|
| 116 |
+
if line.strip():
|
| 117 |
+
lc += 1
|
| 118 |
+
matches = [m.strip() for m in re.findall(r"i18n._\((.*?)\)", line)]
|
| 119 |
+
for msgid in matches:
|
| 120 |
+
stripped_msgid = msgid.strip("\"'")
|
| 121 |
+
if stripped_msgid and msgid[0] in ['"', "'"] and stripped_msgid not in strings_to_langs: # not code
|
| 122 |
+
print(f"Missing {msgid} used in code at \t{file}:{i} \t'{line.strip()}'")
|
| 123 |
+
errors += 1
|
| 124 |
+
print(f"Checked {lc} lines of {ext} code for missing i18n entries.")
|
| 125 |
+
sys.exit(int(errors))
|
katrain.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# for backward compatibility
|
| 2 |
+
from katrain.__main__ import run_app
|
| 3 |
+
|
| 4 |
+
run_app()
|
katrain/KataGo/OpenCL.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0c835106eafe5b4816b90a73b613c34b9542d076813df541d65f04f03b012033
|
| 3 |
+
size 107520
|
katrain/KataGo/__init__.py
ADDED
|
File without changes
|
katrain/KataGo/analysis_config.cfg
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example config for C++ (non-python) gtp bot
|
| 2 |
+
|
| 3 |
+
# SEE NOTES ABOUT PERFORMANCE AND MEMORY USAGE IN gtp_example.cfg
|
| 4 |
+
# SEE NOTES ABOUT numSearchThreads AND OTHER IMPORTANT PARAMS BELOW!
|
| 5 |
+
|
| 6 |
+
# Logs------------------------------------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
# Where to output log?
|
| 9 |
+
# logFile = analysis.log # Use this instead of logDir to just specify a single file directly
|
| 10 |
+
# logToStderr = true # Echo everything output to log file to stderr as well
|
| 11 |
+
# logAllRequests = false # Log all input lines received to the analysis engine.
|
| 12 |
+
# logAllResponses = false # Log all lines output to stdout from the analysis engine.
|
| 13 |
+
# logSearchInfo = false # Log debug info for every search performed
|
| 14 |
+
|
| 15 |
+
# Controls the number of moves after the first move in a variation.
|
| 16 |
+
# analysisPVLen = 15
|
| 17 |
+
|
| 18 |
+
# Report winrates for analysis as (BLACK|WHITE|SIDETOMOVE).
|
| 19 |
+
reportAnalysisWinratesAs = BLACK
|
| 20 |
+
|
| 21 |
+
# Bot behavior---------------------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
# Handicap -------------
|
| 24 |
+
|
| 25 |
+
# Assume that if black makes many moves in a row right at the start of the game, then the game is a handicap game.
|
| 26 |
+
# This is necessary on some servers and for some GUIs and also when initializing from many SGF files, which may
|
| 27 |
+
# set up a handicap games using repeated GTP "play" commands for black rather than GTP "place_free_handicap" commands.
|
| 28 |
+
# However, it may also lead to incorrect undersanding of komi if whiteBonusPerHandicapStone = 1 and a server does NOT
|
| 29 |
+
# have such a practice.
|
| 30 |
+
# Defaults to true! Uncomment and set to false to disable this behavior.
|
| 31 |
+
# assumeMultipleStartingBlackMovesAreHandicap = true
|
| 32 |
+
|
| 33 |
+
# Passing and cleanup -------------
|
| 34 |
+
|
| 35 |
+
# Make the bot never assume that its pass will end the game, even if passing would end and "win" under Tromp-Taylor rules.
|
| 36 |
+
# Usually this is a good idea when using it for analysis or playing on servers where scoring may be implemented non-tromp-taylorly.
|
| 37 |
+
# Defaults to true! Uncomment and set to false to disable this.
|
| 38 |
+
conservativePass = true
|
| 39 |
+
|
| 40 |
+
# When using territory scoring, self-play games continue beyond two passes with special cleanup
|
| 41 |
+
# rules that may be confusing for human players. This option prevents the special cleanup phases from being
|
| 42 |
+
# reachable when using the bot for GTP play.
|
| 43 |
+
# Defaults to true! Uncomment and set to false if you want KataGo to be able to enter special cleanup.
|
| 44 |
+
# For example, if you are testing it against itself, or against another bot that has precisely implemented the rules
|
| 45 |
+
# documented at https://lightvector.github.io/KataGo/rules.html
|
| 46 |
+
# preventCleanupPhase = true
|
| 47 |
+
|
| 48 |
+
# Search limits-----------------------------------------------------------------------------------
|
| 49 |
+
|
| 50 |
+
# By default, if NOT specified in an individual request, limit maximum number of root visits per search to this much
|
| 51 |
+
maxVisits = 500
|
| 52 |
+
# If provided, cap search time at this many seconds
|
| 53 |
+
# maxTime = 60
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# numSearchThreads is the number of threads to use in each MCTS tree search in parallel for any individual position.
|
| 57 |
+
# But NOTE: Analysis engine also specifies max number of POSITIONS to be able to search in parallel via command line
|
| 58 |
+
# argument, -num-analysis-threads.
|
| 59 |
+
|
| 60 |
+
# Parallelization across positions is more efficient since the threads on different positions operate
|
| 61 |
+
# on different MCTS trees so they don't have to synchronize with each other. Also, multiple threads on the same MCTS
|
| 62 |
+
# tree weakens the search (holding playouts fixed) due to out of date statistics on nodes and suboptimal exploration,
|
| 63 |
+
# although the loss is still quite small for only 2,4,8 threads. So you often want to keep numSearchThreads small,
|
| 64 |
+
# unlike in GTP.
|
| 65 |
+
|
| 66 |
+
# But obviously you only get the benefit of parallelization across positions when you actually have lots of positions
|
| 67 |
+
# that you are querying at once.
|
| 68 |
+
|
| 69 |
+
# Therefore:
|
| 70 |
+
# * If you plan to use the analysis engine only for batch processing large numbers of positions,
|
| 71 |
+
# it's preferable to set this to only a small number (e.g. 1,2,4) and use a higher -num-analysis-threads.
|
| 72 |
+
# * But if you sometimes plan to query the analysis engine for single positions, or otherwise in smaller quantities
|
| 73 |
+
# than -num-analysis-threads, or if you plan to be user-interactive such that the response time on some individual
|
| 74 |
+
# analysis requests is important to keep low, then set this to a larger number and use somewhat fewer analysis threads,
|
| 75 |
+
# That way, individual searches complete faster due to having more threads on each one and doing fewer other ones at a time.
|
| 76 |
+
|
| 77 |
+
# For 19x19 boards, weaker GPUs probably want a TOTAL number of threads (numSearchThreads * num-analysis-threads)
|
| 78 |
+
# between 4 and 32. Mid-tier GPUs probably between 16 and 64. Strong GPUs probably between 32 and 256.
|
| 79 |
+
# But there's no substitute for experimenting and seeing what's best for your hardware and your usage case.
|
| 80 |
+
# Keep in mind that the number of threads you want doesn't necessarily have much to do with how many cores you
|
| 81 |
+
# have on your system, and could easily exceed the number of cores. GPU batching is (usually) the dominant consideration.
|
| 82 |
+
numAnalysisThreads = 12
|
| 83 |
+
numSearchThreads = 8
|
| 84 |
+
|
| 85 |
+
# nnMaxBatchSize is the max number of positions to send to a single GPU at once. Generally, it should be the case that:
|
| 86 |
+
# (number of GPUs you will use * nnMaxBatchSize) >= (numSearchThreads * num-analysis-threads)
|
| 87 |
+
# That way, when each threads tries to request a GPU eval, your batch size summed across GPUs is large enough to handle them
|
| 88 |
+
# all at once. However, it can be sensible to set this a little smaller if you are limited on GPU memory,
|
| 89 |
+
# too large a number may fail if the GPU doesn't have enough memory.
|
| 90 |
+
nnMaxBatchSize = 96
|
| 91 |
+
|
| 92 |
+
# Eigen-specific settings--------------------------------------
|
| 93 |
+
# These only apply when using the Eigen (pure CPU) version of KataGo.
|
| 94 |
+
|
| 95 |
+
# This is the number of CPU threads for evaluating the neural net on the Eigen backend.
|
| 96 |
+
# It defaults to min(numAnalysisThreads * numSearchThreadsPerAnalysisThread, numCPUCores).
|
| 97 |
+
# numEigenThreadsPerModel = X
|
| 98 |
+
|
| 99 |
+
# Uncomment and set these smaller if you ONLY are going to use the analysis engine for smaller boards (or plan to
|
| 100 |
+
# run multiple instances, with some instances only handling smaller boards). It should improve performance.
|
| 101 |
+
# It may also mean you can use more threads profitably.
|
| 102 |
+
# maxBoardXSizeForNNBuffer = 19
|
| 103 |
+
# maxBoardYSizeForNNBuffer = 19
|
| 104 |
+
|
| 105 |
+
# TO USE MULTIPLE GPUS:
|
| 106 |
+
# Uncomment and set this to the number of GPUs you have and/or would like to use...
|
| 107 |
+
# AND if it is more than 1, uncomment the appropriate CUDA or OpenCL section below.
|
| 108 |
+
# numNNServerThreadsPerModel = 1
|
| 109 |
+
|
| 110 |
+
# Other General GPU Settings-------------------------------------------------------------------------------
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Cache up to 2 ** this many neural net evaluations in case of transpositions in the tree.
|
| 114 |
+
nnCacheSizePowerOfTwo = 20
|
| 115 |
+
# Size of mutex pool for nnCache is 2 ** this
|
| 116 |
+
nnMutexPoolSizePowerOfTwo = 16
|
| 117 |
+
# Randomize board orientation when running neural net evals?
|
| 118 |
+
nnRandomize = true
|
| 119 |
+
|
| 120 |
+
# TO USE MULTIPLE GPUS:
|
| 121 |
+
# Set this to the number of GPUs you have and/or would like to use...
|
| 122 |
+
# AND if it is more than 1, uncomment the appropriate CUDA or OpenCL section below.
|
| 123 |
+
# numNNServerThreadsPerModel = 1
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# CUDA GPU settings--------------------------------------
|
| 127 |
+
# These only apply when using the CUDA version of KataGo.
|
| 128 |
+
|
| 129 |
+
# IF USING ONE GPU: optionally uncomment and change this if the GPU you want to use turns out to be not device 0
|
| 130 |
+
# cudaDeviceToUse = 0
|
| 131 |
+
|
| 132 |
+
# IF USING TWO GPUS: Uncomment these two lines (AND set numNNServerThreadsPerModel above):
|
| 133 |
+
# cudaDeviceToUseThread0 = 0 # change this if the first GPU you want to use turns out to be not device 0
|
| 134 |
+
# cudaDeviceToUseThread1 = 1 # change this if the second GPU you want to use turns out to be not device 1
|
| 135 |
+
|
| 136 |
+
# IF USING THREE GPUS: Uncomment these three lines (AND set numNNServerThreadsPerModel above):
|
| 137 |
+
# cudaDeviceToUseThread0 = 0 # change this if the first GPU you want to use turns out to be not device 0
|
| 138 |
+
# cudaDeviceToUseThread1 = 1 # change this if the second GPU you want to use turns out to be not device 1
|
| 139 |
+
# cudaDeviceToUseThread2 = 2 # change this if the third GPU you want to use turns out to be not device 2
|
| 140 |
+
|
| 141 |
+
# You can probably guess the pattern if you have four, five, etc. GPUs.
|
| 142 |
+
|
| 143 |
+
# KataGo will automatically use FP16 or not based on the compute capability of your NVIDIA GPU. If you
|
| 144 |
+
# want to try to force a particular behavior though you can uncomment these lines and change them
|
| 145 |
+
# to "true" or "false". E.g. it's using FP16 but on your card that's giving an error, or it's not using
|
| 146 |
+
# FP16 but you think it should.
|
| 147 |
+
# cudaUseFP16 = auto
|
| 148 |
+
# cudaUseNHWC = auto
|
| 149 |
+
|
| 150 |
+
# OpenCL GPU settings--------------------------------------
|
| 151 |
+
# These only apply when using the OpenCL version of KataGo.
|
| 152 |
+
|
| 153 |
+
# Uncomment to tune OpenCL for every board size separately, rather than only the largest possible size
|
| 154 |
+
# openclReTunePerBoardSize = true
|
| 155 |
+
|
| 156 |
+
# IF USING ONE GPU: optionally uncomment and change this if the best device to use is guessed incorrectly.
|
| 157 |
+
# The default behavior tries to guess the 'best' GPU or device on your system to use, usually it will be a good guess.
|
| 158 |
+
# openclDeviceToUse = 0
|
| 159 |
+
|
| 160 |
+
# IF USING TWO GPUS: Uncomment these two lines and replace X and Y with the device ids of the devices you want to use.
|
| 161 |
+
# It might NOT be 0 and 1, some computers will have many OpenCL devices. You can see what the devices are when
|
| 162 |
+
# KataGo starts up - it should print or log all the devices it finds.
|
| 163 |
+
# (AND also set numNNServerThreadsPerModel above)
|
| 164 |
+
# openclDeviceToUseThread0 = X
|
| 165 |
+
# openclDeviceToUseThread1 = Y
|
| 166 |
+
|
| 167 |
+
# IF USING THREE GPUS: Uncomment these three lines and replace X and Y and Z with the device ids of the devices you want to use.
|
| 168 |
+
# It might NOT be 0 and 1 and 2, some computers will have many OpenCL devices. You can see what the devices are when
|
| 169 |
+
# KataGo starts up - it should print or log all the devices it finds.
|
| 170 |
+
# (AND also set numNNServerThreadsPerModel above)
|
| 171 |
+
# openclDeviceToUseThread0 = X
|
| 172 |
+
# openclDeviceToUseThread1 = Y
|
| 173 |
+
# openclDeviceToUseThread2 = Z
|
| 174 |
+
|
| 175 |
+
# You can probably guess the pattern if you have four, five, etc. GPUs.
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# Root move selection and biases------------------------------------------------------------------------------
|
| 179 |
+
# Uncomment and edit any of the below values to change them from their default.
|
| 180 |
+
# Not all of these parameters are applicable to analysis, some are only used for actual play
|
| 181 |
+
|
| 182 |
+
# Temperature for the early game, randomize between chosen moves with this temperature
|
| 183 |
+
# chosenMoveTemperatureEarly = 0.5
|
| 184 |
+
# Decay temperature for the early game by 0.5 every this many moves, scaled with board size.
|
| 185 |
+
# chosenMoveTemperatureHalflife = 19
|
| 186 |
+
# At the end of search after the early game, randomize between chosen moves with this temperature
|
| 187 |
+
# chosenMoveTemperature = 0.10
|
| 188 |
+
# Subtract this many visits from each move prior to applying chosenMoveTemperature
|
| 189 |
+
# (unless all moves have too few visits) to downweight unlikely moves
|
| 190 |
+
# chosenMoveSubtract = 0
|
| 191 |
+
# The same as chosenMoveSubtract but only prunes moves that fall below the threshold, does not affect moves above
|
| 192 |
+
# chosenMovePrune = 1
|
| 193 |
+
|
| 194 |
+
# Number of symmetries to sample (WITH replacement) and average at the root
|
| 195 |
+
# rootNumSymmetriesToSample = 1
|
| 196 |
+
|
| 197 |
+
# Using LCB for move selection?
|
| 198 |
+
# useLcbForSelection = true
|
| 199 |
+
# How many stdevs a move needs to be better than another for LCB selection
|
| 200 |
+
# lcbStdevs = 5.0
|
| 201 |
+
# Only use LCB override when a move has this proportion of visits as the top move
|
| 202 |
+
# minVisitPropForLCB = 0.15
|
| 203 |
+
|
| 204 |
+
# Internal params------------------------------------------------------------------------------
|
| 205 |
+
# Uncomment and edit any of the below values to change them from their default.
|
| 206 |
+
|
| 207 |
+
# Scales the utility of winning/losing
|
| 208 |
+
# winLossUtilityFactor = 1.0
|
| 209 |
+
# Scales the utility for trying to maximize score
|
| 210 |
+
# staticScoreUtilityFactor = 0.10
|
| 211 |
+
# dynamicScoreUtilityFactor = 0.30
|
| 212 |
+
# Adjust dynamic score center this proportion of the way towards zero, capped at a reasonable amount.
|
| 213 |
+
# dynamicScoreCenterZeroWeight = 0.20
|
| 214 |
+
# dynamicScoreCenterScale = 0.75
|
| 215 |
+
# The utility of getting a "no result" due to triple ko or other long cycle in non-superko rulesets (-1 to 1)
|
| 216 |
+
# noResultUtilityForWhite = 0.0
|
| 217 |
+
# The number of wins that a draw counts as, for white. (0 to 1)
|
| 218 |
+
# drawEquivalentWinsForWhite = 0.5
|
| 219 |
+
|
| 220 |
+
# Exploration constant for mcts
|
| 221 |
+
# cpuctExploration = 0.9
|
| 222 |
+
# cpuctExplorationLog = 0.4
|
| 223 |
+
# FPU reduction constant for mcts
|
| 224 |
+
# fpuReductionMax = 0.2
|
| 225 |
+
# rootFpuReductionMax = 0.1
|
| 226 |
+
# Use parent average value for fpu base point instead of point value net estimate
|
| 227 |
+
# fpuUseParentAverage = true
|
| 228 |
+
# Amount to apply a downweighting of children with very bad values relative to good ones
|
| 229 |
+
# valueWeightExponent = 0.5
|
| 230 |
+
# Slight incentive for the bot to behave human-like with regard to passing at the end, filling the dame,
|
| 231 |
+
# not wasting time playing in its own territory, etc, and not play moves that are equivalent in terms of
|
| 232 |
+
# points but a bit more unfriendly to humans.
|
| 233 |
+
# rootEndingBonusPoints = 0.5
|
| 234 |
+
# Make the bot prune useless moves that are just prolonging the game to avoid losing yet
|
| 235 |
+
# rootPruneUselessMoves = true
|
| 236 |
+
|
| 237 |
+
# How big to make the mutex pool for search synchronization
|
| 238 |
+
# mutexPoolSize = 8192
|
| 239 |
+
# How many virtual losses to add when a thread descends through a node
|
| 240 |
+
# numVirtualLossesPerThread = 1
|
katrain/KataGo/cacert.pem
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
katrain/KataGo/contribute_config.cfg
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
serverUrl = https://katagotraining.org/
|
| 3 |
+
username = x
|
| 4 |
+
password = x
|
| 5 |
+
|
| 6 |
+
# How many games should KataGo play at once? For good GPUs, putting too small a number here will be *very* inefficient.
|
| 7 |
+
# For absolute-top-tier GPUs, try numbers like 32, 40, 64, etc.
|
| 8 |
+
# For modern good middle-tier GPUs, you can try numbers like 8 or 16.
|
| 9 |
+
# For very old or weak GPUs, or if you want KataGo to put less load on your system, try 4.
|
| 10 |
+
maxSimultaneousGames = 4
|
| 11 |
+
|
| 12 |
+
# Set to true if you want one of KataGo's games to be streamed to a text file, so you can watch.
|
| 13 |
+
# Follow in a separate shell with a command like the following:
|
| 14 |
+
# Linux: "tail -f watchgame.txt"
|
| 15 |
+
# Windows Powershell: "Get-Content .\watchgame.txt -Tail 50 -Wait"
|
| 16 |
+
watchOngoingGameInFile = false
|
| 17 |
+
watchOngoingGameInFileName = watchgame.txt
|
| 18 |
+
logGamesAsJson = true
|
| 19 |
+
includeOwnership = false
|
| 20 |
+
|
| 21 |
+
# KataGo will only use one GPU by default. You can edit the below if you have multiple GPUs and want to use them all.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# TO USE MULTIPLE GPUS:
|
| 25 |
+
# Set this to the number of GPUs you have and/or would like to use.
|
| 26 |
+
# **AND** if it is more than 1, uncomment the appropriate CUDA or OpenCL section below.
|
| 27 |
+
# numNNServerThreadsPerModel = 1
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# CUDA GPU settings--------------------------------------
|
| 31 |
+
# These only apply when using the CUDA version of KataGo.
|
| 32 |
+
|
| 33 |
+
# IF USING ONE GPU: optionally uncomment and change this if the GPU you want to use turns out to be not device 0
|
| 34 |
+
# cudaDeviceToUse = 0
|
| 35 |
+
|
| 36 |
+
# IF USING TWO GPUS: Uncomment these two lines (AND set numNNServerThreadsPerModel above):
|
| 37 |
+
# cudaDeviceToUseThread0 = 0 # change this if the first GPU you want to use turns out to be not device 0
|
| 38 |
+
# cudaDeviceToUseThread1 = 1 # change this if the second GPU you want to use turns out to be not device 1
|
| 39 |
+
|
| 40 |
+
# IF USING THREE GPUS: Uncomment these three lines (AND set numNNServerThreadsPerModel above):
|
| 41 |
+
# cudaDeviceToUseThread0 = 0 # change this if the first GPU you want to use turns out to be not device 0
|
| 42 |
+
# cudaDeviceToUseThread1 = 1 # change this if the second GPU you want to use turns out to be not device 1
|
| 43 |
+
# cudaDeviceToUseThread2 = 2 # change this if the third GPU you want to use turns out to be not device 2
|
| 44 |
+
|
| 45 |
+
# You can probably guess the pattern if you have four, five, etc. GPUs.
|
| 46 |
+
|
| 47 |
+
# KataGo will automatically use FP16 or not based on the compute capability of your NVIDIA GPU. If you
|
| 48 |
+
# want to try to force a particular behavior though you can uncomment these lines and change them
|
| 49 |
+
# to "true" or "false". E.g. it's using FP16 but on your card that's giving an error, or it's not using
|
| 50 |
+
# FP16 but you think it should.
|
| 51 |
+
# cudaUseFP16 = auto
|
| 52 |
+
# cudaUseNHWC = auto
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# OpenCL GPU settings--------------------------------------
|
| 56 |
+
# These only apply when using the OpenCL version of KataGo.
|
| 57 |
+
|
| 58 |
+
# Uncomment to tune OpenCL for every board size separately, rather than only the largest possible size
|
| 59 |
+
# openclReTunePerBoardSize = true
|
| 60 |
+
|
| 61 |
+
# IF USING ONE GPU: optionally uncomment and change this if the best device to use is guessed incorrectly.
|
| 62 |
+
# The default behavior tries to guess the 'best' GPU or device on your system to use, usually it will be a good guess.
|
| 63 |
+
# openclDeviceToUse = 0
|
| 64 |
+
|
| 65 |
+
# IF USING TWO GPUS: Uncomment these two lines and replace X and Y with the device ids of the devices you want to use.
|
| 66 |
+
# It might NOT be 0 and 1, some computers will have many OpenCL devices. You can see what the devices are when
|
| 67 |
+
# KataGo starts up - it should print or log all the devices it finds.
|
| 68 |
+
# (AND also set numNNServerThreadsPerModel above)
|
| 69 |
+
# openclDeviceToUseThread0 = X
|
| 70 |
+
# openclDeviceToUseThread1 = Y
|
| 71 |
+
|
| 72 |
+
# IF USING THREE GPUS: Uncomment these three lines and replace X and Y and Z with the device ids of the devices you want to use.
|
| 73 |
+
# It might NOT be 0 and 1 and 2, some computers will have many OpenCL devices. You can see what the devices are when
|
| 74 |
+
# KataGo starts up - it should print or log all the devices it finds.
|
| 75 |
+
# (AND also set numNNServerThreadsPerModel above)
|
| 76 |
+
# openclDeviceToUseThread0 = X
|
| 77 |
+
# openclDeviceToUseThread1 = Y
|
| 78 |
+
# openclDeviceToUseThread2 = Z
|
| 79 |
+
|
| 80 |
+
# You can probably guess the pattern if you have four, five, etc. GPUs.
|
| 81 |
+
|
| 82 |
+
# KataGo will automatically use FP16 or not based on testing your GPU during tuning. If you
|
| 83 |
+
# want to try to force a particular behavior though you can uncomment this lines and change it
|
| 84 |
+
# to "true" or "false". This is a fairly blunt setting - more detailed settings are testable
|
| 85 |
+
# by rerunning the tuner with various arguments.
|
| 86 |
+
# openclUseFP16 = auto
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Eigen-specific settings--------------------------------------
|
| 90 |
+
# These only apply when using the Eigen (pure CPU) version of KataGo.
|
| 91 |
+
|
| 92 |
+
# This is the number of CPU threads for evaluating the neural net on the Eigen backend.
|
| 93 |
+
# It defaults to numSearchThreads.
|
| 94 |
+
# numEigenThreadsPerModel = X
|
katrain/KataGo/katago
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ebe2c7dea9c1adf68ae5430509d2faff218f2bb54dcaa090d339554df792f2d9
|
| 3 |
+
size 944632
|
katrain/KataGo/katago.exe
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0684e4f608dc9614e2ac8a068bc66611e7e1dd78a48ad3d2369a66fc304c5e54
|
| 3 |
+
size 4754432
|
katrain/KataGo/libcrypto-1_1-x64.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fef9b83b1ab802d411db78eac01e684e34ca090960d9b88618f054b29f36d9ee
|
| 3 |
+
size 3409920
|
katrain/KataGo/libcrypto-3-x64.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f6560dc57d177417932d04295fcb5f5b9b3414bd3baa75897d8e8bb49e904b7
|
| 3 |
+
size 5148672
|
katrain/KataGo/libssl-1_1-x64.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e803bd8ba59f750935c4e460ff8cb2f37cf03be114380c13c6008b94fdd4a241
|
| 3 |
+
size 682496
|
katrain/KataGo/libssl-3-x64.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:45434db8a17a9ddf3953d85de7e2e4d0c22866593c490e18128ee5c7931db6d1
|
| 3 |
+
size 776704
|
katrain/KataGo/libz.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f41b06ae70e84ce4215e657a9fed61b71b590423d0b19687dced8f95d759b319
|
| 3 |
+
size 95232
|
katrain/KataGo/libzip.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1c3151e9eab8bddffffd0cd180a5258b0de6cb8e780e47f7bd61b48875c1522f
|
| 3 |
+
size 184832
|
katrain/KataGo/msvcp140.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:003da4807acdc912e67edba49be574daa5238bb7acff871d8666d16f8072ff89
|
| 3 |
+
size 579920
|
katrain/KataGo/msvcp140_1.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a61901a4d719a3e1cc4fa8f629218571330331e8dde2ef1f05c34845b180928e
|
| 3 |
+
size 35664
|
katrain/KataGo/msvcp140_2.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3d15cfe238ac1863bbe65501f05d561162f28032b80f2c8d9a1fc7b22f8445a2
|
| 3 |
+
size 197488
|
katrain/KataGo/msvcp140_atomic_wait.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0fcf613254644c2ea451a693d7737741b8041f11decb8feffd3b34e00220620a
|
| 3 |
+
size 50032
|
katrain/KataGo/msvcp140_codecvt_ids.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a714b498ab7b4b0508e69f66ca15196df605844d4d6d5e43969a5f1fd7d7e9e4
|
| 3 |
+
size 31600
|
katrain/KataGo/vcruntime140.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a8f950b4357ec12cfccddc9094cca56a3d5244b95e09ea6e9a746489f2d58736
|
| 3 |
+
size 109392
|
katrain/KataGo/vcruntime140_1.dll
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e4b533a94e02c574780e4b333fcf0889f65ed00d39e32c0fbbda2116f185873f
|
| 3 |
+
size 49520
|
katrain/__init__.py
ADDED
|
File without changes
|
katrain/__main__.py
ADDED
|
@@ -0,0 +1,984 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""isort:skip_file"""
|
| 2 |
+
|
| 3 |
+
# first, logging level lower
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
os.environ["KCFG_KIVY_LOG_LEVEL"] = os.environ.get("KCFG_KIVY_LOG_LEVEL", "warning")
|
| 8 |
+
|
| 9 |
+
from kivy.utils import platform as kivy_platform
|
| 10 |
+
|
| 11 |
+
if kivy_platform == "win":
|
| 12 |
+
from ctypes import windll, c_int64
|
| 13 |
+
|
| 14 |
+
if hasattr(windll.user32, "SetProcessDpiAwarenessContext"):
|
| 15 |
+
windll.user32.SetProcessDpiAwarenessContext(c_int64(-4))
|
| 16 |
+
|
| 17 |
+
import kivy
|
| 18 |
+
|
| 19 |
+
kivy.require("2.0.0")
|
| 20 |
+
|
| 21 |
+
# next, icon
|
| 22 |
+
from katrain.core.utils import find_package_resource, PATHS
|
| 23 |
+
from kivy.config import Config
|
| 24 |
+
|
| 25 |
+
if kivy_platform == "macosx":
|
| 26 |
+
ICON = find_package_resource("katrain/img/icon.icns")
|
| 27 |
+
else:
|
| 28 |
+
ICON = find_package_resource("katrain/img/icon.ico")
|
| 29 |
+
Config.set("kivy", "window_icon", ICON)
|
| 30 |
+
Config.set("input", "mouse", "mouse,multitouch_on_demand")
|
| 31 |
+
|
| 32 |
+
# next, certificates on package builds https://github.com/sanderland/katrain/issues/414
|
| 33 |
+
if getattr(sys, "frozen", False):
|
| 34 |
+
import ssl
|
| 35 |
+
|
| 36 |
+
if ssl.get_default_verify_paths().cafile is None and hasattr(sys, "_MEIPASS"):
|
| 37 |
+
os.environ["SSL_CERT_FILE"] = os.path.join(sys._MEIPASS, "certifi", "cacert.pem")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
import re
|
| 41 |
+
import signal
|
| 42 |
+
import json
|
| 43 |
+
import threading
|
| 44 |
+
import traceback
|
| 45 |
+
from queue import Queue
|
| 46 |
+
import urllib3
|
| 47 |
+
import webbrowser
|
| 48 |
+
import time
|
| 49 |
+
import random
|
| 50 |
+
import glob
|
| 51 |
+
|
| 52 |
+
from kivy.base import ExceptionHandler, ExceptionManager
|
| 53 |
+
from kivy.app import App
|
| 54 |
+
from kivy.core.clipboard import Clipboard
|
| 55 |
+
from kivy.lang import Builder
|
| 56 |
+
from kivy.resources import resource_add_path
|
| 57 |
+
from kivy.uix.popup import Popup
|
| 58 |
+
from kivy.uix.screenmanager import Screen
|
| 59 |
+
from kivy.core.window import Window
|
| 60 |
+
from kivy.uix.widget import Widget
|
| 61 |
+
from kivy.resources import resource_find
|
| 62 |
+
from kivy.properties import NumericProperty, ObjectProperty, StringProperty
|
| 63 |
+
from kivy.clock import Clock
|
| 64 |
+
from kivy.metrics import dp
|
| 65 |
+
from katrain.core.ai import generate_ai_move
|
| 66 |
+
|
| 67 |
+
from katrain.core.lang import DEFAULT_LANGUAGE, i18n
|
| 68 |
+
from katrain.core.constants import (
|
| 69 |
+
OUTPUT_ERROR,
|
| 70 |
+
OUTPUT_KATAGO_STDERR,
|
| 71 |
+
OUTPUT_INFO,
|
| 72 |
+
OUTPUT_DEBUG,
|
| 73 |
+
OUTPUT_EXTRA_DEBUG,
|
| 74 |
+
MODE_ANALYZE,
|
| 75 |
+
HOMEPAGE,
|
| 76 |
+
VERSION,
|
| 77 |
+
STATUS_ERROR,
|
| 78 |
+
STATUS_INFO,
|
| 79 |
+
PLAYING_NORMAL,
|
| 80 |
+
PLAYER_HUMAN,
|
| 81 |
+
SGF_INTERNAL_COMMENTS_MARKER,
|
| 82 |
+
MODE_PLAY,
|
| 83 |
+
DATA_FOLDER,
|
| 84 |
+
AI_DEFAULT,
|
| 85 |
+
)
|
| 86 |
+
from katrain.gui.popups import (
|
| 87 |
+
ConfigTeacherPopup,
|
| 88 |
+
ConfigTimerPopup,
|
| 89 |
+
I18NPopup,
|
| 90 |
+
SaveSGFPopup,
|
| 91 |
+
ContributePopup,
|
| 92 |
+
EngineRecoveryPopup,
|
| 93 |
+
)
|
| 94 |
+
from katrain.gui.sound import play_sound
|
| 95 |
+
from katrain.core.base_katrain import KaTrainBase
|
| 96 |
+
from katrain.core.engine import KataGoEngine
|
| 97 |
+
from katrain.core.contribute_engine import KataGoContributeEngine
|
| 98 |
+
from katrain.core.game import Game, IllegalMoveException, KaTrainSGF, BaseGame
|
| 99 |
+
from katrain.core.sgf_parser import Move, ParseError
|
| 100 |
+
from katrain.gui.popups import ConfigPopup, LoadSGFPopup, NewGamePopup, ConfigAIPopup
|
| 101 |
+
from katrain.gui.theme import Theme
|
| 102 |
+
from kivymd.app import MDApp
|
| 103 |
+
|
| 104 |
+
# used in kv
|
| 105 |
+
from katrain.gui.kivyutils import *
|
| 106 |
+
from katrain.gui.widgets import MoveTree, I18NFileBrowser, SelectionSlider, ScoreGraph # noqa F401
|
| 107 |
+
from katrain.gui.badukpan import AnalysisControls, BadukPanControls, BadukPanWidget # noqa F401
|
| 108 |
+
from katrain.gui.controlspanel import ControlsPanel # noqa F401
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class KaTrainGui(Screen, KaTrainBase):
|
| 112 |
+
"""Top level class responsible for tying everything together"""
|
| 113 |
+
|
| 114 |
+
zen = NumericProperty(0)
|
| 115 |
+
controls = ObjectProperty(None)
|
| 116 |
+
|
| 117 |
+
def __init__(self, **kwargs):
|
| 118 |
+
super().__init__(**kwargs)
|
| 119 |
+
self.engine = None
|
| 120 |
+
self.contributing = False
|
| 121 |
+
|
| 122 |
+
self.new_game_popup = None
|
| 123 |
+
self.fileselect_popup = None
|
| 124 |
+
self.config_popup = None
|
| 125 |
+
self.ai_settings_popup = None
|
| 126 |
+
self.teacher_settings_popup = None
|
| 127 |
+
self.timer_settings_popup = None
|
| 128 |
+
self.contribute_popup = None
|
| 129 |
+
|
| 130 |
+
self.pondering = False
|
| 131 |
+
self.show_move_num = False
|
| 132 |
+
|
| 133 |
+
self.animate_contributing = False
|
| 134 |
+
self.message_queue = Queue()
|
| 135 |
+
|
| 136 |
+
self.last_key_down = None
|
| 137 |
+
self.last_focus_event = 0
|
| 138 |
+
|
| 139 |
+
def log(self, message, level=OUTPUT_INFO):
|
| 140 |
+
super().log(message, level)
|
| 141 |
+
if level == OUTPUT_KATAGO_STDERR and "ERROR" not in self.controls.status.text:
|
| 142 |
+
if self.contributing:
|
| 143 |
+
self.controls.set_status(message, STATUS_INFO)
|
| 144 |
+
elif "starting" in message.lower():
|
| 145 |
+
self.controls.set_status("KataGo engine starting...", STATUS_INFO)
|
| 146 |
+
elif message.startswith("Tuning"):
|
| 147 |
+
self.controls.set_status(
|
| 148 |
+
"KataGo is tuning settings for first startup, please wait." + message, STATUS_INFO
|
| 149 |
+
)
|
| 150 |
+
return
|
| 151 |
+
elif "ready" in message.lower():
|
| 152 |
+
self.controls.set_status("KataGo engine ready.", STATUS_INFO)
|
| 153 |
+
if (
|
| 154 |
+
level == OUTPUT_ERROR
|
| 155 |
+
or (level == OUTPUT_KATAGO_STDERR and "error" in message.lower() and "tuning" not in message.lower())
|
| 156 |
+
) and getattr(self, "controls", None):
|
| 157 |
+
self.controls.set_status(f"ERROR: {message}", STATUS_ERROR)
|
| 158 |
+
|
| 159 |
+
def handle_animations(self, *_args):
|
| 160 |
+
if self.contributing and self.animate_contributing:
|
| 161 |
+
self.engine.advance_showing_game()
|
| 162 |
+
if (self.contributing and self.animate_contributing) or self.pondering:
|
| 163 |
+
self.board_controls.engine_status_pondering += 5
|
| 164 |
+
else:
|
| 165 |
+
self.board_controls.engine_status_pondering = -1
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def play_analyze_mode(self):
|
| 169 |
+
return self.play_mode.mode
|
| 170 |
+
|
| 171 |
+
def toggle_continuous_analysis(self, quiet=False):
|
| 172 |
+
if self.contributing:
|
| 173 |
+
self.animate_contributing = not self.animate_contributing
|
| 174 |
+
else:
|
| 175 |
+
if self.pondering:
|
| 176 |
+
self.controls.set_status("", STATUS_INFO)
|
| 177 |
+
elif not quiet: # See #549
|
| 178 |
+
Clock.schedule_once(self.analysis_controls.hints.activate, 0)
|
| 179 |
+
self.pondering = not self.pondering
|
| 180 |
+
self.update_state()
|
| 181 |
+
|
| 182 |
+
def toggle_move_num(self):
|
| 183 |
+
self.show_move_num = not self.show_move_num
|
| 184 |
+
self.update_state()
|
| 185 |
+
|
| 186 |
+
def start(self):
|
| 187 |
+
if self.engine:
|
| 188 |
+
return
|
| 189 |
+
self.board_gui.trainer_config = self.config("trainer")
|
| 190 |
+
self.engine = KataGoEngine(self, self.config("engine"))
|
| 191 |
+
threading.Thread(target=self._message_loop_thread, daemon=True).start()
|
| 192 |
+
sgf_args = [
|
| 193 |
+
f
|
| 194 |
+
for f in sys.argv[1:]
|
| 195 |
+
if os.path.isfile(f) and any(f.lower().endswith(ext) for ext in ["sgf", "ngf", "gib"])
|
| 196 |
+
]
|
| 197 |
+
if sgf_args:
|
| 198 |
+
self.load_sgf_file(sgf_args[0], fast=True, rewind=True)
|
| 199 |
+
else:
|
| 200 |
+
self._do_new_game()
|
| 201 |
+
|
| 202 |
+
Clock.schedule_interval(self.handle_animations, 0.1)
|
| 203 |
+
Window.request_keyboard(None, self, "").bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up)
|
| 204 |
+
|
| 205 |
+
def set_focus_event(*args):
|
| 206 |
+
self.last_focus_event = time.time()
|
| 207 |
+
|
| 208 |
+
MDApp.get_running_app().root_window.bind(focus=set_focus_event)
|
| 209 |
+
|
| 210 |
+
def update_gui(self, cn, redraw_board=False):
|
| 211 |
+
# Handle prisoners and next player display
|
| 212 |
+
prisoners = self.game.prisoner_count
|
| 213 |
+
top, bot = [w.__self__ for w in self.board_controls.circles] # no weakref
|
| 214 |
+
if self.next_player_info.player == "W":
|
| 215 |
+
top, bot = bot, top
|
| 216 |
+
self.controls.players["W"].active = True
|
| 217 |
+
self.controls.players["B"].active = False
|
| 218 |
+
else:
|
| 219 |
+
self.controls.players["W"].active = False
|
| 220 |
+
self.controls.players["B"].active = True
|
| 221 |
+
self.board_controls.mid_circles_container.clear_widgets()
|
| 222 |
+
self.board_controls.mid_circles_container.add_widget(bot)
|
| 223 |
+
self.board_controls.mid_circles_container.add_widget(top)
|
| 224 |
+
|
| 225 |
+
self.controls.players["W"].captures = prisoners["W"]
|
| 226 |
+
self.controls.players["B"].captures = prisoners["B"]
|
| 227 |
+
|
| 228 |
+
# update engine status dot
|
| 229 |
+
if not self.engine or not self.engine.katago_process or self.engine.katago_process.poll() is not None:
|
| 230 |
+
self.board_controls.engine_status_col = Theme.ENGINE_DOWN_COLOR
|
| 231 |
+
elif self.engine.is_idle():
|
| 232 |
+
self.board_controls.engine_status_col = Theme.ENGINE_READY_COLOR
|
| 233 |
+
else:
|
| 234 |
+
self.board_controls.engine_status_col = Theme.ENGINE_BUSY_COLOR
|
| 235 |
+
self.board_controls.queries_remaining = self.engine.queries_remaining()
|
| 236 |
+
|
| 237 |
+
# redraw board/stones
|
| 238 |
+
if redraw_board:
|
| 239 |
+
self.board_gui.draw_board()
|
| 240 |
+
self.board_gui.redraw_board_contents_trigger()
|
| 241 |
+
self.controls.update_evaluation()
|
| 242 |
+
self.controls.update_timer(1)
|
| 243 |
+
# update move tree
|
| 244 |
+
self.controls.move_tree.current_node = self.game.current_node
|
| 245 |
+
|
| 246 |
+
def update_state(self, redraw_board=False): # redirect to message queue thread
|
| 247 |
+
self("update_state", redraw_board=redraw_board)
|
| 248 |
+
|
| 249 |
+
def _do_update_state(
|
| 250 |
+
self, redraw_board=False
|
| 251 |
+
): # is called after every message and on receiving analyses and config changes
|
| 252 |
+
# AI and Trainer/auto-undo handlers
|
| 253 |
+
if not self.game or not self.game.current_node:
|
| 254 |
+
return
|
| 255 |
+
cn = self.game.current_node
|
| 256 |
+
if not self.contributing:
|
| 257 |
+
last_player, next_player = self.players_info[cn.player], self.players_info[cn.next_player]
|
| 258 |
+
if self.play_analyze_mode == MODE_PLAY and self.nav_drawer.state != "open" and self.popup_open is None:
|
| 259 |
+
points_lost = cn.points_lost
|
| 260 |
+
if (
|
| 261 |
+
last_player.human
|
| 262 |
+
and cn.analysis_complete
|
| 263 |
+
and points_lost is not None
|
| 264 |
+
and points_lost > self.config("trainer/eval_thresholds")[-4]
|
| 265 |
+
):
|
| 266 |
+
self.play_mistake_sound(cn)
|
| 267 |
+
teaching_undo = cn.player and last_player.being_taught and cn.parent
|
| 268 |
+
if (
|
| 269 |
+
teaching_undo
|
| 270 |
+
and cn.analysis_complete
|
| 271 |
+
and cn.parent.analysis_complete
|
| 272 |
+
and not cn.children
|
| 273 |
+
and not self.game.end_result
|
| 274 |
+
):
|
| 275 |
+
self.game.analyze_undo(cn) # not via message loop
|
| 276 |
+
if (
|
| 277 |
+
cn.analysis_complete
|
| 278 |
+
and next_player.ai
|
| 279 |
+
and not cn.children
|
| 280 |
+
and not self.game.end_result
|
| 281 |
+
and not (teaching_undo and cn.auto_undo is None)
|
| 282 |
+
): # cn mismatch stops this if undo fired. avoid message loop here or fires repeatedly.
|
| 283 |
+
self._do_ai_move(cn)
|
| 284 |
+
Clock.schedule_once(self._play_stone_sound, 0.25)
|
| 285 |
+
if self.engine:
|
| 286 |
+
if self.pondering:
|
| 287 |
+
self.game.analyze_extra("ponder")
|
| 288 |
+
else:
|
| 289 |
+
self.engine.stop_pondering()
|
| 290 |
+
Clock.schedule_once(lambda _dt: self.update_gui(cn, redraw_board=redraw_board), -1) # trigger?
|
| 291 |
+
|
| 292 |
+
def update_player(self, bw, **kwargs):
|
| 293 |
+
super().update_player(bw, **kwargs)
|
| 294 |
+
if self.game:
|
| 295 |
+
sgf_name = self.game.root.get_property("P" + bw)
|
| 296 |
+
self.players_info[bw].name = None if not sgf_name or SGF_INTERNAL_COMMENTS_MARKER in sgf_name else sgf_name
|
| 297 |
+
if self.controls:
|
| 298 |
+
self.controls.update_players()
|
| 299 |
+
self.update_state()
|
| 300 |
+
for player_setup_block in PlayerSetupBlock.INSTANCES:
|
| 301 |
+
player_setup_block.update_player_info(bw, self.players_info[bw])
|
| 302 |
+
|
| 303 |
+
def set_note(self, note):
|
| 304 |
+
self.game.current_node.note = note
|
| 305 |
+
|
| 306 |
+
# The message loop is here to make sure moves happen in the right order, and slow operations don't hang the GUI
|
| 307 |
+
def _message_loop_thread(self):
|
| 308 |
+
while True:
|
| 309 |
+
game, msg, args, kwargs = self.message_queue.get()
|
| 310 |
+
try:
|
| 311 |
+
self.log(f"Message Loop Received {msg}: {args} for Game {game}", OUTPUT_EXTRA_DEBUG)
|
| 312 |
+
if game != self.game.game_id:
|
| 313 |
+
self.log(
|
| 314 |
+
f"Message skipped as it is outdated (current game is {self.game.game_id}", OUTPUT_EXTRA_DEBUG
|
| 315 |
+
)
|
| 316 |
+
continue
|
| 317 |
+
msg = msg.replace("-", "_")
|
| 318 |
+
if self.contributing:
|
| 319 |
+
if msg not in [
|
| 320 |
+
"katago_contribute",
|
| 321 |
+
"redo",
|
| 322 |
+
"undo",
|
| 323 |
+
"update_state",
|
| 324 |
+
"save_game",
|
| 325 |
+
"find_mistake",
|
| 326 |
+
]:
|
| 327 |
+
self.controls.set_status(
|
| 328 |
+
i18n._("gui-locked").format(action=msg), STATUS_INFO, check_level=False
|
| 329 |
+
)
|
| 330 |
+
continue
|
| 331 |
+
fn = getattr(self, f"_do_{msg}")
|
| 332 |
+
fn(*args, **kwargs)
|
| 333 |
+
if msg != "update_state":
|
| 334 |
+
self._do_update_state()
|
| 335 |
+
except Exception as exc:
|
| 336 |
+
self.log(f"Exception in processing message {msg} {args}: {exc}", OUTPUT_ERROR)
|
| 337 |
+
traceback.print_exc()
|
| 338 |
+
|
| 339 |
+
def __call__(self, message, *args, **kwargs):
|
| 340 |
+
if self.game:
|
| 341 |
+
if message.endswith("popup"): # gui code needs to run in main kivy thread.
|
| 342 |
+
if self.contributing and "save" not in message and message != "contribute-popup":
|
| 343 |
+
self.controls.set_status(
|
| 344 |
+
i18n._("gui-locked").format(action=message), STATUS_INFO, check_level=False
|
| 345 |
+
)
|
| 346 |
+
return
|
| 347 |
+
fn = getattr(self, f"_do_{message.replace('-', '_')}")
|
| 348 |
+
Clock.schedule_once(lambda _dt: fn(*args, **kwargs), -1)
|
| 349 |
+
else: # game related actions
|
| 350 |
+
self.message_queue.put([self.game.game_id, message, args, kwargs])
|
| 351 |
+
|
| 352 |
+
def _do_new_game(self, move_tree=None, analyze_fast=False, sgf_filename=None):
|
| 353 |
+
self.pondering = False
|
| 354 |
+
mode = self.play_analyze_mode
|
| 355 |
+
if (move_tree is not None and mode == MODE_PLAY) or (move_tree is None and mode == MODE_ANALYZE):
|
| 356 |
+
self.play_mode.switch_ui_mode() # for new game, go to play, for loaded, analyze
|
| 357 |
+
self.board_gui.animating_pv = None
|
| 358 |
+
self.board_gui.reset_rotation()
|
| 359 |
+
self.engine.on_new_game() # clear queries
|
| 360 |
+
self.game = Game(
|
| 361 |
+
self,
|
| 362 |
+
self.engine,
|
| 363 |
+
move_tree=move_tree,
|
| 364 |
+
analyze_fast=analyze_fast or not move_tree,
|
| 365 |
+
sgf_filename=sgf_filename,
|
| 366 |
+
)
|
| 367 |
+
for bw, player_info in self.players_info.items():
|
| 368 |
+
player_info.sgf_rank = self.game.root.get_property(bw + "R")
|
| 369 |
+
player_info.calculated_rank = None
|
| 370 |
+
if sgf_filename is not None: # load game->no ai player
|
| 371 |
+
player_info.player_type = PLAYER_HUMAN
|
| 372 |
+
player_info.player_subtype = PLAYING_NORMAL
|
| 373 |
+
self.update_player(bw, player_type=player_info.player_type, player_subtype=player_info.player_subtype)
|
| 374 |
+
self.controls.graph.initialize_from_game(self.game.root)
|
| 375 |
+
self.update_state(redraw_board=True)
|
| 376 |
+
|
| 377 |
+
def _do_katago_contribute(self):
|
| 378 |
+
if self.contributing and not self.engine.server_error and self.engine.katago_process is not None:
|
| 379 |
+
return
|
| 380 |
+
self.contributing = self.animate_contributing = True # special mode
|
| 381 |
+
if self.play_analyze_mode == MODE_PLAY: # switch to analysis view
|
| 382 |
+
self.play_mode.switch_ui_mode()
|
| 383 |
+
self.pondering = False
|
| 384 |
+
self.board_gui.animating_pv = None
|
| 385 |
+
for bw, player_info in self.players_info.items():
|
| 386 |
+
self.update_player(bw, player_type=PLAYER_AI, player_subtype=AI_DEFAULT)
|
| 387 |
+
self.engine.shutdown(finish=False)
|
| 388 |
+
self.engine = KataGoContributeEngine(self)
|
| 389 |
+
self.game = BaseGame(self)
|
| 390 |
+
|
| 391 |
+
def _do_insert_mode(self, mode="toggle"):
|
| 392 |
+
self.game.set_insert_mode(mode)
|
| 393 |
+
if self.play_analyze_mode != MODE_ANALYZE:
|
| 394 |
+
self.play_mode.switch_ui_mode()
|
| 395 |
+
|
| 396 |
+
def _do_ai_move(self, node=None):
|
| 397 |
+
if node is None or self.game.current_node == node:
|
| 398 |
+
mode = self.next_player_info.strategy
|
| 399 |
+
settings = self.config(f"ai/{mode}")
|
| 400 |
+
if settings is not None:
|
| 401 |
+
generate_ai_move(self.game, mode, settings)
|
| 402 |
+
else:
|
| 403 |
+
self.log(f"AI Mode {mode} not found!", OUTPUT_ERROR)
|
| 404 |
+
|
| 405 |
+
def _do_undo(self, n_times=1):
|
| 406 |
+
if n_times == "smart":
|
| 407 |
+
n_times = 1
|
| 408 |
+
if self.play_analyze_mode == MODE_PLAY and self.last_player_info.ai and self.next_player_info.human:
|
| 409 |
+
n_times = 2
|
| 410 |
+
self.board_gui.animating_pv = None
|
| 411 |
+
self.game.undo(n_times)
|
| 412 |
+
|
| 413 |
+
def _do_reset_analysis(self):
|
| 414 |
+
self.game.reset_current_analysis()
|
| 415 |
+
|
| 416 |
+
def _do_resign(self):
|
| 417 |
+
self.game.current_node.end_state = f"{self.game.current_node.player}+R"
|
| 418 |
+
|
| 419 |
+
def _do_redo(self, n_times=1):
|
| 420 |
+
self.board_gui.animating_pv = None
|
| 421 |
+
self.game.redo(n_times)
|
| 422 |
+
|
| 423 |
+
def _do_rotate(self):
|
| 424 |
+
self.board_gui.rotate_gridpos()
|
| 425 |
+
|
| 426 |
+
def _do_find_mistake(self, fn="redo"):
|
| 427 |
+
self.board_gui.animating_pv = None
|
| 428 |
+
getattr(self.game, fn)(9999, stop_on_mistake=self.config("trainer/eval_thresholds")[-4])
|
| 429 |
+
|
| 430 |
+
def _do_switch_branch(self, *args):
|
| 431 |
+
self.board_gui.animating_pv = None
|
| 432 |
+
self.controls.move_tree.switch_branch(*args)
|
| 433 |
+
|
| 434 |
+
def _play_stone_sound(self, _dt=None):
|
| 435 |
+
play_sound(random.choice(Theme.STONE_SOUNDS))
|
| 436 |
+
|
| 437 |
+
def _do_play(self, coords):
|
| 438 |
+
self.board_gui.animating_pv = None
|
| 439 |
+
try:
|
| 440 |
+
old_prisoner_count = self.game.prisoner_count["W"] + self.game.prisoner_count["B"]
|
| 441 |
+
self.game.play(Move(coords, player=self.next_player_info.player))
|
| 442 |
+
if old_prisoner_count < self.game.prisoner_count["W"] + self.game.prisoner_count["B"]:
|
| 443 |
+
play_sound(Theme.CAPTURING_SOUND)
|
| 444 |
+
elif not self.game.current_node.is_pass:
|
| 445 |
+
self._play_stone_sound()
|
| 446 |
+
|
| 447 |
+
except IllegalMoveException as e:
|
| 448 |
+
self.controls.set_status(f"Illegal Move: {str(e)}", STATUS_ERROR)
|
| 449 |
+
|
| 450 |
+
def _do_analyze_extra(self, mode, **kwargs):
|
| 451 |
+
self.game.analyze_extra(mode, **kwargs)
|
| 452 |
+
|
| 453 |
+
def _do_selfplay_setup(self, until_move, target_b_advantage=None):
|
| 454 |
+
self.game.selfplay(int(until_move) if isinstance(until_move, float) else until_move, target_b_advantage)
|
| 455 |
+
|
| 456 |
+
def _do_select_box(self):
|
| 457 |
+
self.controls.set_status(i18n._("analysis:region:start"), STATUS_INFO)
|
| 458 |
+
self.board_gui.selecting_region_of_interest = True
|
| 459 |
+
|
| 460 |
+
def _do_new_game_popup(self):
|
| 461 |
+
self.controls.timer.paused = True
|
| 462 |
+
if not self.new_game_popup:
|
| 463 |
+
self.new_game_popup = I18NPopup(
|
| 464 |
+
title_key="New Game title", size=[dp(800), dp(900)], content=NewGamePopup(self)
|
| 465 |
+
).__self__
|
| 466 |
+
self.new_game_popup.content.popup = self.new_game_popup
|
| 467 |
+
self.new_game_popup.open()
|
| 468 |
+
self.new_game_popup.content.update_from_current_game()
|
| 469 |
+
|
| 470 |
+
def _do_timer_popup(self):
|
| 471 |
+
self.controls.timer.paused = True
|
| 472 |
+
if not self.timer_settings_popup:
|
| 473 |
+
self.timer_settings_popup = I18NPopup(
|
| 474 |
+
title_key="timer settings", size=[dp(600), dp(500)], content=ConfigTimerPopup(self)
|
| 475 |
+
).__self__
|
| 476 |
+
self.timer_settings_popup.content.popup = self.timer_settings_popup
|
| 477 |
+
self.timer_settings_popup.open()
|
| 478 |
+
|
| 479 |
+
def _do_teacher_popup(self):
|
| 480 |
+
self.controls.timer.paused = True
|
| 481 |
+
if not self.teacher_settings_popup:
|
| 482 |
+
self.teacher_settings_popup = I18NPopup(
|
| 483 |
+
title_key="teacher settings", size=[dp(800), dp(825)], content=ConfigTeacherPopup(self)
|
| 484 |
+
).__self__
|
| 485 |
+
self.teacher_settings_popup.content.popup = self.teacher_settings_popup
|
| 486 |
+
self.teacher_settings_popup.open()
|
| 487 |
+
|
| 488 |
+
def _do_config_popup(self):
|
| 489 |
+
self.controls.timer.paused = True
|
| 490 |
+
if not self.config_popup:
|
| 491 |
+
self.config_popup = I18NPopup(
|
| 492 |
+
title_key="general settings title", size=[dp(1200), dp(950)], content=ConfigPopup(self)
|
| 493 |
+
).__self__
|
| 494 |
+
self.config_popup.content.popup = self.config_popup
|
| 495 |
+
self.config_popup.title += ": " + self.config_file
|
| 496 |
+
self.config_popup.open()
|
| 497 |
+
|
| 498 |
+
def _do_contribute_popup(self):
|
| 499 |
+
if not self.contribute_popup:
|
| 500 |
+
self.contribute_popup = I18NPopup(
|
| 501 |
+
title_key="contribute settings title", size=[dp(1100), dp(800)], content=ContributePopup(self)
|
| 502 |
+
).__self__
|
| 503 |
+
self.contribute_popup.content.popup = self.contribute_popup
|
| 504 |
+
self.contribute_popup.open()
|
| 505 |
+
|
| 506 |
+
def _do_ai_popup(self):
|
| 507 |
+
self.controls.timer.paused = True
|
| 508 |
+
if not self.ai_settings_popup:
|
| 509 |
+
self.ai_settings_popup = I18NPopup(
|
| 510 |
+
title_key="ai settings", size=[dp(750), dp(750)], content=ConfigAIPopup(self)
|
| 511 |
+
).__self__
|
| 512 |
+
self.ai_settings_popup.content.popup = self.ai_settings_popup
|
| 513 |
+
self.ai_settings_popup.open()
|
| 514 |
+
|
| 515 |
+
def _do_engine_recovery_popup(self, error_message, code):
|
| 516 |
+
current_open = self.popup_open
|
| 517 |
+
if current_open and isinstance(current_open.content, EngineRecoveryPopup):
|
| 518 |
+
self.log(f"Not opening engine recovery popup with {error_message} as one is already open", OUTPUT_DEBUG)
|
| 519 |
+
return
|
| 520 |
+
popup = I18NPopup(
|
| 521 |
+
title_key="engine recovery",
|
| 522 |
+
size=[dp(600), dp(700)],
|
| 523 |
+
content=EngineRecoveryPopup(self, error_message=error_message, code=code),
|
| 524 |
+
).__self__
|
| 525 |
+
popup.content.popup = popup
|
| 526 |
+
popup.open()
|
| 527 |
+
|
| 528 |
+
def _do_tsumego_frame(self, ko, margin):
|
| 529 |
+
from katrain.core.tsumego_frame import tsumego_frame_from_katrain_game
|
| 530 |
+
|
| 531 |
+
if not self.game.stones:
|
| 532 |
+
return
|
| 533 |
+
|
| 534 |
+
black_to_play_p = self.next_player_info.player == "B"
|
| 535 |
+
node, analysis_region = tsumego_frame_from_katrain_game(
|
| 536 |
+
self.game, self.game.komi, black_to_play_p, ko_p=ko, margin=margin
|
| 537 |
+
)
|
| 538 |
+
self.game.set_current_node(node)
|
| 539 |
+
if self.play_mode.mode == MODE_PLAY:
|
| 540 |
+
self.play_mode.switch_ui_mode() # go to analysis mode
|
| 541 |
+
if analysis_region:
|
| 542 |
+
flattened_region = [
|
| 543 |
+
analysis_region[0][1],
|
| 544 |
+
analysis_region[0][0],
|
| 545 |
+
analysis_region[1][1],
|
| 546 |
+
analysis_region[1][0],
|
| 547 |
+
]
|
| 548 |
+
self.game.set_region_of_interest(flattened_region)
|
| 549 |
+
node.analyze(self.game.engines[node.next_player])
|
| 550 |
+
self.update_state(redraw_board=True)
|
| 551 |
+
|
| 552 |
+
def play_mistake_sound(self, node):
|
| 553 |
+
if self.config("timer/sound") and node.played_mistake_sound is None and Theme.MISTAKE_SOUNDS:
|
| 554 |
+
node.played_mistake_sound = True
|
| 555 |
+
play_sound(random.choice(Theme.MISTAKE_SOUNDS))
|
| 556 |
+
|
| 557 |
+
def load_sgf_file(self, file, fast=False, rewind=True):
|
| 558 |
+
if self.contributing:
|
| 559 |
+
return
|
| 560 |
+
try:
|
| 561 |
+
file = os.path.abspath(file)
|
| 562 |
+
move_tree = KaTrainSGF.parse_file(file)
|
| 563 |
+
except (ParseError, FileNotFoundError) as e:
|
| 564 |
+
self.log(i18n._("Failed to load SGF").format(error=e), OUTPUT_ERROR)
|
| 565 |
+
return
|
| 566 |
+
self._do_new_game(move_tree=move_tree, analyze_fast=fast, sgf_filename=file)
|
| 567 |
+
if not rewind:
|
| 568 |
+
self.game.redo(999)
|
| 569 |
+
|
| 570 |
+
def _do_analyze_sgf_popup(self):
|
| 571 |
+
if not self.fileselect_popup:
|
| 572 |
+
popup_contents = LoadSGFPopup(self)
|
| 573 |
+
popup_contents.filesel.path = os.path.abspath(os.path.expanduser(self.config("general/sgf_load", ".")))
|
| 574 |
+
self.fileselect_popup = I18NPopup(
|
| 575 |
+
title_key="load sgf title", size=[dp(1200), dp(800)], content=popup_contents
|
| 576 |
+
).__self__
|
| 577 |
+
|
| 578 |
+
def readfile(*_args):
|
| 579 |
+
filename = popup_contents.filesel.filename
|
| 580 |
+
self.fileselect_popup.dismiss()
|
| 581 |
+
path, file = os.path.split(filename)
|
| 582 |
+
if path != self.config("general/sgf_load"):
|
| 583 |
+
self.log(f"Updating sgf load path default to {path}", OUTPUT_DEBUG)
|
| 584 |
+
self._config["general"]["sgf_load"] = path
|
| 585 |
+
popup_contents.update_config(False)
|
| 586 |
+
self.save_config("general")
|
| 587 |
+
self.load_sgf_file(filename, popup_contents.fast.active, popup_contents.rewind.active)
|
| 588 |
+
|
| 589 |
+
popup_contents.filesel.on_success = readfile
|
| 590 |
+
popup_contents.filesel.on_submit = readfile
|
| 591 |
+
self.fileselect_popup.open()
|
| 592 |
+
self.fileselect_popup.content.filesel.ids.list_view._trigger_update()
|
| 593 |
+
|
| 594 |
+
def _do_save_game(self, filename=None):
|
| 595 |
+
filename = filename or self.game.sgf_filename
|
| 596 |
+
if not filename:
|
| 597 |
+
return self("save-game-as-popup")
|
| 598 |
+
try:
|
| 599 |
+
msg = self.game.write_sgf(filename)
|
| 600 |
+
self.log(msg, OUTPUT_INFO)
|
| 601 |
+
self.controls.set_status(msg, STATUS_INFO, check_level=False)
|
| 602 |
+
except Exception as e:
|
| 603 |
+
self.log(f"Failed to save SGF to {filename}: {e}", OUTPUT_ERROR)
|
| 604 |
+
|
| 605 |
+
def _do_save_game_as_popup(self):
|
| 606 |
+
popup_contents = SaveSGFPopup(suggested_filename=self.game.generate_filename())
|
| 607 |
+
save_game_popup = I18NPopup(
|
| 608 |
+
title_key="save sgf title", size=[dp(1200), dp(800)], content=popup_contents
|
| 609 |
+
).__self__
|
| 610 |
+
|
| 611 |
+
def readfile(*_args):
|
| 612 |
+
filename = popup_contents.filesel.filename
|
| 613 |
+
if not filename.lower().endswith(".sgf"):
|
| 614 |
+
filename += ".sgf"
|
| 615 |
+
save_game_popup.dismiss()
|
| 616 |
+
path, file = os.path.split(filename.strip())
|
| 617 |
+
if not path:
|
| 618 |
+
path = popup_contents.filesel.path # whatever dir is shown
|
| 619 |
+
if path != self.config("general/sgf_save"):
|
| 620 |
+
self.log(f"Updating sgf save path default to {path}", OUTPUT_DEBUG)
|
| 621 |
+
self._config["general"]["sgf_save"] = path
|
| 622 |
+
self.save_config("general")
|
| 623 |
+
self._do_save_game(os.path.join(path, file))
|
| 624 |
+
|
| 625 |
+
popup_contents.filesel.on_success = readfile
|
| 626 |
+
popup_contents.filesel.on_submit = readfile
|
| 627 |
+
save_game_popup.open()
|
| 628 |
+
|
| 629 |
+
def load_sgf_from_clipboard(self):
|
| 630 |
+
clipboard = Clipboard.paste()
|
| 631 |
+
if not clipboard:
|
| 632 |
+
self.controls.set_status("Ctrl-V pressed but clipboard is empty.", STATUS_INFO)
|
| 633 |
+
return
|
| 634 |
+
|
| 635 |
+
url_match = re.match(r"(?P<url>https?://[^\s]+)", clipboard)
|
| 636 |
+
if url_match:
|
| 637 |
+
self.log("Recognized url: " + url_match.group(), OUTPUT_INFO)
|
| 638 |
+
http = urllib3.PoolManager()
|
| 639 |
+
response = http.request("GET", url_match.group())
|
| 640 |
+
clipboard = response.data.decode("utf-8")
|
| 641 |
+
|
| 642 |
+
try:
|
| 643 |
+
move_tree = KaTrainSGF.parse_sgf(clipboard)
|
| 644 |
+
except Exception as exc:
|
| 645 |
+
self.controls.set_status(
|
| 646 |
+
i18n._("Failed to import from clipboard").format(error=exc, contents=clipboard[:50]), STATUS_INFO
|
| 647 |
+
)
|
| 648 |
+
return
|
| 649 |
+
move_tree.nodes_in_tree[-1].analyze(
|
| 650 |
+
self.engine, analyze_fast=False
|
| 651 |
+
) # speed up result for looking at end of game
|
| 652 |
+
self._do_new_game(move_tree=move_tree, analyze_fast=True)
|
| 653 |
+
self("redo", 9999)
|
| 654 |
+
self.log("Imported game from clipboard.", OUTPUT_INFO)
|
| 655 |
+
|
| 656 |
+
def on_touch_up(self, touch):
|
| 657 |
+
if touch.is_mouse_scrolling:
|
| 658 |
+
touching_board = self.board_gui.collide_point(*touch.pos) or self.board_controls.collide_point(*touch.pos)
|
| 659 |
+
touching_control_nonscroll = self.controls.collide_point(
|
| 660 |
+
*touch.pos
|
| 661 |
+
) and not self.controls.notes_panel.collide_point(*touch.pos)
|
| 662 |
+
if self.board_gui.animating_pv is not None and touching_board:
|
| 663 |
+
if touch.button == "scrollup":
|
| 664 |
+
self.board_gui.adjust_animate_pv_index(1)
|
| 665 |
+
elif touch.button == "scrolldown":
|
| 666 |
+
self.board_gui.adjust_animate_pv_index(-1)
|
| 667 |
+
elif touching_board or touching_control_nonscroll: # scroll through moves
|
| 668 |
+
if touch.button == "scrollup":
|
| 669 |
+
self("redo")
|
| 670 |
+
elif touch.button == "scrolldown":
|
| 671 |
+
self("undo")
|
| 672 |
+
return super().on_touch_up(touch)
|
| 673 |
+
|
| 674 |
+
@property
|
| 675 |
+
def shortcuts(self):
|
| 676 |
+
return {
|
| 677 |
+
k: v
|
| 678 |
+
for ks, v in [
|
| 679 |
+
(Theme.KEY_ANALYSIS_CONTROLS_SHOW_CHILDREN, self.analysis_controls.show_children),
|
| 680 |
+
(Theme.KEY_ANALYSIS_CONTROLS_EVAL, self.analysis_controls.eval),
|
| 681 |
+
(Theme.KEY_ANALYSIS_CONTROLS_HINTS, self.analysis_controls.hints),
|
| 682 |
+
(Theme.KEY_ANALYSIS_CONTROLS_OWNERSHIP, self.analysis_controls.ownership),
|
| 683 |
+
(Theme.KEY_ANALYSIS_CONTROLS_POLICY, self.analysis_controls.policy),
|
| 684 |
+
(Theme.KEY_AI_MOVE, ("ai-move",)),
|
| 685 |
+
(Theme.KEY_ANALYZE_EXTRA_EXTRA, ("analyze-extra", "extra")),
|
| 686 |
+
(Theme.KEY_ANALYZE_EXTRA_EQUALIZE, ("analyze-extra", "equalize")),
|
| 687 |
+
(Theme.KEY_ANALYZE_EXTRA_SWEEP, ("analyze-extra", "sweep")),
|
| 688 |
+
(Theme.KEY_ANALYZE_EXTRA_ALTERNATIVE, ("analyze-extra", "alternative")),
|
| 689 |
+
(Theme.KEY_SELECT_BOX, ("select-box",)),
|
| 690 |
+
(Theme.KEY_RESET_ANALYSIS, ("reset-analysis",)),
|
| 691 |
+
(Theme.KEY_INSERT_MODE, ("insert-mode",)),
|
| 692 |
+
(Theme.KEY_PASS, ("play", None)),
|
| 693 |
+
(Theme.KEY_SELFPLAY_TO_END, ("selfplay-setup", "end", None)),
|
| 694 |
+
(Theme.KEY_NAV_PREV_BRANCH, ("undo", "branch")),
|
| 695 |
+
(Theme.KEY_NAV_BRANCH_DOWN, ("switch-branch", 1)),
|
| 696 |
+
(Theme.KEY_NAV_BRANCH_UP, ("switch-branch", -1)),
|
| 697 |
+
(Theme.KEY_TIMER_POPUP, ("timer-popup",)),
|
| 698 |
+
(Theme.KEY_TEACHER_POPUP, ("teacher-popup",)),
|
| 699 |
+
(Theme.KEY_AI_POPUP, ("ai-popup",)),
|
| 700 |
+
(Theme.KEY_CONFIG_POPUP, ("config-popup",)),
|
| 701 |
+
(Theme.KEY_CONTRIBUTE_POPUP, ("contribute-popup",)),
|
| 702 |
+
(Theme.KEY_STOP_ANALYSIS, ("analyze-extra", "stop")),
|
| 703 |
+
]
|
| 704 |
+
for k in (ks if isinstance(ks, list) else [ks])
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
@property
|
| 708 |
+
def popup_open(self) -> Popup:
|
| 709 |
+
app = App.get_running_app()
|
| 710 |
+
if app:
|
| 711 |
+
first_child = app.root_window.children[0]
|
| 712 |
+
return first_child if isinstance(first_child, Popup) else None
|
| 713 |
+
|
| 714 |
+
def _on_keyboard_down(self, _keyboard, keycode, _text, modifiers):
|
| 715 |
+
self.last_key_down = keycode
|
| 716 |
+
ctrl_pressed = "ctrl" in modifiers or ("meta" in modifiers and kivy_platform == "macosx")
|
| 717 |
+
shift_pressed = "shift" in modifiers
|
| 718 |
+
if self.controls.note.focus:
|
| 719 |
+
return # when making notes, don't allow keyboard shortcuts
|
| 720 |
+
popup = self.popup_open
|
| 721 |
+
if popup:
|
| 722 |
+
if keycode[1] in [
|
| 723 |
+
Theme.KEY_DEEPERANALYSIS_POPUP,
|
| 724 |
+
Theme.KEY_REPORT_POPUP,
|
| 725 |
+
Theme.KEY_TIMER_POPUP,
|
| 726 |
+
Theme.KEY_TEACHER_POPUP,
|
| 727 |
+
Theme.KEY_AI_POPUP,
|
| 728 |
+
Theme.KEY_CONFIG_POPUP,
|
| 729 |
+
Theme.KEY_TSUMEGO_FRAME,
|
| 730 |
+
Theme.KEY_CONTRIBUTE_POPUP,
|
| 731 |
+
]: # switch between popups
|
| 732 |
+
popup.dismiss()
|
| 733 |
+
|
| 734 |
+
return
|
| 735 |
+
elif keycode[1] in Theme.KEY_SUBMIT_POPUP:
|
| 736 |
+
fn = getattr(popup.content, "on_submit", None)
|
| 737 |
+
if fn:
|
| 738 |
+
fn()
|
| 739 |
+
return
|
| 740 |
+
else:
|
| 741 |
+
return
|
| 742 |
+
|
| 743 |
+
if self.contributing:
|
| 744 |
+
if keycode[1] == Theme.KEY_STOP_CONTRIBUTING:
|
| 745 |
+
self.engine.graceful_shutdown()
|
| 746 |
+
return
|
| 747 |
+
elif keycode[1] in Theme.KEY_PAUSE_CONTRIBUTE:
|
| 748 |
+
self.engine.pause()
|
| 749 |
+
return
|
| 750 |
+
|
| 751 |
+
if keycode[1] == Theme.KEY_TOGGLE_CONTINUOUS_ANALYSIS:
|
| 752 |
+
self.toggle_continuous_analysis(quiet=shift_pressed)
|
| 753 |
+
elif keycode[1] == Theme.KEY_TOGGLE_MOVENUM:
|
| 754 |
+
self.toggle_move_num()
|
| 755 |
+
elif keycode[1] == Theme.KEY_TOGGLE_COORDINATES:
|
| 756 |
+
self.board_gui.toggle_coordinates()
|
| 757 |
+
elif keycode[1] in Theme.KEY_PAUSE_TIMER and not ctrl_pressed:
|
| 758 |
+
self.controls.timer.paused = not self.controls.timer.paused
|
| 759 |
+
elif keycode[1] in Theme.KEY_ZEN:
|
| 760 |
+
self.zen = (self.zen + 1) % 3
|
| 761 |
+
elif keycode[1] in Theme.KEY_NAV_PREV:
|
| 762 |
+
self("undo", 1 + shift_pressed * 9 + ctrl_pressed * 9999)
|
| 763 |
+
elif keycode[1] in Theme.KEY_NAV_NEXT:
|
| 764 |
+
self("redo", 1 + shift_pressed * 9 + ctrl_pressed * 9999)
|
| 765 |
+
elif keycode[1] == Theme.KEY_NAV_GAME_START:
|
| 766 |
+
self("undo", 9999)
|
| 767 |
+
elif keycode[1] == Theme.KEY_NAV_GAME_END:
|
| 768 |
+
self("redo", 9999)
|
| 769 |
+
elif keycode[1] == Theme.KEY_MOVE_TREE_MAKE_SELECTED_NODE_MAIN_BRANCH:
|
| 770 |
+
self.controls.move_tree.make_selected_node_main_branch()
|
| 771 |
+
elif keycode[1] == Theme.KEY_NAV_MISTAKE and not ctrl_pressed:
|
| 772 |
+
self("find-mistake", "undo" if shift_pressed else "redo")
|
| 773 |
+
elif keycode[1] == Theme.KEY_MOVE_TREE_DELETE_SELECTED_NODE and ctrl_pressed:
|
| 774 |
+
self.controls.move_tree.delete_selected_node()
|
| 775 |
+
elif keycode[1] == Theme.KEY_MOVE_TREE_TOGGLE_SELECTED_NODE_COLLAPSE and not ctrl_pressed:
|
| 776 |
+
self.controls.move_tree.toggle_selected_node_collapse()
|
| 777 |
+
elif keycode[1] == Theme.KEY_NEW_GAME and ctrl_pressed:
|
| 778 |
+
self("new-game-popup")
|
| 779 |
+
elif keycode[1] == Theme.KEY_LOAD_GAME and ctrl_pressed:
|
| 780 |
+
self("analyze-sgf-popup")
|
| 781 |
+
elif keycode[1] == Theme.KEY_SAVE_GAME and ctrl_pressed:
|
| 782 |
+
self("save-game")
|
| 783 |
+
elif keycode[1] == Theme.KEY_SAVE_GAME_AS and ctrl_pressed:
|
| 784 |
+
self("save-game-as-popup")
|
| 785 |
+
elif keycode[1] == Theme.KEY_COPY and ctrl_pressed:
|
| 786 |
+
Clipboard.copy(self.game.root.sgf())
|
| 787 |
+
self.controls.set_status(i18n._("Copied SGF to clipboard."), STATUS_INFO)
|
| 788 |
+
elif keycode[1] == Theme.KEY_PASTE and ctrl_pressed:
|
| 789 |
+
self.load_sgf_from_clipboard()
|
| 790 |
+
elif keycode[1] == Theme.KEY_NAV_PREV_BRANCH and shift_pressed:
|
| 791 |
+
self("undo", "main-branch")
|
| 792 |
+
elif keycode[1] == Theme.KEY_DEEPERANALYSIS_POPUP:
|
| 793 |
+
self.analysis_controls.dropdown.open_game_analysis_popup()
|
| 794 |
+
elif keycode[1] == Theme.KEY_TSUMEGO_FRAME:
|
| 795 |
+
self.analysis_controls.dropdown.open_tsumego_frame_popup()
|
| 796 |
+
elif keycode[1] == Theme.KEY_REPORT_POPUP:
|
| 797 |
+
self.analysis_controls.dropdown.open_report_popup()
|
| 798 |
+
elif keycode[1] == "f10" and self.debug_level >= OUTPUT_EXTRA_DEBUG:
|
| 799 |
+
import yappi
|
| 800 |
+
|
| 801 |
+
yappi.set_clock_type("cpu")
|
| 802 |
+
yappi.start()
|
| 803 |
+
self.log("starting profiler", OUTPUT_ERROR)
|
| 804 |
+
elif keycode[1] == "f11" and self.debug_level >= OUTPUT_EXTRA_DEBUG:
|
| 805 |
+
import time
|
| 806 |
+
import yappi
|
| 807 |
+
|
| 808 |
+
stats = yappi.get_func_stats()
|
| 809 |
+
filename = f"callgrind.{int(time.time())}.prof"
|
| 810 |
+
stats.save(filename, type="callgrind")
|
| 811 |
+
self.log(f"wrote profiling results to {filename}", OUTPUT_ERROR)
|
| 812 |
+
elif not ctrl_pressed:
|
| 813 |
+
shortcut = self.shortcuts.get(keycode[1])
|
| 814 |
+
if shortcut is not None:
|
| 815 |
+
if isinstance(shortcut, Widget):
|
| 816 |
+
shortcut.trigger_action(duration=0)
|
| 817 |
+
else:
|
| 818 |
+
self(*shortcut)
|
| 819 |
+
|
| 820 |
+
def _on_keyboard_up(self, _keyboard, keycode):
|
| 821 |
+
if keycode[1] in ["alt", "tab"]:
|
| 822 |
+
Clock.schedule_once(lambda *_args: self._single_key_action(keycode), 0.05)
|
| 823 |
+
|
| 824 |
+
def _single_key_action(self, keycode):
|
| 825 |
+
if (
|
| 826 |
+
self.controls.note.focus
|
| 827 |
+
or self.popup_open
|
| 828 |
+
or keycode != self.last_key_down
|
| 829 |
+
or time.time() - self.last_focus_event < 0.2 # this is here to prevent alt-tab from firing alt or tab
|
| 830 |
+
):
|
| 831 |
+
return
|
| 832 |
+
if keycode[1] == "alt":
|
| 833 |
+
self.nav_drawer.set_state("toggle")
|
| 834 |
+
elif keycode[1] == "tab":
|
| 835 |
+
self.play_mode.switch_ui_mode()
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
class KaTrainApp(MDApp):
|
| 839 |
+
gui = ObjectProperty(None)
|
| 840 |
+
language = StringProperty(DEFAULT_LANGUAGE)
|
| 841 |
+
|
| 842 |
+
def __init__(self):
|
| 843 |
+
super().__init__()
|
| 844 |
+
|
| 845 |
+
def is_valid_window_position(self, left, top, width, height):
|
| 846 |
+
try:
|
| 847 |
+
from screeninfo import get_monitors
|
| 848 |
+
monitors = get_monitors()
|
| 849 |
+
for monitor in monitors:
|
| 850 |
+
if (left >= monitor.x and left + width <= monitor.x + monitor.width and
|
| 851 |
+
top >= monitor.y and top + height <= monitor.y + monitor.height):
|
| 852 |
+
return True
|
| 853 |
+
return False
|
| 854 |
+
except Exception as e:
|
| 855 |
+
return True # yolo
|
| 856 |
+
|
| 857 |
+
def build(self):
|
| 858 |
+
self.icon = ICON # how you're supposed to set an icon
|
| 859 |
+
|
| 860 |
+
self.title = f"KaTrain v{VERSION}"
|
| 861 |
+
self.theme_cls.theme_style = "Dark"
|
| 862 |
+
self.theme_cls.primary_palette = "Gray"
|
| 863 |
+
self.theme_cls.primary_hue = "200"
|
| 864 |
+
|
| 865 |
+
kv_file = find_package_resource("katrain/gui.kv")
|
| 866 |
+
popup_kv_file = find_package_resource("katrain/popups.kv")
|
| 867 |
+
resource_add_path(PATHS["PACKAGE"] + "/fonts")
|
| 868 |
+
resource_add_path(PATHS["PACKAGE"] + "/sounds")
|
| 869 |
+
resource_add_path(PATHS["PACKAGE"] + "/img")
|
| 870 |
+
resource_add_path(os.path.abspath(os.path.expanduser(DATA_FOLDER))) # prefer resources in .katrain
|
| 871 |
+
|
| 872 |
+
theme_files = glob.glob(os.path.join(os.path.expanduser(DATA_FOLDER), "theme*.json"))
|
| 873 |
+
for theme_file in sorted(theme_files):
|
| 874 |
+
try:
|
| 875 |
+
with open(theme_file) as f:
|
| 876 |
+
theme_overrides = json.load(f)
|
| 877 |
+
for k, v in theme_overrides.items():
|
| 878 |
+
setattr(Theme, k, v)
|
| 879 |
+
print(f"[{theme_file}] Found theme override {k} = {v}")
|
| 880 |
+
except Exception as e: # noqa E722
|
| 881 |
+
print(f"Failed to load theme file {theme_file}: {e}")
|
| 882 |
+
|
| 883 |
+
Theme.DEFAULT_FONT = resource_find(Theme.DEFAULT_FONT)
|
| 884 |
+
Builder.load_file(kv_file)
|
| 885 |
+
|
| 886 |
+
Window.bind(on_request_close=self.on_request_close)
|
| 887 |
+
Window.bind(on_dropfile=lambda win, file: self.gui.load_sgf_file(file.decode("utf8")))
|
| 888 |
+
self.gui = KaTrainGui()
|
| 889 |
+
Builder.load_file(popup_kv_file)
|
| 890 |
+
|
| 891 |
+
win_left = win_top = win_size = None
|
| 892 |
+
if self.gui.config("ui_state/restoresize", True):
|
| 893 |
+
win_size = self.gui.config("ui_state/size", [])
|
| 894 |
+
win_left = self.gui.config("ui_state/left", None)
|
| 895 |
+
win_top = self.gui.config("ui_state/top", None)
|
| 896 |
+
if not win_size:
|
| 897 |
+
window_scale_fac = 1
|
| 898 |
+
try:
|
| 899 |
+
from screeninfo import get_monitors
|
| 900 |
+
|
| 901 |
+
for m in get_monitors():
|
| 902 |
+
window_scale_fac = min(window_scale_fac, (m.height - 100) / 1000, (m.width - 100) / 1300)
|
| 903 |
+
except Exception as e:
|
| 904 |
+
window_scale_fac = 0.85
|
| 905 |
+
win_size = [1300 * window_scale_fac, 1000 * window_scale_fac]
|
| 906 |
+
self.gui.log(f"Setting window size to {win_size} and position to {[win_left, win_top]}", OUTPUT_DEBUG)
|
| 907 |
+
Window.size = (win_size[0], win_size[1])
|
| 908 |
+
if win_left is not None and win_top is not None and self.is_valid_window_position(win_left, win_top, win_size[0], win_size[1]):
|
| 909 |
+
Window.left = win_left
|
| 910 |
+
Window.top = win_top
|
| 911 |
+
|
| 912 |
+
return self.gui
|
| 913 |
+
|
| 914 |
+
def on_language(self, _instance, language):
|
| 915 |
+
self.gui.log(f"Switching language to {language}", OUTPUT_INFO)
|
| 916 |
+
i18n.switch_lang(language)
|
| 917 |
+
self.gui._config["general"]["lang"] = language
|
| 918 |
+
self.gui.save_config()
|
| 919 |
+
if self.gui.game:
|
| 920 |
+
self.gui.update_state()
|
| 921 |
+
self.gui.controls.set_status("", STATUS_INFO)
|
| 922 |
+
|
| 923 |
+
def webbrowser(self, site_key):
|
| 924 |
+
websites = {
|
| 925 |
+
"homepage": HOMEPAGE + "#manual",
|
| 926 |
+
"support": HOMEPAGE + "#support",
|
| 927 |
+
"contribute:signup": "http://katagotraining.org/accounts/signup/",
|
| 928 |
+
"engine:help": HOMEPAGE + "/blob/master/ENGINE.md",
|
| 929 |
+
}
|
| 930 |
+
if site_key in websites:
|
| 931 |
+
webbrowser.open(websites[site_key])
|
| 932 |
+
|
| 933 |
+
def on_start(self):
|
| 934 |
+
self.language = self.gui.config("general/lang")
|
| 935 |
+
self.gui.start()
|
| 936 |
+
|
| 937 |
+
def on_request_close(self, *_args, source=None):
|
| 938 |
+
if source == "keyboard":
|
| 939 |
+
return True # do not close on esc
|
| 940 |
+
if getattr(self, "gui", None):
|
| 941 |
+
self.gui.play_mode.save_ui_state()
|
| 942 |
+
self.gui._config["ui_state"]["size"] = list(Window._size)
|
| 943 |
+
self.gui._config["ui_state"]["top"] = Window.top
|
| 944 |
+
self.gui._config["ui_state"]["left"] = Window.left
|
| 945 |
+
self.gui.save_config("ui_state")
|
| 946 |
+
if self.gui.engine:
|
| 947 |
+
self.gui.engine.shutdown(finish=None)
|
| 948 |
+
|
| 949 |
+
def signal_handler(self, _signal, _frame):
|
| 950 |
+
if self.gui.debug_level >= OUTPUT_DEBUG:
|
| 951 |
+
print("TRACEBACKS")
|
| 952 |
+
for threadId, stack in sys._current_frames().items():
|
| 953 |
+
print(f"\n# ThreadID: {threadId}")
|
| 954 |
+
for filename, lineno, name, line in traceback.extract_stack(stack):
|
| 955 |
+
print(f"\tFile: {filename}, line {lineno}, in {name}")
|
| 956 |
+
if line:
|
| 957 |
+
print(f"\t\t{line.strip()}")
|
| 958 |
+
self.stop()
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def run_app():
|
| 962 |
+
class CrashHandler(ExceptionHandler):
|
| 963 |
+
def handle_exception(self, inst):
|
| 964 |
+
ex_type, ex, tb = sys.exc_info()
|
| 965 |
+
trace = "".join(traceback.format_tb(tb))
|
| 966 |
+
app = MDApp.get_running_app()
|
| 967 |
+
|
| 968 |
+
if app and app.gui:
|
| 969 |
+
app.gui.log(
|
| 970 |
+
f"Exception {inst.__class__.__name__}: {', '.join(repr(a) for a in inst.args)}\n{trace}",
|
| 971 |
+
OUTPUT_ERROR,
|
| 972 |
+
)
|
| 973 |
+
else:
|
| 974 |
+
print(f"Exception {inst.__class__}: {inst.args}\n{trace}")
|
| 975 |
+
return ExceptionManager.PASS
|
| 976 |
+
|
| 977 |
+
ExceptionManager.add_handler(CrashHandler())
|
| 978 |
+
app = KaTrainApp()
|
| 979 |
+
signal.signal(signal.SIGINT, app.signal_handler)
|
| 980 |
+
app.run()
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
if __name__ == "__main__":
|
| 984 |
+
run_app()
|
katrain/config.json
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"engine": {
|
| 3 |
+
"katago": "",
|
| 4 |
+
"altcommand": "",
|
| 5 |
+
"model": "katrain/models/kata1-b18c384nbt-s9996604416-d4316597426.bin.gz",
|
| 6 |
+
"humanlike_model": "",
|
| 7 |
+
"config": "katrain/KataGo/analysis_config.cfg",
|
| 8 |
+
"max_visits": 500,
|
| 9 |
+
"fast_visits": 25,
|
| 10 |
+
"max_time": 8.0,
|
| 11 |
+
"wide_root_noise": 0.04,
|
| 12 |
+
"_enable_ownership": true
|
| 13 |
+
},
|
| 14 |
+
"contribute": {
|
| 15 |
+
"katago": "",
|
| 16 |
+
"config": "katrain/KataGo/contribute_config.cfg",
|
| 17 |
+
"ownership": false,
|
| 18 |
+
"maxgames": 6,
|
| 19 |
+
"movespeed": 2,
|
| 20 |
+
"username": "",
|
| 21 |
+
"password": "",
|
| 22 |
+
"savepath": "./dist_sgf/",
|
| 23 |
+
"savesgf": false
|
| 24 |
+
},
|
| 25 |
+
"general": {
|
| 26 |
+
"sgf_load": "~/Downloads",
|
| 27 |
+
"sgf_save": "./sgfout",
|
| 28 |
+
"anim_pv_time": 0.5,
|
| 29 |
+
"debug_level": 0,
|
| 30 |
+
"lang": "en",
|
| 31 |
+
"version": "1.17.0",
|
| 32 |
+
"load_fast_analysis": false,
|
| 33 |
+
"load_sgf_rewind": true
|
| 34 |
+
},
|
| 35 |
+
"timer": {
|
| 36 |
+
"byo_length": 30,
|
| 37 |
+
"byo_periods": 5,
|
| 38 |
+
"minimal_use": 0,
|
| 39 |
+
"main_time": 0,
|
| 40 |
+
"sound": true
|
| 41 |
+
},
|
| 42 |
+
"game": {
|
| 43 |
+
"size": "19",
|
| 44 |
+
"komi": 6.5,
|
| 45 |
+
"handicap": 0,
|
| 46 |
+
"rules": "japanese",
|
| 47 |
+
"clear_cache": false,
|
| 48 |
+
"setup_move": 100,
|
| 49 |
+
"setup_advantage": 20
|
| 50 |
+
},
|
| 51 |
+
"trainer": {
|
| 52 |
+
"theme": "theme:normal",
|
| 53 |
+
"num_undo_prompts": [
|
| 54 |
+
1,
|
| 55 |
+
1,
|
| 56 |
+
1,
|
| 57 |
+
0.5,
|
| 58 |
+
0,
|
| 59 |
+
0
|
| 60 |
+
],
|
| 61 |
+
"eval_thresholds": [
|
| 62 |
+
12,
|
| 63 |
+
6,
|
| 64 |
+
3,
|
| 65 |
+
1.5,
|
| 66 |
+
0.5,
|
| 67 |
+
0
|
| 68 |
+
],
|
| 69 |
+
"save_feedback": [
|
| 70 |
+
true,
|
| 71 |
+
true,
|
| 72 |
+
true,
|
| 73 |
+
true,
|
| 74 |
+
false,
|
| 75 |
+
false
|
| 76 |
+
],
|
| 77 |
+
"show_dots": [
|
| 78 |
+
true,
|
| 79 |
+
true,
|
| 80 |
+
true,
|
| 81 |
+
true,
|
| 82 |
+
true,
|
| 83 |
+
true
|
| 84 |
+
],
|
| 85 |
+
"extra_precision": false,
|
| 86 |
+
"save_analysis": false,
|
| 87 |
+
"save_marks": false,
|
| 88 |
+
"low_visits": 25,
|
| 89 |
+
"eval_on_show_last": 3,
|
| 90 |
+
"top_moves_show": "top_move_delta_score",
|
| 91 |
+
"top_moves_show_secondary": "top_move_visits",
|
| 92 |
+
"eval_show_ai": true,
|
| 93 |
+
"lock_ai": false
|
| 94 |
+
},
|
| 95 |
+
"ai": {
|
| 96 |
+
"ai:default": {},
|
| 97 |
+
"ai:antimirror": {},
|
| 98 |
+
"ai:handicap": {
|
| 99 |
+
"automatic": true,
|
| 100 |
+
"pda": 0
|
| 101 |
+
},
|
| 102 |
+
"ai:jigo": {
|
| 103 |
+
"target_score": 0.5
|
| 104 |
+
},
|
| 105 |
+
"ai:scoreloss": {
|
| 106 |
+
"strength": 0.2
|
| 107 |
+
},
|
| 108 |
+
"ai:policy": {
|
| 109 |
+
"opening_moves": 22.0
|
| 110 |
+
},
|
| 111 |
+
"ai:simple": {
|
| 112 |
+
"max_points_lost": 1.75,
|
| 113 |
+
"settled_weight": 1.0,
|
| 114 |
+
"opponent_fac": 0.5,
|
| 115 |
+
"min_visits": 3,
|
| 116 |
+
"attach_penalty": 1,
|
| 117 |
+
"tenuki_penalty": 0.5
|
| 118 |
+
},
|
| 119 |
+
"ai:p:weighted": {
|
| 120 |
+
"weaken_fac": 1.25,
|
| 121 |
+
"pick_override": 1.0,
|
| 122 |
+
"lower_bound": 0.001
|
| 123 |
+
},
|
| 124 |
+
"ai:p:pick": {
|
| 125 |
+
"pick_override": 0.95,
|
| 126 |
+
"pick_n": 5,
|
| 127 |
+
"pick_frac": 0.35
|
| 128 |
+
},
|
| 129 |
+
"ai:p:local": {
|
| 130 |
+
"pick_override": 0.95,
|
| 131 |
+
"stddev": 1.5,
|
| 132 |
+
"pick_n": 15,
|
| 133 |
+
"pick_frac": 0.0,
|
| 134 |
+
"endgame": 0.5
|
| 135 |
+
},
|
| 136 |
+
"ai:p:tenuki": {
|
| 137 |
+
"pick_override": 0.85,
|
| 138 |
+
"stddev": 7.5,
|
| 139 |
+
"pick_n": 5,
|
| 140 |
+
"pick_frac": 0.4,
|
| 141 |
+
"endgame": 0.45
|
| 142 |
+
},
|
| 143 |
+
"ai:p:influence": {
|
| 144 |
+
"pick_override": 0.95,
|
| 145 |
+
"pick_n": 5,
|
| 146 |
+
"pick_frac": 0.3,
|
| 147 |
+
"threshold": 3.5,
|
| 148 |
+
"line_weight": 10,
|
| 149 |
+
"endgame": 0.4
|
| 150 |
+
},
|
| 151 |
+
"ai:p:territory": {
|
| 152 |
+
"pick_override": 0.95,
|
| 153 |
+
"pick_n": 5,
|
| 154 |
+
"pick_frac": 0.3,
|
| 155 |
+
"threshold": 3.5,
|
| 156 |
+
"line_weight": 2,
|
| 157 |
+
"endgame": 0.4
|
| 158 |
+
},
|
| 159 |
+
"ai:p:rank": {
|
| 160 |
+
"kyu_rank": 4.0
|
| 161 |
+
},
|
| 162 |
+
"ai:human": {
|
| 163 |
+
"human_kyu_rank": 8,
|
| 164 |
+
"modern_style": false
|
| 165 |
+
},
|
| 166 |
+
"ai:pro": {
|
| 167 |
+
"pro_year": 1914
|
| 168 |
+
}
|
| 169 |
+
},
|
| 170 |
+
"ui_state": {
|
| 171 |
+
"restoresize": true,
|
| 172 |
+
"size": [],
|
| 173 |
+
"play": {
|
| 174 |
+
"analysis_controls": {
|
| 175 |
+
"show_children": true,
|
| 176 |
+
"eval": false,
|
| 177 |
+
"hints": false,
|
| 178 |
+
"policy": false,
|
| 179 |
+
"ownership": false
|
| 180 |
+
},
|
| 181 |
+
"panels": {
|
| 182 |
+
"graph_panel": [
|
| 183 |
+
"open",
|
| 184 |
+
{
|
| 185 |
+
"score": true,
|
| 186 |
+
"winrate": false
|
| 187 |
+
}
|
| 188 |
+
],
|
| 189 |
+
"stats_panel": [
|
| 190 |
+
"open",
|
| 191 |
+
{
|
| 192 |
+
"score": true,
|
| 193 |
+
"winrate": true,
|
| 194 |
+
"points": true
|
| 195 |
+
}
|
| 196 |
+
],
|
| 197 |
+
"notes_panel": [
|
| 198 |
+
"open",
|
| 199 |
+
{
|
| 200 |
+
"info": true,
|
| 201 |
+
"info-details": false,
|
| 202 |
+
"notes": false
|
| 203 |
+
}
|
| 204 |
+
]
|
| 205 |
+
}
|
| 206 |
+
},
|
| 207 |
+
"analyze": {
|
| 208 |
+
"analysis_controls": {
|
| 209 |
+
"show_children": true,
|
| 210 |
+
"eval": true,
|
| 211 |
+
"hints": true,
|
| 212 |
+
"policy": false,
|
| 213 |
+
"ownership": true
|
| 214 |
+
},
|
| 215 |
+
"panels": {
|
| 216 |
+
"graph_panel": [
|
| 217 |
+
"open",
|
| 218 |
+
{
|
| 219 |
+
"score": true,
|
| 220 |
+
"winrate": true
|
| 221 |
+
}
|
| 222 |
+
],
|
| 223 |
+
"stats_panel": [
|
| 224 |
+
"open",
|
| 225 |
+
{
|
| 226 |
+
"score": true,
|
| 227 |
+
"winrate": true,
|
| 228 |
+
"points": true
|
| 229 |
+
}
|
| 230 |
+
],
|
| 231 |
+
"notes_panel": [
|
| 232 |
+
"open",
|
| 233 |
+
{
|
| 234 |
+
"info": true,
|
| 235 |
+
"info-details": true,
|
| 236 |
+
"notes": false
|
| 237 |
+
}
|
| 238 |
+
]
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
}
|
| 242 |
+
}
|
katrain/core/__init__.py
ADDED
|
File without changes
|
katrain/core/ai.py
ADDED
|
@@ -0,0 +1,1460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
import heapq
|
| 3 |
+
import math
|
| 4 |
+
import random
|
| 5 |
+
import time
|
| 6 |
+
from typing import Dict, List, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
from katrain.core.constants import (
|
| 9 |
+
AI_DEFAULT, AI_HANDICAP, AI_INFLUENCE, AI_INFLUENCE_ELO_GRID, AI_JIGO,
|
| 10 |
+
AI_ANTIMIRROR, AI_LOCAL, AI_LOCAL_ELO_GRID, AI_PICK, AI_PICK_ELO_GRID,
|
| 11 |
+
AI_POLICY, AI_RANK, AI_SCORELOSS, AI_SCORELOSS_ELO, AI_SETTLE_STONES,
|
| 12 |
+
AI_SIMPLE_OWNERSHIP, AI_STRENGTH,
|
| 13 |
+
AI_TENUKI, AI_TENUKI_ELO_GRID, AI_TERRITORY, AI_TERRITORY_ELO_GRID,
|
| 14 |
+
AI_WEIGHTED, AI_WEIGHTED_ELO, CALIBRATED_RANK_ELO, OUTPUT_DEBUG,
|
| 15 |
+
OUTPUT_ERROR, OUTPUT_INFO, PRIORITY_EXTRA_AI_QUERY, ADDITIONAL_MOVE_ORDER, AI_HUMAN, AI_PRO
|
| 16 |
+
)
|
| 17 |
+
from katrain.core.game import Game, GameNode, Move
|
| 18 |
+
from katrain.core.utils import var_to_grid, weighted_selection_without_replacement, evaluation_class
|
| 19 |
+
|
| 20 |
+
# Decorator pattern for adding classes to the registry
|
| 21 |
+
STRATEGY_REGISTRY = {}
|
| 22 |
+
|
| 23 |
+
def register_strategy(strategy_name):
|
| 24 |
+
def decorator(strategy_class):
|
| 25 |
+
STRATEGY_REGISTRY[strategy_name] = strategy_class
|
| 26 |
+
return strategy_class
|
| 27 |
+
return decorator
|
| 28 |
+
|
| 29 |
+
def interp_ix(lst, x):
|
| 30 |
+
i = 0
|
| 31 |
+
while i + 1 < len(lst) - 1 and lst[i + 1] < x:
|
| 32 |
+
i += 1
|
| 33 |
+
t = max(0, min(1, (x - lst[i]) / (lst[i + 1] - lst[i])))
|
| 34 |
+
return i, t
|
| 35 |
+
|
| 36 |
+
def interp1d(lst, x):
|
| 37 |
+
xs, ys = zip(*lst)
|
| 38 |
+
i, t = interp_ix(xs, x)
|
| 39 |
+
return (1 - t) * ys[i] + t * ys[i + 1]
|
| 40 |
+
|
| 41 |
+
def interp2d(gridspec, x, y):
|
| 42 |
+
xs, ys, matrix = gridspec
|
| 43 |
+
i, t = interp_ix(xs, x)
|
| 44 |
+
j, s = interp_ix(ys, y)
|
| 45 |
+
return (
|
| 46 |
+
matrix[j][i] * (1 - t) * (1 - s)
|
| 47 |
+
+ matrix[j][i + 1] * t * (1 - s)
|
| 48 |
+
+ matrix[j + 1][i] * (1 - t) * s
|
| 49 |
+
+ matrix[j + 1][i + 1] * t * s
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def ai_rank_estimation(strategy, settings) -> int:
|
| 53 |
+
if strategy in [AI_DEFAULT, AI_HANDICAP, AI_JIGO, AI_PRO]:
|
| 54 |
+
return 9
|
| 55 |
+
if strategy == AI_RANK:
|
| 56 |
+
return 1 - settings["kyu_rank"]
|
| 57 |
+
if strategy == AI_HUMAN:
|
| 58 |
+
return 1 - settings["human_kyu_rank"]
|
| 59 |
+
|
| 60 |
+
if strategy in [AI_WEIGHTED, AI_SCORELOSS, AI_LOCAL, AI_TENUKI, AI_TERRITORY, AI_INFLUENCE, AI_PICK]:
|
| 61 |
+
if strategy == AI_WEIGHTED:
|
| 62 |
+
elo = interp1d(AI_WEIGHTED_ELO, settings["weaken_fac"])
|
| 63 |
+
if strategy == AI_SCORELOSS:
|
| 64 |
+
elo = interp1d(AI_SCORELOSS_ELO, settings["strength"])
|
| 65 |
+
if strategy == AI_PICK:
|
| 66 |
+
elo = interp2d(AI_PICK_ELO_GRID, settings["pick_frac"], settings["pick_n"])
|
| 67 |
+
if strategy == AI_LOCAL:
|
| 68 |
+
elo = interp2d(AI_LOCAL_ELO_GRID, settings["pick_frac"], settings["pick_n"])
|
| 69 |
+
if strategy == AI_TENUKI:
|
| 70 |
+
elo = interp2d(AI_TENUKI_ELO_GRID, settings["pick_frac"], settings["pick_n"])
|
| 71 |
+
if strategy == AI_TERRITORY:
|
| 72 |
+
elo = interp2d(AI_TERRITORY_ELO_GRID, settings["pick_frac"], settings["pick_n"])
|
| 73 |
+
if strategy == AI_INFLUENCE:
|
| 74 |
+
elo = interp2d(AI_INFLUENCE_ELO_GRID, settings["pick_frac"], settings["pick_n"])
|
| 75 |
+
|
| 76 |
+
kyu = interp1d(CALIBRATED_RANK_ELO, elo)
|
| 77 |
+
return 1 - kyu
|
| 78 |
+
else:
|
| 79 |
+
return AI_STRENGTH[strategy]
|
| 80 |
+
|
| 81 |
+
def game_report(game, thresholds, depth_filter=None):
|
| 82 |
+
cn = game.current_node
|
| 83 |
+
nodes = cn.nodes_from_root
|
| 84 |
+
while cn.children: # main branch
|
| 85 |
+
cn = cn.children[0]
|
| 86 |
+
nodes.append(cn)
|
| 87 |
+
|
| 88 |
+
x, y = game.board_size
|
| 89 |
+
depth_filter = [math.ceil(board_frac * x * y) for board_frac in depth_filter or (0, 1e9)]
|
| 90 |
+
nodes = [n for n in nodes if n.move and not n.is_root and depth_filter[0] <= n.depth < depth_filter[1]]
|
| 91 |
+
histogram = [{"B": 0, "W": 0} for _ in thresholds]
|
| 92 |
+
ai_top_move_count = {"B": 0, "W": 0}
|
| 93 |
+
ai_approved_move_count = {"B": 0, "W": 0}
|
| 94 |
+
player_ptloss = {"B": [], "W": []}
|
| 95 |
+
weights = {"B": [], "W": []}
|
| 96 |
+
|
| 97 |
+
for n in nodes:
|
| 98 |
+
points_lost = n.points_lost
|
| 99 |
+
if n.points_lost is None:
|
| 100 |
+
continue
|
| 101 |
+
else:
|
| 102 |
+
points_lost = max(0, points_lost)
|
| 103 |
+
bucket = len(thresholds) - 1 - evaluation_class(points_lost, thresholds)
|
| 104 |
+
player_ptloss[n.player].append(points_lost)
|
| 105 |
+
histogram[bucket][n.player] += 1
|
| 106 |
+
cands = n.parent.candidate_moves
|
| 107 |
+
filtered_cands = [d for d in cands if d["order"] < ADDITIONAL_MOVE_ORDER and "prior" in d]
|
| 108 |
+
weight = min(
|
| 109 |
+
1.0,
|
| 110 |
+
sum([max(d["pointsLost"], 0) * d["prior"] for d in filtered_cands])
|
| 111 |
+
/ (sum(d["prior"] for d in filtered_cands) or 1e-6),
|
| 112 |
+
) # complexity capped at 1
|
| 113 |
+
# adj_weight between 0.05 - 1, dependent on difficulty and points lost
|
| 114 |
+
adj_weight = max(0.05, min(1.0, max(weight, points_lost / 4)))
|
| 115 |
+
weights[n.player].append((weight, adj_weight))
|
| 116 |
+
if n.parent.analysis_complete:
|
| 117 |
+
ai_top_move_count[n.player] += int(cands[0]["move"] == n.move.gtp())
|
| 118 |
+
ai_approved_move_count[n.player] += int(
|
| 119 |
+
n.move.gtp()
|
| 120 |
+
in [d["move"] for d in filtered_cands if d["order"] == 0 or (d["pointsLost"] < 0.5 and d["order"] < 5)]
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
wt_loss = {
|
| 124 |
+
bw: sum(s * aw for s, (w, aw) in zip(player_ptloss[bw], weights[bw]))
|
| 125 |
+
/ (sum(aw for _, aw in weights[bw]) or 1e-6)
|
| 126 |
+
for bw in "BW"
|
| 127 |
+
}
|
| 128 |
+
sum_stats = {
|
| 129 |
+
bw: (
|
| 130 |
+
{
|
| 131 |
+
"accuracy": 100 * 0.75 ** wt_loss[bw],
|
| 132 |
+
"complexity": sum(w for w, aw in weights[bw]) / len(player_ptloss[bw]),
|
| 133 |
+
"mean_ptloss": sum(player_ptloss[bw]) / len(player_ptloss[bw]),
|
| 134 |
+
"weighted_ptloss": wt_loss[bw],
|
| 135 |
+
"ai_top_move": ai_top_move_count[bw] / len(player_ptloss[bw]),
|
| 136 |
+
"ai_top5_move": ai_approved_move_count[bw] / len(player_ptloss[bw]),
|
| 137 |
+
}
|
| 138 |
+
if len(player_ptloss[bw]) > 0
|
| 139 |
+
else {}
|
| 140 |
+
)
|
| 141 |
+
for bw in "BW"
|
| 142 |
+
}
|
| 143 |
+
return sum_stats, histogram, player_ptloss
|
| 144 |
+
|
| 145 |
+
def fmt_moves(moves: List[Tuple[float, Move]]):
|
| 146 |
+
return ", ".join(f"{mv.gtp()} ({p:.2%})" for p, mv in moves)
|
| 147 |
+
|
| 148 |
+
# Utility functions from the original code
|
| 149 |
+
def policy_weighted_move(policy_moves, lower_bound, weaken_fac):
|
| 150 |
+
lower_bound, weaken_fac = max(0, lower_bound), max(0.01, weaken_fac)
|
| 151 |
+
weighted_coords = [
|
| 152 |
+
(pv, pv ** (1 / weaken_fac), move) for pv, move in policy_moves if pv > lower_bound and not move.is_pass
|
| 153 |
+
]
|
| 154 |
+
if weighted_coords:
|
| 155 |
+
top = weighted_selection_without_replacement(weighted_coords, 1)[0]
|
| 156 |
+
move = top[2]
|
| 157 |
+
ai_thoughts = f"Playing policy-weighted random move {move.gtp()} ({top[0]:.1%}) from {len(weighted_coords)} moves above lower_bound of {lower_bound:.1%}."
|
| 158 |
+
else:
|
| 159 |
+
move = policy_moves[0][1]
|
| 160 |
+
ai_thoughts = f"Playing top policy move because no non-pass move > above lower_bound of {lower_bound:.1%}."
|
| 161 |
+
return move, ai_thoughts
|
| 162 |
+
|
| 163 |
+
def generate_influence_territory_weights(ai_mode, ai_settings, policy_grid, size):
|
| 164 |
+
thr_line = ai_settings["threshold"] - 1 # zero-based
|
| 165 |
+
if ai_mode == AI_INFLUENCE:
|
| 166 |
+
weight = lambda x, y: (1 / ai_settings["line_weight"]) ** ( # noqa E731
|
| 167 |
+
max(0, thr_line - min(size[0] - 1 - x, x)) + max(0, thr_line - min(size[1] - 1 - y, y))
|
| 168 |
+
) # noqa E731
|
| 169 |
+
else:
|
| 170 |
+
weight = lambda x, y: (1 / ai_settings["line_weight"]) ** ( # noqa E731
|
| 171 |
+
max(0, min(size[0] - 1 - x, x, size[1] - 1 - y, y) - thr_line)
|
| 172 |
+
)
|
| 173 |
+
weighted_coords = [
|
| 174 |
+
(policy_grid[y][x] * weight(x, y), weight(x, y), x, y)
|
| 175 |
+
for x in range(size[0])
|
| 176 |
+
for y in range(size[1])
|
| 177 |
+
if policy_grid[y][x] > 0
|
| 178 |
+
]
|
| 179 |
+
ai_thoughts = f"Generated weights for {ai_mode} according to weight factor {ai_settings['line_weight']} and distance from {thr_line + 1}th line. "
|
| 180 |
+
return weighted_coords, ai_thoughts
|
| 181 |
+
|
| 182 |
+
def generate_local_tenuki_weights(ai_mode, ai_settings, policy_grid, cn, size):
|
| 183 |
+
var = ai_settings["stddev"] ** 2
|
| 184 |
+
mx, my = cn.move.coords
|
| 185 |
+
weighted_coords = [
|
| 186 |
+
(policy_grid[y][x], math.exp(-0.5 * ((x - mx) ** 2 + (y - my) ** 2) / var), x, y)
|
| 187 |
+
for x in range(size[0])
|
| 188 |
+
for y in range(size[1])
|
| 189 |
+
if policy_grid[y][x] > 0
|
| 190 |
+
]
|
| 191 |
+
ai_thoughts = f"Generated weights based on one minus gaussian with variance {var} around coordinates {mx},{my}. "
|
| 192 |
+
if ai_mode == AI_TENUKI:
|
| 193 |
+
weighted_coords = [(p, 1 - w, x, y) for p, w, x, y in weighted_coords]
|
| 194 |
+
ai_thoughts = (
|
| 195 |
+
f"Generated weights based on one minus gaussian with variance {var} around coordinates {mx},{my}. "
|
| 196 |
+
)
|
| 197 |
+
return weighted_coords, ai_thoughts
|
| 198 |
+
|
| 199 |
+
class AIStrategy(ABC):
|
| 200 |
+
"""Base strategy class for AI move generation"""
|
| 201 |
+
|
| 202 |
+
def __init__(self, game: Game, ai_settings: Dict):
|
| 203 |
+
self.game = game
|
| 204 |
+
self.settings = ai_settings
|
| 205 |
+
self.cn = game.current_node
|
| 206 |
+
self.strategy_name = self.__class__.__name__
|
| 207 |
+
self.game.katrain.log(f"Initializing {self.strategy_name} with settings: {self.settings}", OUTPUT_DEBUG)
|
| 208 |
+
|
| 209 |
+
@abstractmethod
|
| 210 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 211 |
+
"""Generate a move and explanation"""
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
def request_analysis(self, extra_settings: Dict) -> Optional[Dict]:
|
| 215 |
+
"""Helper to request additional analysis with custom settings"""
|
| 216 |
+
self.game.katrain.log(f"[{self.strategy_name}] Requesting analysis with settings: {extra_settings}", OUTPUT_DEBUG)
|
| 217 |
+
error = False
|
| 218 |
+
analysis = None
|
| 219 |
+
|
| 220 |
+
def set_analysis(a, partial_result):
|
| 221 |
+
nonlocal analysis
|
| 222 |
+
if not partial_result:
|
| 223 |
+
analysis = a
|
| 224 |
+
self.game.katrain.log(f"[{self.strategy_name}] Analysis received", OUTPUT_DEBUG)
|
| 225 |
+
|
| 226 |
+
def set_error(a):
|
| 227 |
+
nonlocal error
|
| 228 |
+
self.game.katrain.log(f"[{self.strategy_name}] Error in additional analysis query: {a}", OUTPUT_ERROR)
|
| 229 |
+
error = True
|
| 230 |
+
|
| 231 |
+
engine = self.game.engines[self.cn.player]
|
| 232 |
+
engine.request_analysis(
|
| 233 |
+
self.cn,
|
| 234 |
+
callback=set_analysis,
|
| 235 |
+
error_callback=set_error,
|
| 236 |
+
priority=PRIORITY_EXTRA_AI_QUERY,
|
| 237 |
+
ownership=False,
|
| 238 |
+
extra_settings=extra_settings,
|
| 239 |
+
)
|
| 240 |
+
self.game.katrain.log(f"[{self.strategy_name}] Waiting for analysis to complete...", OUTPUT_DEBUG)
|
| 241 |
+
while not (error or analysis):
|
| 242 |
+
time.sleep(0.01) # TODO: prevent deadlock if esc, check node in queries?
|
| 243 |
+
engine.check_alive(exception_if_dead=True)
|
| 244 |
+
|
| 245 |
+
if analysis:
|
| 246 |
+
self.game.katrain.log(f"[{self.strategy_name}] Analysis completed successfully", OUTPUT_DEBUG)
|
| 247 |
+
return analysis
|
| 248 |
+
|
| 249 |
+
def wait_for_analysis(self):
|
| 250 |
+
"""Wait for the analysis to complete"""
|
| 251 |
+
self.game.katrain.log(f"[{self.strategy_name}] Waiting for regular analysis to complete...", OUTPUT_DEBUG)
|
| 252 |
+
while not self.cn.analysis_complete:
|
| 253 |
+
time.sleep(0.01)
|
| 254 |
+
self.game.engines[self.cn.next_player].check_alive(exception_if_dead=True)
|
| 255 |
+
self.game.katrain.log(f"[{self.strategy_name}] Regular analysis completed", OUTPUT_DEBUG)
|
| 256 |
+
|
| 257 |
+
def should_play_top_move(self, policy_moves, top_5_pass, override=0.0, overridetwo=1.0):
|
| 258 |
+
"""Check if we should play the top policy move, regardless of strategy"""
|
| 259 |
+
top_policy_move = policy_moves[0][1]
|
| 260 |
+
self.game.katrain.log(f"[{self.strategy_name}] Checking if should play top move. Top move: {top_policy_move.gtp()} ({policy_moves[0][0]:.2%})", OUTPUT_DEBUG)
|
| 261 |
+
self.game.katrain.log(f"[{self.strategy_name}] Override thresholds: single={override:.2%}, combined={overridetwo:.2%}", OUTPUT_DEBUG)
|
| 262 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top 5 pass: {top_5_pass}", OUTPUT_DEBUG)
|
| 263 |
+
|
| 264 |
+
if top_5_pass:
|
| 265 |
+
self.game.katrain.log(f"[{self.strategy_name}] Playing top move because pass is in top 5", OUTPUT_DEBUG)
|
| 266 |
+
return top_policy_move, "Playing top one because one of them is pass."
|
| 267 |
+
|
| 268 |
+
if policy_moves[0][0] > override:
|
| 269 |
+
self.game.katrain.log(f"[{self.strategy_name}] Playing top move because weight {policy_moves[0][0]:.2%} > override {override:.2%}", OUTPUT_DEBUG)
|
| 270 |
+
return top_policy_move, f"Top policy move has weight > {override:.1%}, so overriding other strategies."
|
| 271 |
+
|
| 272 |
+
if policy_moves[0][0] + policy_moves[1][0] > overridetwo:
|
| 273 |
+
combined = policy_moves[0][0] + policy_moves[1][0]
|
| 274 |
+
self.game.katrain.log(f"[{self.strategy_name}] Playing top move because combined weight {combined:.2%} > overridetwo {overridetwo:.2%}", OUTPUT_DEBUG)
|
| 275 |
+
return top_policy_move, f"Top two policy moves have cumulative weight > {overridetwo:.1%}, so overriding other strategies."
|
| 276 |
+
|
| 277 |
+
self.game.katrain.log(f"[{self.strategy_name}] No override condition met, continuing with strategy", OUTPUT_DEBUG)
|
| 278 |
+
return None, ""
|
| 279 |
+
|
| 280 |
+
@register_strategy(AI_DEFAULT)
|
| 281 |
+
class DefaultStrategy(AIStrategy):
|
| 282 |
+
"""Default strategy - simply plays the top move from the engine"""
|
| 283 |
+
|
| 284 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 285 |
+
self.game.katrain.log(f"[DefaultStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 286 |
+
self.wait_for_analysis()
|
| 287 |
+
|
| 288 |
+
candidate_moves = self.cn.candidate_moves
|
| 289 |
+
self.game.katrain.log(f"[DefaultStrategy] Analysis found {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 290 |
+
|
| 291 |
+
if not candidate_moves:
|
| 292 |
+
self.game.katrain.log(f"[DefaultStrategy] No candidate moves found, will play pass", OUTPUT_DEBUG)
|
| 293 |
+
top_cand = Move(is_pass=True, player=self.cn.next_player)
|
| 294 |
+
else:
|
| 295 |
+
top_move_data = candidate_moves[0]
|
| 296 |
+
top_cand = Move.from_gtp(top_move_data["move"], player=self.cn.next_player)
|
| 297 |
+
self.game.katrain.log(f"[DefaultStrategy] Top move: {top_cand.gtp()} with stats: {top_move_data}", OUTPUT_DEBUG)
|
| 298 |
+
|
| 299 |
+
ai_thoughts = f"Default strategy found {len(candidate_moves)} moves returned from the engine and chose {top_cand.gtp()} as top move"
|
| 300 |
+
self.game.katrain.log(f"[DefaultStrategy] Final decision: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 301 |
+
|
| 302 |
+
return top_cand, ai_thoughts
|
| 303 |
+
|
| 304 |
+
@register_strategy(AI_HANDICAP)
|
| 305 |
+
class HandicapStrategy(AIStrategy):
|
| 306 |
+
"""Handicap strategy - uses playoutDoublingAdvantage to analyze the position"""
|
| 307 |
+
|
| 308 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 309 |
+
self.game.katrain.log(f"[HandicapStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 310 |
+
|
| 311 |
+
# Calculate PDA (Playout Doubling Advantage)
|
| 312 |
+
pda = self.settings["pda"]
|
| 313 |
+
self.game.katrain.log(f"[HandicapStrategy] Initial PDA from settings: {pda}", OUTPUT_DEBUG)
|
| 314 |
+
|
| 315 |
+
if self.settings["automatic"]:
|
| 316 |
+
n_handicaps = len(self.game.root.get_list_property("AB", []))
|
| 317 |
+
MOVE_VALUE = 14 # could be rules dependent
|
| 318 |
+
b_stones_advantage = max(n_handicaps - 1, 0) - (self.cn.komi - MOVE_VALUE / 2) / MOVE_VALUE
|
| 319 |
+
pda = min(3, max(-3, -b_stones_advantage * (3 / 8))) # max PDA at 8 stone adv, normal 9 stone game is 8.46
|
| 320 |
+
|
| 321 |
+
self.game.katrain.log(f"[HandicapStrategy] Automatic PDA calculation:", OUTPUT_DEBUG)
|
| 322 |
+
self.game.katrain.log(f"[HandicapStrategy] - Handicap stones: {n_handicaps}", OUTPUT_DEBUG)
|
| 323 |
+
self.game.katrain.log(f"[HandicapStrategy] - Komi: {self.cn.komi}", OUTPUT_DEBUG)
|
| 324 |
+
self.game.katrain.log(f"[HandicapStrategy] - Stone advantage: {b_stones_advantage}", OUTPUT_DEBUG)
|
| 325 |
+
self.game.katrain.log(f"[HandicapStrategy] - Calculated PDA: {pda}", OUTPUT_DEBUG)
|
| 326 |
+
|
| 327 |
+
# Request additional analysis with PDA
|
| 328 |
+
self.game.katrain.log(f"[HandicapStrategy] Requesting analysis with PDA={pda}", OUTPUT_DEBUG)
|
| 329 |
+
handicap_analysis = self.request_analysis(
|
| 330 |
+
{"playoutDoublingAdvantage": pda, "playoutDoublingAdvantagePla": "BLACK"}
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
if not handicap_analysis:
|
| 334 |
+
self.game.katrain.log("[HandicapStrategy] Error getting handicap-based move, falling back to DefaultStrategy", OUTPUT_ERROR)
|
| 335 |
+
return DefaultStrategy(self.game, self.settings).generate_move()
|
| 336 |
+
|
| 337 |
+
self.wait_for_analysis()
|
| 338 |
+
|
| 339 |
+
candidate_moves = handicap_analysis["moveInfos"]
|
| 340 |
+
self.game.katrain.log(f"[HandicapStrategy] Analysis returned {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 341 |
+
|
| 342 |
+
# Get top candidate move
|
| 343 |
+
top_move_data = candidate_moves[0]
|
| 344 |
+
top_cand = Move.from_gtp(top_move_data["move"], player=self.cn.next_player)
|
| 345 |
+
|
| 346 |
+
# Log details about the top move
|
| 347 |
+
self.game.katrain.log(f"[HandicapStrategy] Top move: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 348 |
+
self.game.katrain.log(f"[HandicapStrategy] Score lead: {handicap_analysis['rootInfo']['scoreLead']}", OUTPUT_DEBUG)
|
| 349 |
+
self.game.katrain.log(f"[HandicapStrategy] Win rate: {handicap_analysis['rootInfo']['winrate']}", OUTPUT_DEBUG)
|
| 350 |
+
|
| 351 |
+
ai_thoughts = f"Handicap strategy found {len(candidate_moves)} moves returned from the engine and chose {top_cand.gtp()} as top move. PDA based score {self.cn.format_score(handicap_analysis['rootInfo']['scoreLead'])} and win rate {self.cn.format_winrate(handicap_analysis['rootInfo']['winrate'])}"
|
| 352 |
+
|
| 353 |
+
self.game.katrain.log(f"[HandicapStrategy] Final decision: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 354 |
+
return top_cand, ai_thoughts
|
| 355 |
+
|
| 356 |
+
@register_strategy(AI_ANTIMIRROR)
|
| 357 |
+
class AntimirrorStrategy(AIStrategy):
|
| 358 |
+
"""Antimirror strategy - uses antiMirror to analyze the position"""
|
| 359 |
+
|
| 360 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 361 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 362 |
+
|
| 363 |
+
# Request analysis with antimirror option
|
| 364 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Requesting analysis with antiMirror=True", OUTPUT_DEBUG)
|
| 365 |
+
antimirror_analysis = self.request_analysis({"antiMirror": True})
|
| 366 |
+
|
| 367 |
+
if not antimirror_analysis:
|
| 368 |
+
self.game.katrain.log("[AntimirrorStrategy] Error getting antimirror move, falling back to DefaultStrategy", OUTPUT_ERROR)
|
| 369 |
+
return DefaultStrategy(self.game, self.settings).generate_move()
|
| 370 |
+
|
| 371 |
+
self.wait_for_analysis()
|
| 372 |
+
|
| 373 |
+
candidate_moves = antimirror_analysis["moveInfos"]
|
| 374 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Analysis returned {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 375 |
+
|
| 376 |
+
# Get top candidate move
|
| 377 |
+
top_move_data = candidate_moves[0]
|
| 378 |
+
top_cand = Move.from_gtp(top_move_data["move"], player=self.cn.next_player)
|
| 379 |
+
|
| 380 |
+
# Log details about the top move
|
| 381 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Top move: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 382 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Score lead: {antimirror_analysis['rootInfo']['scoreLead']}", OUTPUT_DEBUG)
|
| 383 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Win rate: {antimirror_analysis['rootInfo']['winrate']}", OUTPUT_DEBUG)
|
| 384 |
+
|
| 385 |
+
# Log the top 3 moves for comparison
|
| 386 |
+
for i, move_data in enumerate(candidate_moves[:3]):
|
| 387 |
+
move = Move.from_gtp(move_data["move"], player=self.cn.next_player)
|
| 388 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Move #{i+1}: {move.gtp()} - visits: {move_data.get('visits', 'N/A')}, points lost: {move_data.get('pointsLost', 'N/A')}", OUTPUT_DEBUG)
|
| 389 |
+
|
| 390 |
+
ai_thoughts = f"AntiMirror strategy found {len(candidate_moves)} moves returned from the engine and chose {top_cand.gtp()} as top move. antiMirror based score {self.cn.format_score(antimirror_analysis['rootInfo']['scoreLead'])} and win rate {self.cn.format_winrate(antimirror_analysis['rootInfo']['winrate'])}"
|
| 391 |
+
|
| 392 |
+
self.game.katrain.log(f"[AntimirrorStrategy] Final decision: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 393 |
+
return top_cand, ai_thoughts
|
| 394 |
+
|
| 395 |
+
@register_strategy(AI_JIGO)
|
| 396 |
+
class JigoStrategy(AIStrategy):
|
| 397 |
+
"""Jigo strategy - aims for a specific score difference"""
|
| 398 |
+
|
| 399 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 400 |
+
self.game.katrain.log(f"[JigoStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 401 |
+
self.wait_for_analysis()
|
| 402 |
+
|
| 403 |
+
candidate_moves = self.cn.candidate_moves
|
| 404 |
+
self.game.katrain.log(f"[JigoStrategy] Analysis found {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 405 |
+
|
| 406 |
+
if not candidate_moves:
|
| 407 |
+
self.game.katrain.log(f"[JigoStrategy] No candidate moves found, will play pass", OUTPUT_DEBUG)
|
| 408 |
+
return Move(is_pass=True, player=self.cn.next_player), "No candidate moves found, passing"
|
| 409 |
+
|
| 410 |
+
# Get top engine move for reference
|
| 411 |
+
top_cand = Move.from_gtp(candidate_moves[0]["move"], player=self.cn.next_player)
|
| 412 |
+
self.game.katrain.log(f"[JigoStrategy] Top engine move would be: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 413 |
+
|
| 414 |
+
# Calculate player sign (1 for black, -1 for white)
|
| 415 |
+
sign = self.cn.player_sign(self.cn.next_player)
|
| 416 |
+
self.game.katrain.log(f"[JigoStrategy] Player sign: {sign}", OUTPUT_DEBUG)
|
| 417 |
+
|
| 418 |
+
# Get target score from settings
|
| 419 |
+
target_score = self.settings["target_score"]
|
| 420 |
+
self.game.katrain.log(f"[JigoStrategy] Target score: {target_score}", OUTPUT_DEBUG)
|
| 421 |
+
|
| 422 |
+
# Log score leads before selecting jigo move
|
| 423 |
+
self.game.katrain.log("[JigoStrategy] Candidate move score leads:", OUTPUT_DEBUG)
|
| 424 |
+
for i, move_data in enumerate(candidate_moves[:5]):
|
| 425 |
+
move = Move.from_gtp(move_data["move"], player=self.cn.next_player)
|
| 426 |
+
score_diff = abs(sign * move_data["scoreLead"] - target_score)
|
| 427 |
+
self.game.katrain.log(f"[JigoStrategy] - {move.gtp()}: scoreLead={move_data['scoreLead']}, diff from target={score_diff}", OUTPUT_DEBUG)
|
| 428 |
+
|
| 429 |
+
# Find the move that gives a score closest to the target
|
| 430 |
+
jigo_move = min(
|
| 431 |
+
candidate_moves,
|
| 432 |
+
key=lambda move: abs(sign * move["scoreLead"] - target_score)
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
aimove = Move.from_gtp(jigo_move["move"], player=self.cn.next_player)
|
| 436 |
+
jigo_score_diff = abs(sign * jigo_move["scoreLead"] - target_score)
|
| 437 |
+
|
| 438 |
+
self.game.katrain.log(f"[JigoStrategy] Selected move: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 439 |
+
self.game.katrain.log(f"[JigoStrategy] Selected move score lead: {jigo_move['scoreLead']}", OUTPUT_DEBUG)
|
| 440 |
+
self.game.katrain.log(f"[JigoStrategy] Distance from target: {jigo_score_diff}", OUTPUT_DEBUG)
|
| 441 |
+
|
| 442 |
+
ai_thoughts = f"Jigo strategy found {len(candidate_moves)} candidate moves (best {top_cand.gtp()}) and chose {aimove.gtp()} as closest to 0.5 point win"
|
| 443 |
+
|
| 444 |
+
self.game.katrain.log(f"[JigoStrategy] Final decision: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 445 |
+
return aimove, ai_thoughts
|
| 446 |
+
|
| 447 |
+
@register_strategy(AI_SCORELOSS)
|
| 448 |
+
class ScoreLossStrategy(AIStrategy):
|
| 449 |
+
"""ScoreLoss strategy - weights moves based on point loss"""
|
| 450 |
+
|
| 451 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 452 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 453 |
+
self.wait_for_analysis()
|
| 454 |
+
|
| 455 |
+
candidate_moves = self.cn.candidate_moves
|
| 456 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Analysis found {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 457 |
+
|
| 458 |
+
if not candidate_moves:
|
| 459 |
+
self.game.katrain.log(f"[ScoreLossStrategy] No candidate moves found, will play pass", OUTPUT_DEBUG)
|
| 460 |
+
return Move(is_pass=True, player=self.cn.next_player), "No candidate moves found, passing"
|
| 461 |
+
|
| 462 |
+
top_cand = Move.from_gtp(candidate_moves[0]["move"], player=self.cn.next_player)
|
| 463 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Top engine move would be: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 464 |
+
|
| 465 |
+
# Check if top move is pass
|
| 466 |
+
if top_cand.is_pass:
|
| 467 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Top move is pass, so passing regardless of strategy", OUTPUT_DEBUG)
|
| 468 |
+
return top_cand, "Top move is pass, so passing regardless of strategy."
|
| 469 |
+
|
| 470 |
+
# Get strength parameter
|
| 471 |
+
c = self.settings["strength"]
|
| 472 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Strength parameter: {c}", OUTPUT_DEBUG)
|
| 473 |
+
|
| 474 |
+
# Calculate weights for moves based on point loss
|
| 475 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Calculating weights for candidate moves", OUTPUT_DEBUG)
|
| 476 |
+
|
| 477 |
+
moves = []
|
| 478 |
+
for i, d in enumerate(candidate_moves):
|
| 479 |
+
move = Move.from_gtp(d["move"], player=self.cn.next_player)
|
| 480 |
+
points_lost = d["pointsLost"]
|
| 481 |
+
weight = math.exp(min(200, -c * max(0, points_lost)))
|
| 482 |
+
|
| 483 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Move {i+1}: {move.gtp()} - Points lost: {points_lost:.2f}, Weight: {weight:.6f}", OUTPUT_DEBUG)
|
| 484 |
+
moves.append((points_lost, weight, move))
|
| 485 |
+
|
| 486 |
+
# Select move based on weights
|
| 487 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Selecting move with weighted selection", OUTPUT_DEBUG)
|
| 488 |
+
topmove = weighted_selection_without_replacement(moves, 1)[0]
|
| 489 |
+
aimove = topmove[2]
|
| 490 |
+
|
| 491 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Selected move: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 492 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Selected move points lost: {topmove[0]:.2f}", OUTPUT_DEBUG)
|
| 493 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Selected move weight: {topmove[1]:.6f}", OUTPUT_DEBUG)
|
| 494 |
+
|
| 495 |
+
ai_thoughts = f"ScoreLoss strategy found {len(candidate_moves)} candidate moves (best {top_cand.gtp()}) and chose {aimove.gtp()} (weight {topmove[1]:.3f}, point loss {topmove[0]:.1f}) based on score weights."
|
| 496 |
+
|
| 497 |
+
self.game.katrain.log(f"[ScoreLossStrategy] Final decision: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 498 |
+
return aimove, ai_thoughts
|
| 499 |
+
|
| 500 |
+
class OwnershipBaseStrategy(AIStrategy):
|
| 501 |
+
"""Base class for ownership-based strategies"""
|
| 502 |
+
|
| 503 |
+
def settledness(self, d, player_sign, player):
|
| 504 |
+
"""Calculate settledness for Simple Ownership strategy"""
|
| 505 |
+
ownership_sum = sum([abs(o) for o in d["ownership"] if player_sign * o > 0])
|
| 506 |
+
self.game.katrain.log(f"[{self.strategy_name}] Calculating settledness for {player}, sign={player_sign}: {ownership_sum:.2f}", OUTPUT_DEBUG)
|
| 507 |
+
return ownership_sum
|
| 508 |
+
|
| 509 |
+
def is_attachment(self, move):
|
| 510 |
+
"""Check if a move is an attachment"""
|
| 511 |
+
if move.is_pass:
|
| 512 |
+
return False
|
| 513 |
+
|
| 514 |
+
stones_with_player = {(*s.coords, s.player) for s in self.game.stones}
|
| 515 |
+
|
| 516 |
+
attach_opponent_stones = sum(
|
| 517 |
+
(move.coords[0] + dx, move.coords[1] + dy, self.cn.player) in stones_with_player
|
| 518 |
+
for dx in [-1, 0, 1]
|
| 519 |
+
for dy in [-1, 0, 1]
|
| 520 |
+
if abs(dx) + abs(dy) == 1
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
nearby_own_stones = sum(
|
| 524 |
+
(move.coords[0] + dx, move.coords[1] + dy, self.cn.next_player) in stones_with_player
|
| 525 |
+
for dx in [-2, 0, 1, 2]
|
| 526 |
+
for dy in [-2 - 1, 0, 1, 2]
|
| 527 |
+
if abs(dx) + abs(dy) <= 2 # allows clamps/jumps
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
is_attach = attach_opponent_stones >= 1 and nearby_own_stones == 0
|
| 531 |
+
self.game.katrain.log(f"[{self.strategy_name}] Is move {move.gtp()} an attachment? {is_attach} (opponent stones: {attach_opponent_stones}, own stones: {nearby_own_stones})", OUTPUT_DEBUG)
|
| 532 |
+
return is_attach
|
| 533 |
+
|
| 534 |
+
def is_tenuki(self, move):
|
| 535 |
+
"""Check if a move is a tenuki (far from previous moves)"""
|
| 536 |
+
if move.is_pass:
|
| 537 |
+
return False
|
| 538 |
+
|
| 539 |
+
result = not any(
|
| 540 |
+
not node
|
| 541 |
+
or not node.move
|
| 542 |
+
or node.move.is_pass
|
| 543 |
+
or max(abs(last_c - cand_c) for last_c, cand_c in zip(node.move.coords, move.coords)) < 5
|
| 544 |
+
for node in [self.cn, self.cn.parent]
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
distances = []
|
| 548 |
+
for node in [self.cn, self.cn.parent]:
|
| 549 |
+
if node and node.move and not node.move.is_pass:
|
| 550 |
+
dist = max(abs(last_c - cand_c) for last_c, cand_c in zip(node.move.coords, move.coords))
|
| 551 |
+
distances.append(dist)
|
| 552 |
+
|
| 553 |
+
if distances:
|
| 554 |
+
self.game.katrain.log(f"[{self.strategy_name}] Is move {move.gtp()} a tenuki? {result} (distances: {distances})", OUTPUT_DEBUG)
|
| 555 |
+
else:
|
| 556 |
+
self.game.katrain.log(f"[{self.strategy_name}] Is move {move.gtp()} a tenuki? {result} (no valid previous moves)", OUTPUT_DEBUG)
|
| 557 |
+
|
| 558 |
+
return result
|
| 559 |
+
|
| 560 |
+
def get_moves_with_settledness(self):
|
| 561 |
+
"""Get moves with ownership and settledness information"""
|
| 562 |
+
self.game.katrain.log(f"[{self.strategy_name}] Getting moves with settledness information", OUTPUT_DEBUG)
|
| 563 |
+
|
| 564 |
+
next_player_sign = self.cn.player_sign(self.cn.next_player)
|
| 565 |
+
candidate_moves = self.cn.candidate_moves
|
| 566 |
+
|
| 567 |
+
self.game.katrain.log(f"[{self.strategy_name}] Processing {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 568 |
+
self.game.katrain.log(f"[{self.strategy_name}] Settings: max_points_lost={self.settings['max_points_lost']}, min_visits={self.settings.get('min_visits', 1)}", OUTPUT_DEBUG)
|
| 569 |
+
self.game.katrain.log(f"[{self.strategy_name}] Penalties: attach={self.settings['attach_penalty']}, tenuki={self.settings['tenuki_penalty']}", OUTPUT_DEBUG)
|
| 570 |
+
self.game.katrain.log(f"[{self.strategy_name}] Weights: settled={self.settings['settled_weight']}, opponent_fac={self.settings['opponent_fac']}", OUTPUT_DEBUG)
|
| 571 |
+
|
| 572 |
+
moves_data = []
|
| 573 |
+
for d in candidate_moves:
|
| 574 |
+
# Check basic filtering conditions
|
| 575 |
+
if "pointsLost" not in d:
|
| 576 |
+
self.game.katrain.log(f"[{self.strategy_name}] Move {d['move']} has no pointsLost, skipping", OUTPUT_DEBUG)
|
| 577 |
+
continue
|
| 578 |
+
|
| 579 |
+
if d["pointsLost"] >= self.settings["max_points_lost"]:
|
| 580 |
+
self.game.katrain.log(f"[{self.strategy_name}] Move {d['move']} has pointsLost={d['pointsLost']}, which exceeds max_points_lost={self.settings['max_points_lost']}, skipping", OUTPUT_DEBUG)
|
| 581 |
+
continue
|
| 582 |
+
|
| 583 |
+
if "ownership" not in d:
|
| 584 |
+
self.game.katrain.log(f"[{self.strategy_name}] Move {d['move']} has no ownership data, skipping", OUTPUT_DEBUG)
|
| 585 |
+
continue
|
| 586 |
+
|
| 587 |
+
if not (d["order"] <= 1 or d["visits"] >= self.settings.get("min_visits", 1)):
|
| 588 |
+
self.game.katrain.log(f"[{self.strategy_name}] Move {d['move']} has order={d['order']} and visits={d.get('visits', 'N/A')}, doesn't meet criteria, skipping", OUTPUT_DEBUG)
|
| 589 |
+
continue
|
| 590 |
+
|
| 591 |
+
move = Move.from_gtp(d["move"], player=self.cn.next_player)
|
| 592 |
+
if move.is_pass and d["pointsLost"] > 0.75:
|
| 593 |
+
self.game.katrain.log(f"[{self.strategy_name}] Move {move.gtp()} is pass with high point loss ({d['pointsLost']}), skipping", OUTPUT_DEBUG)
|
| 594 |
+
continue
|
| 595 |
+
|
| 596 |
+
# Calculate metrics
|
| 597 |
+
own_settledness = self.settledness(d, next_player_sign, self.cn.next_player)
|
| 598 |
+
opp_settledness = self.settledness(d, -next_player_sign, self.cn.player)
|
| 599 |
+
is_attach = self.is_attachment(move)
|
| 600 |
+
is_tenuki = self.is_tenuki(move)
|
| 601 |
+
|
| 602 |
+
# Calculate total score for sorting
|
| 603 |
+
score = (d["pointsLost"]
|
| 604 |
+
+ self.settings["attach_penalty"] * is_attach
|
| 605 |
+
+ self.settings["tenuki_penalty"] * is_tenuki
|
| 606 |
+
- self.settings["settled_weight"] * (own_settledness + self.settings["opponent_fac"] * opp_settledness))
|
| 607 |
+
|
| 608 |
+
self.game.katrain.log(f"[{self.strategy_name}] Move {move.gtp()}: points_lost={d['pointsLost']:.2f}, own_settled={own_settledness:.2f}, opp_settled={opp_settledness:.2f}, attach={is_attach}, tenuki={is_tenuki}, score={score:.2f}", OUTPUT_DEBUG)
|
| 609 |
+
|
| 610 |
+
moves_data.append((
|
| 611 |
+
move,
|
| 612 |
+
own_settledness,
|
| 613 |
+
opp_settledness,
|
| 614 |
+
is_attach,
|
| 615 |
+
is_tenuki,
|
| 616 |
+
d,
|
| 617 |
+
score # Store the score for debugging
|
| 618 |
+
))
|
| 619 |
+
|
| 620 |
+
# Sort moves by score
|
| 621 |
+
sorted_moves = sorted(
|
| 622 |
+
moves_data,
|
| 623 |
+
key=lambda t: t[6] # Sort by the precalculated score
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
self.game.katrain.log(f"[{self.strategy_name}] Found {len(sorted_moves)} valid moves with settledness data", OUTPUT_DEBUG)
|
| 627 |
+
if sorted_moves:
|
| 628 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top move after sorting: {sorted_moves[0][0].gtp()} with score {sorted_moves[0][6]:.2f}", OUTPUT_DEBUG)
|
| 629 |
+
|
| 630 |
+
# Return all data except the score which was just for debugging
|
| 631 |
+
return [(move, own_settled, opp_settled, is_attach, is_tenuki, d) for move, own_settled, opp_settled, is_attach, is_tenuki, d, _ in sorted_moves]
|
| 632 |
+
|
| 633 |
+
@register_strategy(AI_SIMPLE_OWNERSHIP)
|
| 634 |
+
class SimpleOwnershipStrategy(OwnershipBaseStrategy):
|
| 635 |
+
"""Simple Ownership strategy - weights moves based on territory control"""
|
| 636 |
+
|
| 637 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 638 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 639 |
+
self.wait_for_analysis()
|
| 640 |
+
|
| 641 |
+
candidate_moves = self.cn.candidate_moves
|
| 642 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Analysis found {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 643 |
+
|
| 644 |
+
if not candidate_moves:
|
| 645 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] No candidate moves found, will play pass", OUTPUT_DEBUG)
|
| 646 |
+
return Move(is_pass=True, player=self.cn.next_player), "No candidate moves found, passing"
|
| 647 |
+
|
| 648 |
+
top_cand = Move.from_gtp(candidate_moves[0]["move"], player=self.cn.next_player)
|
| 649 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Top engine move would be: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 650 |
+
|
| 651 |
+
# Check if top move is pass
|
| 652 |
+
if top_cand.is_pass:
|
| 653 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Top move is pass, so passing regardless of strategy", OUTPUT_DEBUG)
|
| 654 |
+
return top_cand, "Top move is pass, so passing regardless of strategy."
|
| 655 |
+
|
| 656 |
+
# Get moves sorted by settledness criteria
|
| 657 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Getting moves with settledness info", OUTPUT_DEBUG)
|
| 658 |
+
moves_with_settledness = self.get_moves_with_settledness()
|
| 659 |
+
|
| 660 |
+
if moves_with_settledness:
|
| 661 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Found {len(moves_with_settledness)} moves with settledness info", OUTPUT_DEBUG)
|
| 662 |
+
|
| 663 |
+
# Log top 5 candidates in detail
|
| 664 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Top 5 candidates:", OUTPUT_DEBUG)
|
| 665 |
+
for i, (move, settled, oppsettled, isattach, istenuki, d) in enumerate(moves_with_settledness[:5]):
|
| 666 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] #{i+1}: {move.gtp()} - pt_lost: {d['pointsLost']:.1f}, visits: {d.get('visits', 'N/A')}, settledness: {settled:.1f}, opp_settled: {oppsettled:.1f}, attach: {isattach}, tenuki: {istenuki}", OUTPUT_DEBUG)
|
| 667 |
+
|
| 668 |
+
# Format candidate moves for ai_thoughts
|
| 669 |
+
cands = [
|
| 670 |
+
f"{move.gtp()} ({d['pointsLost']:.1f} pt lost, {d.get('visits', 'N/A')} visits, {settled:.1f} settledness, {oppsettled:.1f} opponent settledness{', attachment' if isattach else ''}{', tenuki' if istenuki else ''})"
|
| 671 |
+
for move, settled, oppsettled, isattach, istenuki, d in moves_with_settledness[:5]
|
| 672 |
+
]
|
| 673 |
+
|
| 674 |
+
ai_thoughts = f"{AI_SIMPLE_OWNERSHIP} strategy. Top 5 Candidates {', '.join(cands)} "
|
| 675 |
+
aimove = moves_with_settledness[0][0]
|
| 676 |
+
|
| 677 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Selected move: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 678 |
+
else:
|
| 679 |
+
error_msg = "No moves found - are you using an older KataGo with no per-move ownership info?"
|
| 680 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Error: {error_msg}", OUTPUT_ERROR)
|
| 681 |
+
raise Exception(error_msg)
|
| 682 |
+
|
| 683 |
+
self.game.katrain.log(f"[SimpleOwnershipStrategy] Final decision: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 684 |
+
return aimove, ai_thoughts
|
| 685 |
+
|
| 686 |
+
@register_strategy(AI_SETTLE_STONES)
|
| 687 |
+
class SettleStonesStrategy(OwnershipBaseStrategy):
|
| 688 |
+
"""Settle Stones strategy - focuses on settled stones"""
|
| 689 |
+
|
| 690 |
+
def settledness(self, d, player_sign, player):
|
| 691 |
+
"""Calculate settledness for Settle Stones strategy"""
|
| 692 |
+
board_size_x, board_size_y = self.game.board_size
|
| 693 |
+
ownership_grid = var_to_grid(d["ownership"], (board_size_x, board_size_y))
|
| 694 |
+
|
| 695 |
+
# Sum the absolute ownership values of existing stones
|
| 696 |
+
stone_ownership_values = [abs(ownership_grid[s.coords[0]][s.coords[1]]) for s in self.game.stones if s.player == player]
|
| 697 |
+
total_settledness = sum(stone_ownership_values)
|
| 698 |
+
|
| 699 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Calculating settledness for {player}, sign={player_sign}", OUTPUT_DEBUG)
|
| 700 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Number of stones considered: {len(stone_ownership_values)}", OUTPUT_DEBUG)
|
| 701 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Total settledness: {total_settledness:.2f}", OUTPUT_DEBUG)
|
| 702 |
+
|
| 703 |
+
if stone_ownership_values:
|
| 704 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Min stone ownership: {min(stone_ownership_values):.2f}", OUTPUT_DEBUG)
|
| 705 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Max stone ownership: {max(stone_ownership_values):.2f}", OUTPUT_DEBUG)
|
| 706 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Avg stone ownership: {total_settledness / len(stone_ownership_values):.2f}", OUTPUT_DEBUG)
|
| 707 |
+
|
| 708 |
+
return total_settledness
|
| 709 |
+
|
| 710 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 711 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 712 |
+
self.wait_for_analysis()
|
| 713 |
+
|
| 714 |
+
candidate_moves = self.cn.candidate_moves
|
| 715 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Analysis found {len(candidate_moves)} candidate moves", OUTPUT_DEBUG)
|
| 716 |
+
|
| 717 |
+
if not candidate_moves:
|
| 718 |
+
self.game.katrain.log(f"[SettleStonesStrategy] No candidate moves found, will play pass", OUTPUT_DEBUG)
|
| 719 |
+
return Move(is_pass=True, player=self.cn.next_player), "No candidate moves found, passing"
|
| 720 |
+
|
| 721 |
+
top_cand = Move.from_gtp(candidate_moves[0]["move"], player=self.cn.next_player)
|
| 722 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Top engine move would be: {top_cand.gtp()}", OUTPUT_DEBUG)
|
| 723 |
+
|
| 724 |
+
# Check if top move is pass
|
| 725 |
+
if top_cand.is_pass:
|
| 726 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Top move is pass, so passing regardless of strategy", OUTPUT_DEBUG)
|
| 727 |
+
return top_cand, "Top move is pass, so passing regardless of strategy."
|
| 728 |
+
|
| 729 |
+
# Log the number of stones on the board
|
| 730 |
+
black_stones = sum(1 for s in self.game.stones if s.player == "B")
|
| 731 |
+
white_stones = sum(1 for s in self.game.stones if s.player == "W")
|
| 732 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Stones on board: B={black_stones}, W={white_stones}", OUTPUT_DEBUG)
|
| 733 |
+
|
| 734 |
+
# Get moves sorted by settledness criteria
|
| 735 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Getting moves with settledness info", OUTPUT_DEBUG)
|
| 736 |
+
moves_with_settledness = self.get_moves_with_settledness()
|
| 737 |
+
|
| 738 |
+
if moves_with_settledness:
|
| 739 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Found {len(moves_with_settledness)} moves with settledness info", OUTPUT_DEBUG)
|
| 740 |
+
|
| 741 |
+
# Log top 5 candidates in detail
|
| 742 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Top 5 candidates:", OUTPUT_DEBUG)
|
| 743 |
+
for i, (move, settled, oppsettled, isattach, istenuki, d) in enumerate(moves_with_settledness[:5]):
|
| 744 |
+
self.game.katrain.log(f"[SettleStonesStrategy] #{i+1}: {move.gtp()} - pt_lost: {d['pointsLost']:.1f}, visits: {d.get('visits', 'N/A')}, settledness: {settled:.1f}, opp_settled: {oppsettled:.1f}, attach: {isattach}, tenuki: {istenuki}", OUTPUT_DEBUG)
|
| 745 |
+
|
| 746 |
+
# Format candidate moves for ai_thoughts
|
| 747 |
+
cands = [
|
| 748 |
+
f"{move.gtp()} ({d['pointsLost']:.1f} pt lost, {d.get('visits', 'N/A')} visits, {settled:.1f} settledness, {oppsettled:.1f} opponent settledness{', attachment' if isattach else ''}{', tenuki' if istenuki else ''})"
|
| 749 |
+
for move, settled, oppsettled, isattach, istenuki, d in moves_with_settledness[:5]
|
| 750 |
+
]
|
| 751 |
+
|
| 752 |
+
ai_thoughts = f"{AI_SETTLE_STONES} strategy. Top 5 Candidates {', '.join(cands)} "
|
| 753 |
+
aimove = moves_with_settledness[0][0]
|
| 754 |
+
|
| 755 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Selected move: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 756 |
+
else:
|
| 757 |
+
error_msg = "No moves found - are you using an older KataGo with no per-move ownership info?"
|
| 758 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Error: {error_msg}", OUTPUT_ERROR)
|
| 759 |
+
raise Exception(error_msg)
|
| 760 |
+
|
| 761 |
+
self.game.katrain.log(f"[SettleStonesStrategy] Final decision: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 762 |
+
return aimove, ai_thoughts
|
| 763 |
+
|
| 764 |
+
@register_strategy(AI_POLICY)
|
| 765 |
+
class PolicyStrategy(AIStrategy):
|
| 766 |
+
"""Policy strategy - plays the top move suggested by policy network"""
|
| 767 |
+
|
| 768 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 769 |
+
self.game.katrain.log(f"[PolicyStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 770 |
+
self.wait_for_analysis()
|
| 771 |
+
|
| 772 |
+
# Ensure policy is available
|
| 773 |
+
if not self.cn.policy:
|
| 774 |
+
self.game.katrain.log(f"[PolicyStrategy] No policy data available, falling back to DefaultStrategy", OUTPUT_DEBUG)
|
| 775 |
+
return DefaultStrategy(self.game, self.settings).generate_move()
|
| 776 |
+
|
| 777 |
+
policy_moves = self.cn.policy_ranking
|
| 778 |
+
pass_policy = self.cn.policy[-1]
|
| 779 |
+
|
| 780 |
+
self.game.katrain.log(f"[PolicyStrategy] Got {len(policy_moves)} policy moves", OUTPUT_DEBUG)
|
| 781 |
+
self.game.katrain.log(f"[PolicyStrategy] Current move depth: {self.cn.depth}", OUTPUT_DEBUG)
|
| 782 |
+
self.game.katrain.log(f"[PolicyStrategy] Opening moves setting: {self.settings.get('opening_moves', 0)}", OUTPUT_DEBUG)
|
| 783 |
+
|
| 784 |
+
# Log top 5 policy moves
|
| 785 |
+
self.game.katrain.log(f"[PolicyStrategy] Top 5 policy moves:", OUTPUT_DEBUG)
|
| 786 |
+
for i, (prob, move) in enumerate(policy_moves[:5]):
|
| 787 |
+
self.game.katrain.log(f"[PolicyStrategy] #{i+1}: {move.gtp()} - {prob:.2%}", OUTPUT_DEBUG)
|
| 788 |
+
|
| 789 |
+
self.game.katrain.log(f"[PolicyStrategy] Pass policy: {pass_policy:.2%}", OUTPUT_DEBUG)
|
| 790 |
+
|
| 791 |
+
# Check for pass in top 5
|
| 792 |
+
top_5_pass = any([polmove[1].is_pass for polmove in policy_moves[:5]])
|
| 793 |
+
self.game.katrain.log(f"[PolicyStrategy] Pass in top 5: {top_5_pass}", OUTPUT_DEBUG)
|
| 794 |
+
|
| 795 |
+
# Handle opening moves override
|
| 796 |
+
if self.cn.depth <= self.settings.get("opening_moves", 0):
|
| 797 |
+
self.game.katrain.log(f"[PolicyStrategy] In opening phase, using WeightedStrategy instead", OUTPUT_DEBUG)
|
| 798 |
+
weighted_settings = {
|
| 799 |
+
"pick_override": 0.9,
|
| 800 |
+
"weaken_fac": 1,
|
| 801 |
+
"lower_bound": 0.02
|
| 802 |
+
}
|
| 803 |
+
self.game.katrain.log(f"[PolicyStrategy] Weighted settings: {weighted_settings}", OUTPUT_DEBUG)
|
| 804 |
+
return WeightedStrategy(self.game, weighted_settings).generate_move()
|
| 805 |
+
|
| 806 |
+
# Check for pass in top 5
|
| 807 |
+
if top_5_pass:
|
| 808 |
+
aimove = policy_moves[0][1]
|
| 809 |
+
self.game.katrain.log(f"[PolicyStrategy] Playing top move {aimove.gtp()} because pass in top 5", OUTPUT_DEBUG)
|
| 810 |
+
ai_thoughts = "Playing top one because one of them is pass."
|
| 811 |
+
return aimove, ai_thoughts
|
| 812 |
+
|
| 813 |
+
# Otherwise play top policy move
|
| 814 |
+
aimove = policy_moves[0][1]
|
| 815 |
+
self.game.katrain.log(f"[PolicyStrategy] Playing top policy move {aimove.gtp()} with probability {policy_moves[0][0]:.2%}", OUTPUT_DEBUG)
|
| 816 |
+
ai_thoughts = f"Playing top policy move {aimove.gtp()}."
|
| 817 |
+
|
| 818 |
+
self.game.katrain.log(f"[PolicyStrategy] Final decision: {aimove.gtp()}", OUTPUT_DEBUG)
|
| 819 |
+
return aimove, ai_thoughts
|
| 820 |
+
|
| 821 |
+
@register_strategy(AI_WEIGHTED)
|
| 822 |
+
class WeightedStrategy(AIStrategy):
|
| 823 |
+
"""Weighted strategy - weights moves based on policy and a weakening factor"""
|
| 824 |
+
|
| 825 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 826 |
+
self.game.katrain.log(f"[WeightedStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 827 |
+
self.wait_for_analysis()
|
| 828 |
+
|
| 829 |
+
# Ensure policy is available
|
| 830 |
+
if not self.cn.policy:
|
| 831 |
+
self.game.katrain.log(f"[WeightedStrategy] No policy data available, falling back to DefaultStrategy", OUTPUT_DEBUG)
|
| 832 |
+
return DefaultStrategy(self.game, self.settings).generate_move()
|
| 833 |
+
|
| 834 |
+
policy_moves = self.cn.policy_ranking
|
| 835 |
+
pass_policy = self.cn.policy[-1]
|
| 836 |
+
|
| 837 |
+
self.game.katrain.log(f"[WeightedStrategy] Got {len(policy_moves)} policy moves", OUTPUT_DEBUG)
|
| 838 |
+
|
| 839 |
+
# Log top 5 policy moves
|
| 840 |
+
self.game.katrain.log(f"[WeightedStrategy] Top 5 policy moves:", OUTPUT_DEBUG)
|
| 841 |
+
for i, (prob, move) in enumerate(policy_moves[:5]):
|
| 842 |
+
self.game.katrain.log(f"[WeightedStrategy] #{i+1}: {move.gtp()} - {prob:.2%}", OUTPUT_DEBUG)
|
| 843 |
+
|
| 844 |
+
self.game.katrain.log(f"[WeightedStrategy] Pass policy: {pass_policy:.2%}", OUTPUT_DEBUG)
|
| 845 |
+
|
| 846 |
+
# Check for pass in top 5
|
| 847 |
+
top_5_pass = any([polmove[1].is_pass for polmove in policy_moves[:5]])
|
| 848 |
+
self.game.katrain.log(f"[WeightedStrategy] Pass in top 5: {top_5_pass}", OUTPUT_DEBUG)
|
| 849 |
+
|
| 850 |
+
# Get override threshold
|
| 851 |
+
override = self.settings.get("pick_override", 0.0)
|
| 852 |
+
self.game.katrain.log(f"[WeightedStrategy] Override threshold: {override:.2%}", OUTPUT_DEBUG)
|
| 853 |
+
|
| 854 |
+
# Check if we should override with top move
|
| 855 |
+
override_move, override_thoughts = self.should_play_top_move(
|
| 856 |
+
policy_moves,
|
| 857 |
+
top_5_pass,
|
| 858 |
+
override=override
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
if override_move:
|
| 862 |
+
self.game.katrain.log(f"[WeightedStrategy] Using override move: {override_move.gtp()}", OUTPUT_DEBUG)
|
| 863 |
+
return override_move, override_thoughts
|
| 864 |
+
|
| 865 |
+
# Apply weighted policy move selection
|
| 866 |
+
lower_bound = self.settings.get("lower_bound", 0.02)
|
| 867 |
+
weaken_fac = self.settings.get("weaken_fac", 1.0)
|
| 868 |
+
|
| 869 |
+
self.game.katrain.log(f"[WeightedStrategy] Using weighted selection with lower_bound={lower_bound:.2%}, weaken_fac={weaken_fac}", OUTPUT_DEBUG)
|
| 870 |
+
|
| 871 |
+
# Generate list of weighted coordinates
|
| 872 |
+
weighted_coords = [
|
| 873 |
+
(pv, pv ** (1 / weaken_fac), move) for pv, move in policy_moves if pv > lower_bound and not move.is_pass
|
| 874 |
+
]
|
| 875 |
+
|
| 876 |
+
self.game.katrain.log(f"[WeightedStrategy] Found {len(weighted_coords)} moves above lower bound", OUTPUT_DEBUG)
|
| 877 |
+
|
| 878 |
+
if weighted_coords:
|
| 879 |
+
self.game.katrain.log(f"[WeightedStrategy] Performing weighted selection", OUTPUT_DEBUG)
|
| 880 |
+
top = weighted_selection_without_replacement(weighted_coords, 1)[0]
|
| 881 |
+
move = top[2]
|
| 882 |
+
prob = top[0]
|
| 883 |
+
|
| 884 |
+
self.game.katrain.log(f"[WeightedStrategy] Selected move {move.gtp()} with probability {prob:.2%}", OUTPUT_DEBUG)
|
| 885 |
+
ai_thoughts = f"Playing policy-weighted random move {move.gtp()} ({prob:.1%}) from {len(weighted_coords)} moves above lower_bound of {lower_bound:.1%}."
|
| 886 |
+
else:
|
| 887 |
+
move = policy_moves[0][1]
|
| 888 |
+
self.game.katrain.log(f"[WeightedStrategy] No moves above lower bound, playing top policy move {move.gtp()}", OUTPUT_DEBUG)
|
| 889 |
+
ai_thoughts = f"Playing top policy move because no non-pass move > above lower_bound of {lower_bound:.1%}."
|
| 890 |
+
|
| 891 |
+
self.game.katrain.log(f"[WeightedStrategy] Final decision: {move.gtp()}", OUTPUT_DEBUG)
|
| 892 |
+
return move, ai_thoughts
|
| 893 |
+
|
| 894 |
+
class PickBasedStrategy(AIStrategy):
|
| 895 |
+
"""Base class for pick-based strategies"""
|
| 896 |
+
|
| 897 |
+
def get_n_moves(self, legal_policy_moves):
|
| 898 |
+
"""Calculate the number of moves to consider"""
|
| 899 |
+
board_squares = self.game.board_size[0] * self.game.board_size[1]
|
| 900 |
+
|
| 901 |
+
if self.settings.get("pick_frac") is not None:
|
| 902 |
+
n_moves = max(1, int(self.settings["pick_frac"] * len(legal_policy_moves) + self.settings["pick_n"]))
|
| 903 |
+
self.game.katrain.log(f"[{self.strategy_name}] Calculated n_moves={n_moves} from pick_frac={self.settings['pick_frac']}, pick_n={self.settings['pick_n']}, legal_moves={len(legal_policy_moves)}", OUTPUT_DEBUG)
|
| 904 |
+
else:
|
| 905 |
+
n_moves = 1 # Default
|
| 906 |
+
self.game.katrain.log(f"[{self.strategy_name}] Using default n_moves={n_moves} (no pick_frac in settings)", OUTPUT_DEBUG)
|
| 907 |
+
|
| 908 |
+
return n_moves
|
| 909 |
+
|
| 910 |
+
def generate_weighted_coords(self, legal_policy_moves, policy_grid, size):
|
| 911 |
+
"""Generate weighted coordinates for selection"""
|
| 912 |
+
self.game.katrain.log(f"[{self.strategy_name}] Generating weighted coordinates (default equal weights implementation)", OUTPUT_DEBUG)
|
| 913 |
+
|
| 914 |
+
# Default implementation for AI_PICK - equal weights
|
| 915 |
+
weighted_coords = [
|
| 916 |
+
(policy_grid[y][x], 1, x, y)
|
| 917 |
+
for x in range(size[0])
|
| 918 |
+
for y in range(size[1])
|
| 919 |
+
if policy_grid[y][x] > 0
|
| 920 |
+
]
|
| 921 |
+
|
| 922 |
+
self.game.katrain.log(f"[{self.strategy_name}] Generated {len(weighted_coords)} weighted coordinates", OUTPUT_DEBUG)
|
| 923 |
+
|
| 924 |
+
if weighted_coords:
|
| 925 |
+
top5 = heapq.nlargest(5, weighted_coords, key=lambda t: t[0])
|
| 926 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top 5 weighted coordinates by policy value:", OUTPUT_DEBUG)
|
| 927 |
+
for i, (pol, wt, x, y) in enumerate(top5):
|
| 928 |
+
self.game.katrain.log(f"[{self.strategy_name}] #{i+1}: ({x},{y}) - policy={pol:.2%}, weight={wt}", OUTPUT_DEBUG)
|
| 929 |
+
|
| 930 |
+
return weighted_coords, "Generated equal weights for all moves. "
|
| 931 |
+
|
| 932 |
+
def handle_endgame(self, legal_policy_moves, policy_grid, size):
|
| 933 |
+
"""Handle special endgame case"""
|
| 934 |
+
board_squares = size[0] * size[1]
|
| 935 |
+
endgame_threshold = self.settings.get("endgame", 0.75) * board_squares
|
| 936 |
+
|
| 937 |
+
self.game.katrain.log(f"[{self.strategy_name}] Checking endgame condition: move depth {self.cn.depth} vs threshold {endgame_threshold}", OUTPUT_DEBUG)
|
| 938 |
+
|
| 939 |
+
if self.cn.depth > endgame_threshold:
|
| 940 |
+
self.game.katrain.log(f"[{self.strategy_name}] In endgame phase (move {self.cn.depth} > {endgame_threshold})", OUTPUT_DEBUG)
|
| 941 |
+
|
| 942 |
+
weighted_coords = [(pol, 1, *mv.coords) for pol, mv in legal_policy_moves]
|
| 943 |
+
ai_thoughts = f"Generated equal weights as move number >= {self.settings['endgame'] * size[0] * size[1]}. "
|
| 944 |
+
|
| 945 |
+
n_moves = int(max(self.get_n_moves(legal_policy_moves), len(legal_policy_moves) // 2))
|
| 946 |
+
self.game.katrain.log(f"[{self.strategy_name}] Using endgame n_moves={n_moves}", OUTPUT_DEBUG)
|
| 947 |
+
|
| 948 |
+
self.game.katrain.log(f"[{self.strategy_name}] Generated {len(weighted_coords)} weighted coordinates for endgame", OUTPUT_DEBUG)
|
| 949 |
+
|
| 950 |
+
return weighted_coords, ai_thoughts, n_moves, True
|
| 951 |
+
|
| 952 |
+
self.game.katrain.log(f"[{self.strategy_name}] Not in endgame phase yet", OUTPUT_DEBUG)
|
| 953 |
+
return None, "", None, False
|
| 954 |
+
|
| 955 |
+
def select_from_weighted_coords(self, weighted_coords, n_moves, pass_policy):
|
| 956 |
+
"""Select moves from weighted coordinates"""
|
| 957 |
+
self.game.katrain.log(f"[{self.strategy_name}] Selecting from {len(weighted_coords)} weighted coordinates, n_moves={n_moves}", OUTPUT_DEBUG)
|
| 958 |
+
|
| 959 |
+
# Perform weighted selection
|
| 960 |
+
pick_moves = weighted_selection_without_replacement(weighted_coords, n_moves)
|
| 961 |
+
self.game.katrain.log(f"[{self.strategy_name}] Picked {len(pick_moves)} moves", OUTPUT_DEBUG)
|
| 962 |
+
|
| 963 |
+
if pick_moves:
|
| 964 |
+
# Get top 5 from picked moves
|
| 965 |
+
top_picked = heapq.nlargest(5, pick_moves)
|
| 966 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top 5 after selection:", OUTPUT_DEBUG)
|
| 967 |
+
for i, (p, wt, x, y) in enumerate(top_picked):
|
| 968 |
+
self.game.katrain.log(f"[{self.strategy_name}] #{i+1}: ({x},{y}) - policy={p:.2%}, weight={wt}", OUTPUT_DEBUG)
|
| 969 |
+
|
| 970 |
+
# Convert to move objects
|
| 971 |
+
new_top = [
|
| 972 |
+
(p, Move((x, y), player=self.cn.next_player)) for p, wt, x, y in top_picked
|
| 973 |
+
]
|
| 974 |
+
|
| 975 |
+
aimove = new_top[0][1]
|
| 976 |
+
ai_thoughts = f"Top 5 among these were {fmt_moves(new_top)} and picked top {aimove.gtp()}. "
|
| 977 |
+
|
| 978 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top picked move: {aimove.gtp()} ({new_top[0][0]:.2%})", OUTPUT_DEBUG)
|
| 979 |
+
self.game.katrain.log(f"[{self.strategy_name}] Pass policy: {pass_policy:.2%}", OUTPUT_DEBUG)
|
| 980 |
+
|
| 981 |
+
# Check if pass is better
|
| 982 |
+
if new_top[0][0] < pass_policy:
|
| 983 |
+
self.game.katrain.log(f"[{self.strategy_name}] Pass policy {pass_policy:.2%} is better than top move {aimove.gtp()} ({new_top[0][0]:.2%}), switching to top policy move", OUTPUT_DEBUG)
|
| 984 |
+
|
| 985 |
+
policy_moves = self.cn.policy_ranking
|
| 986 |
+
top_policy_move = policy_moves[0][1]
|
| 987 |
+
|
| 988 |
+
ai_thoughts += f"But found pass ({pass_policy:.2%} to be higher rated than {aimove.gtp()} ({new_top[0][0]:.2%}) so will play top policy move instead."
|
| 989 |
+
aimove = top_policy_move
|
| 990 |
+
|
| 991 |
+
self.game.katrain.log(f"[{self.strategy_name}] Final move (after pass check): {aimove.gtp()}", OUTPUT_DEBUG)
|
| 992 |
+
else:
|
| 993 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top move is better than pass, keeping it", OUTPUT_DEBUG)
|
| 994 |
+
else:
|
| 995 |
+
self.game.katrain.log(f"[{self.strategy_name}] No moves selected, falling back to top policy move", OUTPUT_DEBUG)
|
| 996 |
+
|
| 997 |
+
policy_moves = self.cn.policy_ranking
|
| 998 |
+
top_policy_move = policy_moves[0][1]
|
| 999 |
+
aimove = top_policy_move
|
| 1000 |
+
|
| 1001 |
+
ai_thoughts = f"Pick policy strategy failed to find legal moves, so is playing top policy move {aimove.gtp()}."
|
| 1002 |
+
|
| 1003 |
+
self.game.katrain.log(f"[{self.strategy_name}] Final move (fallback): {aimove.gtp()}", OUTPUT_DEBUG)
|
| 1004 |
+
|
| 1005 |
+
return aimove, ai_thoughts
|
| 1006 |
+
|
| 1007 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 1008 |
+
self.game.katrain.log(f"[{self.strategy_name}] Starting move generation", OUTPUT_DEBUG)
|
| 1009 |
+
self.wait_for_analysis()
|
| 1010 |
+
|
| 1011 |
+
# Ensure policy is available
|
| 1012 |
+
if not self.cn.policy:
|
| 1013 |
+
self.game.katrain.log(f"[{self.strategy_name}] No policy data available, falling back to DefaultStrategy", OUTPUT_DEBUG)
|
| 1014 |
+
return DefaultStrategy(self.game, self.settings).generate_move()
|
| 1015 |
+
|
| 1016 |
+
policy_moves = self.cn.policy_ranking
|
| 1017 |
+
pass_policy = self.cn.policy[-1]
|
| 1018 |
+
|
| 1019 |
+
self.game.katrain.log(f"[{self.strategy_name}] Got {len(policy_moves)} policy moves", OUTPUT_DEBUG)
|
| 1020 |
+
|
| 1021 |
+
# Log top 5 policy moves
|
| 1022 |
+
self.game.katrain.log(f"[{self.strategy_name}] Top 5 policy moves:", OUTPUT_DEBUG)
|
| 1023 |
+
for i, (prob, move) in enumerate(policy_moves[:5]):
|
| 1024 |
+
self.game.katrain.log(f"[{self.strategy_name}] #{i+1}: {move.gtp()} - {prob:.2%}", OUTPUT_DEBUG)
|
| 1025 |
+
|
| 1026 |
+
self.game.katrain.log(f"[{self.strategy_name}] Pass policy: {pass_policy:.2%}", OUTPUT_DEBUG)
|
| 1027 |
+
|
| 1028 |
+
# Check for pass in top 5
|
| 1029 |
+
top_5_pass = any([polmove[1].is_pass for polmove in policy_moves[:5]])
|
| 1030 |
+
self.game.katrain.log(f"[{self.strategy_name}] Pass in top 5: {top_5_pass}", OUTPUT_DEBUG)
|
| 1031 |
+
|
| 1032 |
+
# Get override settings
|
| 1033 |
+
override = self.settings.get("pick_override", 0.0)
|
| 1034 |
+
overridetwo = self.settings.get("pick_override_two", 1.0)
|
| 1035 |
+
self.game.katrain.log(f"[{self.strategy_name}] Override settings: single={override:.2%}, combined={overridetwo:.2%}", OUTPUT_DEBUG)
|
| 1036 |
+
|
| 1037 |
+
# Check if we should override with top move
|
| 1038 |
+
override_move, override_thoughts = self.should_play_top_move(
|
| 1039 |
+
policy_moves,
|
| 1040 |
+
top_5_pass,
|
| 1041 |
+
override=override,
|
| 1042 |
+
overridetwo=overridetwo
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
if override_move:
|
| 1046 |
+
self.game.katrain.log(f"[{self.strategy_name}] Using override move: {override_move.gtp()}", OUTPUT_DEBUG)
|
| 1047 |
+
return override_move, override_thoughts
|
| 1048 |
+
|
| 1049 |
+
# Get legal policy moves
|
| 1050 |
+
legal_policy_moves = [(pol, mv) for pol, mv in policy_moves if not mv.is_pass and pol > 0]
|
| 1051 |
+
self.game.katrain.log(f"[{self.strategy_name}] Found {len(legal_policy_moves)} legal non-pass policy moves", OUTPUT_DEBUG)
|
| 1052 |
+
|
| 1053 |
+
# Create policy grid
|
| 1054 |
+
# Create policy grid
|
| 1055 |
+
size = self.game.board_size
|
| 1056 |
+
self.game.katrain.log(f"[{self.strategy_name}] Board size: {size}", OUTPUT_DEBUG)
|
| 1057 |
+
policy_grid = var_to_grid(self.cn.policy, size)
|
| 1058 |
+
|
| 1059 |
+
# Check for endgame
|
| 1060 |
+
end_coords, end_thoughts, end_n_moves, is_endgame = self.handle_endgame(legal_policy_moves, policy_grid, size)
|
| 1061 |
+
|
| 1062 |
+
if is_endgame:
|
| 1063 |
+
self.game.katrain.log(f"[{self.strategy_name}] Using endgame logic", OUTPUT_DEBUG)
|
| 1064 |
+
return self.select_from_weighted_coords(end_coords, end_n_moves, pass_policy)
|
| 1065 |
+
|
| 1066 |
+
# Get weighted coordinates
|
| 1067 |
+
self.game.katrain.log(f"[{self.strategy_name}] Generating weighted coordinates", OUTPUT_DEBUG)
|
| 1068 |
+
weighted_coords, weight_thoughts = self.generate_weighted_coords(legal_policy_moves, policy_grid, size)
|
| 1069 |
+
|
| 1070 |
+
# Get number of moves to consider
|
| 1071 |
+
n_moves = self.get_n_moves(legal_policy_moves)
|
| 1072 |
+
self.game.katrain.log(f"[{self.strategy_name}] Using n_moves={n_moves}", OUTPUT_DEBUG)
|
| 1073 |
+
|
| 1074 |
+
ai_thoughts = weight_thoughts + f"Picked {min(n_moves, len(weighted_coords))} random moves according to weights. "
|
| 1075 |
+
|
| 1076 |
+
# Select and return move
|
| 1077 |
+
self.game.katrain.log(f"[{self.strategy_name}] Selecting move from weighted coordinates", OUTPUT_DEBUG)
|
| 1078 |
+
move, thoughts = self.select_from_weighted_coords(weighted_coords, n_moves, pass_policy)
|
| 1079 |
+
|
| 1080 |
+
self.game.katrain.log(f"[{self.strategy_name}] Final decision: {move.gtp()}", OUTPUT_DEBUG)
|
| 1081 |
+
return move, ai_thoughts + thoughts
|
| 1082 |
+
|
| 1083 |
+
@register_strategy(AI_PICK)
|
| 1084 |
+
class PickStrategy(PickBasedStrategy):
|
| 1085 |
+
"""Pick strategy - picks a move from a subset of legal moves"""
|
| 1086 |
+
|
| 1087 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 1088 |
+
self.game.katrain.log(f"[PickStrategy] Starting move generation using base PickBasedStrategy implementation", OUTPUT_DEBUG)
|
| 1089 |
+
return super().generate_move()
|
| 1090 |
+
|
| 1091 |
+
def handle_endgame(self, legal_policy_moves, policy_grid, size):
|
| 1092 |
+
return None, "", None, False
|
| 1093 |
+
|
| 1094 |
+
@register_strategy(AI_RANK)
|
| 1095 |
+
class RankStrategy(PickBasedStrategy):
|
| 1096 |
+
"""Rank strategy - similar to Pick but calibrated based on rank"""
|
| 1097 |
+
|
| 1098 |
+
def get_n_moves(self, legal_policy_moves):
|
| 1099 |
+
"""Calculate n_moves based on rank"""
|
| 1100 |
+
self.game.katrain.log(f"[RankStrategy] Calculating n_moves based on rank", OUTPUT_DEBUG)
|
| 1101 |
+
|
| 1102 |
+
size = self.game.board_size
|
| 1103 |
+
board_squares = size[0] * size[1]
|
| 1104 |
+
norm_leg_moves = len(legal_policy_moves) / board_squares
|
| 1105 |
+
|
| 1106 |
+
self.game.katrain.log(f"[RankStrategy] Board squares: {board_squares}", OUTPUT_DEBUG)
|
| 1107 |
+
self.game.katrain.log(f"[RankStrategy] Legal moves: {len(legal_policy_moves)}", OUTPUT_DEBUG)
|
| 1108 |
+
self.game.katrain.log(f"[RankStrategy] Normalized legal moves: {norm_leg_moves:.4f}", OUTPUT_DEBUG)
|
| 1109 |
+
self.game.katrain.log(f"[RankStrategy] Kyu rank: {self.settings['kyu_rank']}", OUTPUT_DEBUG)
|
| 1110 |
+
|
| 1111 |
+
# Calculate n_moves using the rank formula
|
| 1112 |
+
orig_calib_avemodrank = 0.063015 + 0.7624 * board_squares / (
|
| 1113 |
+
10 ** (-0.05737 * self.settings["kyu_rank"] + 1.9482)
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
self.game.katrain.log(f"[RankStrategy] Original calibrated average mod rank: {orig_calib_avemodrank:.4f}", OUTPUT_DEBUG)
|
| 1117 |
+
|
| 1118 |
+
exponent_term = (
|
| 1119 |
+
3.002 * norm_leg_moves * norm_leg_moves
|
| 1120 |
+
- norm_leg_moves
|
| 1121 |
+
- 0.034889 * self.settings["kyu_rank"]
|
| 1122 |
+
- 0.5097
|
| 1123 |
+
)
|
| 1124 |
+
self.game.katrain.log(f"[RankStrategy] Exponent term: {exponent_term:.4f}", OUTPUT_DEBUG)
|
| 1125 |
+
|
| 1126 |
+
modified_calib_avemodrank = (
|
| 1127 |
+
0.3931
|
| 1128 |
+
+ 0.6559
|
| 1129 |
+
* norm_leg_moves
|
| 1130 |
+
* math.exp(-1 * exponent_term ** 2)
|
| 1131 |
+
- 0.01093 * self.settings["kyu_rank"]
|
| 1132 |
+
) * orig_calib_avemodrank
|
| 1133 |
+
|
| 1134 |
+
self.game.katrain.log(f"[RankStrategy] Modified calibrated average mod rank: {modified_calib_avemodrank:.4f}", OUTPUT_DEBUG)
|
| 1135 |
+
|
| 1136 |
+
denominator = 1.31165 * (modified_calib_avemodrank + 1) - 0.082653
|
| 1137 |
+
self.game.katrain.log(f"[RankStrategy] Denominator: {denominator:.4f}", OUTPUT_DEBUG)
|
| 1138 |
+
|
| 1139 |
+
n_moves = board_squares * norm_leg_moves / denominator
|
| 1140 |
+
n_moves = max(1, round(n_moves))
|
| 1141 |
+
|
| 1142 |
+
self.game.katrain.log(f"[RankStrategy] Calculated n_moves: {n_moves}", OUTPUT_DEBUG)
|
| 1143 |
+
|
| 1144 |
+
return n_moves
|
| 1145 |
+
|
| 1146 |
+
def should_play_top_move(self, policy_moves, top_5_pass, override=0.0, overridetwo=1.0):
|
| 1147 |
+
"""Special override logic for rank-based"""
|
| 1148 |
+
self.game.katrain.log(f"[RankStrategy] Calculating special override thresholds based on rank", OUTPUT_DEBUG)
|
| 1149 |
+
|
| 1150 |
+
size = self.game.board_size
|
| 1151 |
+
board_squares = size[0] * size[1]
|
| 1152 |
+
legal_policy_moves = [(pol, mv) for pol, mv in policy_moves if not mv.is_pass and pol > 0]
|
| 1153 |
+
|
| 1154 |
+
# Parameters for calculating the overrides
|
| 1155 |
+
self.game.katrain.log(f"[RankStrategy] Board squares: {board_squares}", OUTPUT_DEBUG)
|
| 1156 |
+
self.game.katrain.log(f"[RankStrategy] Legal non-pass moves: {len(legal_policy_moves)}", OUTPUT_DEBUG)
|
| 1157 |
+
self.game.katrain.log(f"[RankStrategy] Kyu rank: {self.settings['kyu_rank']}", OUTPUT_DEBUG)
|
| 1158 |
+
|
| 1159 |
+
# Calibrated override based on board filling
|
| 1160 |
+
ratio = (board_squares - len(legal_policy_moves)) / board_squares
|
| 1161 |
+
override = 0.8 * (1 - 0.5 * ratio)
|
| 1162 |
+
self.game.katrain.log(f"[RankStrategy] Calculated override: {override:.2%} (from board filling ratio {ratio:.2f})", OUTPUT_DEBUG)
|
| 1163 |
+
|
| 1164 |
+
overridetwo = 0.85 + max(0, 0.02 * (self.settings["kyu_rank"] - 8))
|
| 1165 |
+
self.game.katrain.log(f"[RankStrategy] Calculated overridetwo: {overridetwo:.2%} (from kyu rank adjustment)", OUTPUT_DEBUG)
|
| 1166 |
+
|
| 1167 |
+
# Call the parent class method with calculated overrides
|
| 1168 |
+
return super().should_play_top_move(policy_moves, top_5_pass, override, overridetwo)
|
| 1169 |
+
|
| 1170 |
+
def handle_endgame(self, legal_policy_moves, policy_grid, size):
|
| 1171 |
+
return None, "", None, False
|
| 1172 |
+
|
| 1173 |
+
@register_strategy(AI_INFLUENCE)
|
| 1174 |
+
class InfluenceStrategy(PickBasedStrategy):
|
| 1175 |
+
"""Influence strategy - weights moves based on influence (distance from edge)"""
|
| 1176 |
+
|
| 1177 |
+
def generate_weighted_coords(self, legal_policy_moves, policy_grid, size):
|
| 1178 |
+
"""Generate influence-based weights"""
|
| 1179 |
+
self.game.katrain.log(f"[InfluenceStrategy] Generating influence-based weights", OUTPUT_DEBUG)
|
| 1180 |
+
self.game.katrain.log(f"[InfluenceStrategy] Settings: threshold={self.settings['threshold']}, line_weight={self.settings['line_weight']}", OUTPUT_DEBUG)
|
| 1181 |
+
weighted_coords, ai_thoughts = generate_influence_territory_weights(
|
| 1182 |
+
AI_INFLUENCE,
|
| 1183 |
+
self.settings,
|
| 1184 |
+
policy_grid,
|
| 1185 |
+
size
|
| 1186 |
+
)
|
| 1187 |
+
self.game.katrain.log(f"[InfluenceStrategy] Generated {len(weighted_coords)} weighted coordinates", OUTPUT_DEBUG)
|
| 1188 |
+
if weighted_coords:
|
| 1189 |
+
top5 = heapq.nlargest(5, weighted_coords, key=lambda t: t[0] * t[1])
|
| 1190 |
+
self.game.katrain.log(f"[InfluenceStrategy] Top 5 weighted coordinates (by policy*weight):", OUTPUT_DEBUG)
|
| 1191 |
+
for i, (pol, wt, x, y) in enumerate(top5):
|
| 1192 |
+
self.game.katrain.log(f"[InfluenceStrategy] #{i+1}: ({x},{y}) - policy={pol:.2%}, weight={wt}, combined={pol*wt:.2%}", OUTPUT_DEBUG)
|
| 1193 |
+
return weighted_coords, ai_thoughts
|
| 1194 |
+
|
| 1195 |
+
@register_strategy(AI_TERRITORY)
|
| 1196 |
+
class TerritoryStrategy(PickBasedStrategy):
|
| 1197 |
+
"""Territory strategy - weights moves based on territory (distance from center)"""
|
| 1198 |
+
|
| 1199 |
+
def generate_weighted_coords(self, legal_policy_moves, policy_grid, size):
|
| 1200 |
+
"""Generate territory-based weights"""
|
| 1201 |
+
self.game.katrain.log(f"[TerritoryStrategy] Generating territory-based weights", OUTPUT_DEBUG)
|
| 1202 |
+
self.game.katrain.log(f"[TerritoryStrategy] Settings: threshold={self.settings['threshold']}, line_weight={self.settings['line_weight']}", OUTPUT_DEBUG)
|
| 1203 |
+
weighted_coords, ai_thoughts = generate_influence_territory_weights(
|
| 1204 |
+
AI_TERRITORY,
|
| 1205 |
+
self.settings,
|
| 1206 |
+
policy_grid,
|
| 1207 |
+
size
|
| 1208 |
+
)
|
| 1209 |
+
self.game.katrain.log(f"[TerritoryStrategy] Generated {len(weighted_coords)} weighted coordinates", OUTPUT_DEBUG)
|
| 1210 |
+
if weighted_coords:
|
| 1211 |
+
top5 = heapq.nlargest(5, weighted_coords, key=lambda t: t[0] * t[1])
|
| 1212 |
+
self.game.katrain.log(f"[TerritoryStrategy] Top 5 weighted coordinates (by policy*weight):", OUTPUT_DEBUG)
|
| 1213 |
+
for i, (pol, wt, x, y) in enumerate(top5):
|
| 1214 |
+
self.game.katrain.log(f"[TerritoryStrategy] #{i+1}: ({x},{y}) - policy={pol:.2%}, weight={wt}, combined={pol*wt:.2%}", OUTPUT_DEBUG)
|
| 1215 |
+
return weighted_coords, ai_thoughts
|
| 1216 |
+
|
| 1217 |
+
@register_strategy(AI_LOCAL)
|
| 1218 |
+
class LocalStrategy(PickBasedStrategy):
|
| 1219 |
+
"""Local strategy - weights moves based on proximity to the last move"""
|
| 1220 |
+
|
| 1221 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 1222 |
+
# Handle the case where there's no previous move
|
| 1223 |
+
if not (self.cn.move and self.cn.move.coords):
|
| 1224 |
+
self.game.katrain.log(f"[LocalStrategy] No previous move with valid coordinates found, falling back to WeightedStrategy", OUTPUT_DEBUG)
|
| 1225 |
+
self.game.katrain.log(f"[LocalStrategy] Using default weighted settings: pick_override=0.9, weaken_fac=1, lower_bound=0.02", OUTPUT_DEBUG)
|
| 1226 |
+
return WeightedStrategy(self.game, {
|
| 1227 |
+
"pick_override": 0.9,
|
| 1228 |
+
"weaken_fac": 1,
|
| 1229 |
+
"lower_bound": 0.02
|
| 1230 |
+
}).generate_move()
|
| 1231 |
+
|
| 1232 |
+
return super().generate_move()
|
| 1233 |
+
|
| 1234 |
+
def generate_weighted_coords(self, legal_policy_moves, policy_grid, size):
|
| 1235 |
+
"""Generate local-based weights"""
|
| 1236 |
+
self.game.katrain.log(f"[LocalStrategy] Generating local-based weights around previous move", OUTPUT_DEBUG)
|
| 1237 |
+
self.game.katrain.log(f"[LocalStrategy] Previous move: {self.cn.move.gtp()}", OUTPUT_DEBUG)
|
| 1238 |
+
self.game.katrain.log(f"[LocalStrategy] Variance setting: {self.settings['stddev']}", OUTPUT_DEBUG)
|
| 1239 |
+
weighted_coords, ai_thoughts = generate_local_tenuki_weights(
|
| 1240 |
+
AI_LOCAL,
|
| 1241 |
+
self.settings,
|
| 1242 |
+
policy_grid,
|
| 1243 |
+
self.cn,
|
| 1244 |
+
size
|
| 1245 |
+
)
|
| 1246 |
+
self.game.katrain.log(f"[LocalStrategy] Generated {len(weighted_coords)} weighted coordinates", OUTPUT_DEBUG)
|
| 1247 |
+
if weighted_coords:
|
| 1248 |
+
top5 = heapq.nlargest(5, weighted_coords, key=lambda t: t[0] * t[1])
|
| 1249 |
+
self.game.katrain.log(f"[LocalStrategy] Top 5 weighted coordinates (by policy*weight):", OUTPUT_DEBUG)
|
| 1250 |
+
for i, (pol, wt, x, y) in enumerate(top5):
|
| 1251 |
+
self.game.katrain.log(f"[LocalStrategy] #{i+1}: ({x},{y}) - policy={pol:.2%}, weight={wt}, combined={pol*wt:.2%}", OUTPUT_DEBUG)
|
| 1252 |
+
return weighted_coords, ai_thoughts
|
| 1253 |
+
|
| 1254 |
+
@register_strategy(AI_TENUKI)
|
| 1255 |
+
class TenukiStrategy(PickBasedStrategy):
|
| 1256 |
+
"""Tenuki strategy - weights moves based on distance from the last move"""
|
| 1257 |
+
|
| 1258 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 1259 |
+
# Handle the case where there's no previous move
|
| 1260 |
+
if not (self.cn.move and self.cn.move.coords):
|
| 1261 |
+
self.game.katrain.log(f"[TenukiStrategy] No previous move with valid coordinates found, falling back to WeightedStrategy", OUTPUT_DEBUG)
|
| 1262 |
+
self.game.katrain.log(f"[TenukiStrategy] Using default weighted settings: pick_override=0.9, weaken_fac=1, lower_bound=0.02", OUTPUT_DEBUG)
|
| 1263 |
+
return WeightedStrategy(self.game, {
|
| 1264 |
+
"pick_override": 0.9,
|
| 1265 |
+
"weaken_fac": 1,
|
| 1266 |
+
"lower_bound": 0.02
|
| 1267 |
+
}).generate_move()
|
| 1268 |
+
|
| 1269 |
+
return super().generate_move()
|
| 1270 |
+
|
| 1271 |
+
def generate_weighted_coords(self, legal_policy_moves, policy_grid, size):
|
| 1272 |
+
"""Generate tenuki-based weights"""
|
| 1273 |
+
self.game.katrain.log(f"[TenukiStrategy] Generating tenuki-based weights (far from previous move)", OUTPUT_DEBUG)
|
| 1274 |
+
self.game.katrain.log(f"[TenukiStrategy] Previous move: {self.cn.move.gtp()}", OUTPUT_DEBUG)
|
| 1275 |
+
self.game.katrain.log(f"[TenukiStrategy] Variance setting: {self.settings['stddev']}", OUTPUT_DEBUG)
|
| 1276 |
+
weighted_coords, ai_thoughts = generate_local_tenuki_weights(
|
| 1277 |
+
AI_TENUKI,
|
| 1278 |
+
self.settings,
|
| 1279 |
+
policy_grid,
|
| 1280 |
+
self.cn,
|
| 1281 |
+
size
|
| 1282 |
+
)
|
| 1283 |
+
self.game.katrain.log(f"[TenukiStrategy] Generated {len(weighted_coords)} weighted coordinates", OUTPUT_DEBUG)
|
| 1284 |
+
if weighted_coords:
|
| 1285 |
+
top5 = heapq.nlargest(5, weighted_coords, key=lambda t: t[0] * t[1])
|
| 1286 |
+
self.game.katrain.log(f"[TenukiStrategy] Top 5 weighted coordinates (by policy*weight):", OUTPUT_DEBUG)
|
| 1287 |
+
for i, (pol, wt, x, y) in enumerate(top5):
|
| 1288 |
+
self.game.katrain.log(f"[TenukiStrategy] #{i+1}: ({x},{y}) - policy={pol:.2%}, weight={wt}, combined={pol*wt:.2%}", OUTPUT_DEBUG)
|
| 1289 |
+
return weighted_coords, ai_thoughts
|
| 1290 |
+
|
| 1291 |
+
@register_strategy(AI_HUMAN)
|
| 1292 |
+
@register_strategy(AI_PRO)
|
| 1293 |
+
class HumanStyleStrategy(AIStrategy):
|
| 1294 |
+
"""Strategy that imitates human play at various skill levels"""
|
| 1295 |
+
|
| 1296 |
+
def __init__(self, game: Game, ai_settings: Dict):
|
| 1297 |
+
super().__init__(game, ai_settings)
|
| 1298 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Initializing HumanStyleStrategy", OUTPUT_DEBUG)
|
| 1299 |
+
self.game.katrain.log(f"[HumanStyleStrategy] AI settings: {ai_settings}", OUTPUT_DEBUG)
|
| 1300 |
+
|
| 1301 |
+
def generate_move(self) -> Tuple[Move, str]:
|
| 1302 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Starting move generation", OUTPUT_DEBUG)
|
| 1303 |
+
|
| 1304 |
+
if "human_kyu_rank" in self.settings:
|
| 1305 |
+
human_kyu_rank = round(self.settings["human_kyu_rank"])
|
| 1306 |
+
human_style = "rank" if self.settings["modern_style"] else "preaz"
|
| 1307 |
+
|
| 1308 |
+
if human_kyu_rank <= 0: # dan ranks
|
| 1309 |
+
rank_text = f"{1-human_kyu_rank}d"
|
| 1310 |
+
else: # kyu ranks
|
| 1311 |
+
rank_text = f"{human_kyu_rank}k"
|
| 1312 |
+
|
| 1313 |
+
human_profile = f"{human_style}_{rank_text}"
|
| 1314 |
+
else:
|
| 1315 |
+
pro_year = round(self.settings["pro_year"])
|
| 1316 |
+
human_profile = f"proyear_{pro_year}"
|
| 1317 |
+
|
| 1318 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Human profile string: {human_profile}", OUTPUT_DEBUG)
|
| 1319 |
+
|
| 1320 |
+
# Define override settings (separate from includePolicy)
|
| 1321 |
+
override_settings = {
|
| 1322 |
+
"humanSLProfile": human_profile,
|
| 1323 |
+
"ignorePreRootHistory": False,
|
| 1324 |
+
}
|
| 1325 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Override settings for engine: {override_settings}", OUTPUT_DEBUG)
|
| 1326 |
+
|
| 1327 |
+
# Request analysis from engine - note includePolicy is a direct parameter
|
| 1328 |
+
analysis = None
|
| 1329 |
+
|
| 1330 |
+
def set_analysis(a, partial_result):
|
| 1331 |
+
nonlocal analysis
|
| 1332 |
+
if not partial_result:
|
| 1333 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Full analysis results received", OUTPUT_DEBUG)
|
| 1334 |
+
analysis = a
|
| 1335 |
+
# Log some analysis stats for debugging
|
| 1336 |
+
if a:
|
| 1337 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Analysis contains humanPolicy: {'humanPolicy' in a}", OUTPUT_DEBUG)
|
| 1338 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Analysis contains moveInfos: {len(a.get('moveInfos', []))} moves", OUTPUT_DEBUG)
|
| 1339 |
+
if 'humanPolicy' in a:
|
| 1340 |
+
policy_sum = sum(a['humanPolicy'])
|
| 1341 |
+
policy_max = max(a['humanPolicy'])
|
| 1342 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Human policy sum: {policy_sum}, max: {policy_max}", OUTPUT_DEBUG)
|
| 1343 |
+
else:
|
| 1344 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Received partial analysis results - ignoring", OUTPUT_DEBUG)
|
| 1345 |
+
|
| 1346 |
+
def set_error(a):
|
| 1347 |
+
nonlocal error
|
| 1348 |
+
error = True
|
| 1349 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Error in human analysis query: {a}", OUTPUT_ERROR)
|
| 1350 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Will attempt to fall back to policy move", OUTPUT_DEBUG)
|
| 1351 |
+
|
| 1352 |
+
error = False
|
| 1353 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Getting engine for player", OUTPUT_DEBUG)
|
| 1354 |
+
engine = self.game.engines[self.cn.player]
|
| 1355 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Using engine for player {self.cn.player}", OUTPUT_DEBUG)
|
| 1356 |
+
|
| 1357 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Requesting analysis with human profile settings", OUTPUT_DEBUG)
|
| 1358 |
+
engine.request_analysis(
|
| 1359 |
+
self.cn,
|
| 1360 |
+
callback=set_analysis,
|
| 1361 |
+
error_callback=set_error,
|
| 1362 |
+
priority=PRIORITY_EXTRA_AI_QUERY,
|
| 1363 |
+
include_policy=True,
|
| 1364 |
+
extra_settings=override_settings
|
| 1365 |
+
)
|
| 1366 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Analysis request sent, waiting for results", OUTPUT_DEBUG)
|
| 1367 |
+
|
| 1368 |
+
# Wait for analysis to complete
|
| 1369 |
+
wait_count = 0
|
| 1370 |
+
while not (error or analysis):
|
| 1371 |
+
import time
|
| 1372 |
+
time.sleep(0.01)
|
| 1373 |
+
wait_count += 1
|
| 1374 |
+
if wait_count % 100 == 0: # Log every 1 second
|
| 1375 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Still waiting for analysis results ({wait_count/100:.1f}s)", OUTPUT_DEBUG)
|
| 1376 |
+
engine.check_alive(exception_if_dead=True)
|
| 1377 |
+
|
| 1378 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Finished waiting for analysis, error={error}, analysis received={analysis is not None}", OUTPUT_DEBUG)
|
| 1379 |
+
|
| 1380 |
+
if error or not analysis:
|
| 1381 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Analysis failed or returned empty", OUTPUT_DEBUG)
|
| 1382 |
+
# Fall back to policy
|
| 1383 |
+
policy_move = self.cn.policy_ranking[0][1] if self.cn.policy_ranking else None
|
| 1384 |
+
if policy_move:
|
| 1385 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Falling back to top policy move: {policy_move.gtp()}", OUTPUT_DEBUG)
|
| 1386 |
+
return policy_move, "Falling back to policy move due to error in human analysis."
|
| 1387 |
+
else:
|
| 1388 |
+
self.game.katrain.log(f"[HumanStyleStrategy] No policy moves available for fallback - will return pass", OUTPUT_DEBUG)
|
| 1389 |
+
return Move(None, player=self.cn.next_player), "No valid moves found."
|
| 1390 |
+
|
| 1391 |
+
# Check if human policy is available
|
| 1392 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Processing analysis results", OUTPUT_DEBUG)
|
| 1393 |
+
if "humanPolicy" not in analysis:
|
| 1394 |
+
error_msg = "humanPolicy not found in analysis—have you downloaded and configured your human model yet?"
|
| 1395 |
+
raise Exception(error_msg)
|
| 1396 |
+
|
| 1397 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Human policy found in analysis", OUTPUT_DEBUG)
|
| 1398 |
+
board_size = self.game.board_size
|
| 1399 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Board size: {board_size}", OUTPUT_DEBUG)
|
| 1400 |
+
human_policy = analysis["humanPolicy"]
|
| 1401 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Human policy length: {len(human_policy)}", OUTPUT_DEBUG)
|
| 1402 |
+
if len(human_policy) != 362:
|
| 1403 |
+
self.game.katrain.log(f"[HumanStyleStrategy] WARNING: Human policy length {len(human_policy)} != 362", OUTPUT_ERROR)
|
| 1404 |
+
|
| 1405 |
+
# Create a list of moves with their human policy weights
|
| 1406 |
+
moves = []
|
| 1407 |
+
for x in range(board_size[0]):
|
| 1408 |
+
for y in range(board_size[1]):
|
| 1409 |
+
idx = (board_size[1] - y - 1) * board_size[0] + x
|
| 1410 |
+
if idx < len(human_policy) and human_policy[idx] > 0:
|
| 1411 |
+
moves.append((Move((x, y), player=self.cn.next_player), human_policy[idx]))
|
| 1412 |
+
|
| 1413 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Generated {len(moves)} candidate moves from human policy", OUTPUT_DEBUG)
|
| 1414 |
+
|
| 1415 |
+
# Add pass move if it has positive probability
|
| 1416 |
+
if len(human_policy) > board_size[0] * board_size[1] and human_policy[-1] > 0:
|
| 1417 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Adding pass move with probability {human_policy[-1]}", OUTPUT_DEBUG)
|
| 1418 |
+
moves.append((Move(None, player=self.cn.next_player), human_policy[-1]))
|
| 1419 |
+
|
| 1420 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Performing weighted selection from {len(moves)} moves", OUTPUT_DEBUG)
|
| 1421 |
+
top_moves = sorted(moves, key=lambda x: -x[1])
|
| 1422 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Top 5 moves by probability:", OUTPUT_DEBUG)
|
| 1423 |
+
|
| 1424 |
+
# Create a formatted string of top 5 moves for ai_thoughts
|
| 1425 |
+
top_moves_str = "\n".join([f"#{i+1}: {move.gtp()} - {prob:.1%}" for i, (move, prob) in enumerate(top_moves[:5])])
|
| 1426 |
+
|
| 1427 |
+
self.game.katrain.log(f"[HumanStyleStrategy]\n{top_moves_str}", OUTPUT_DEBUG)
|
| 1428 |
+
|
| 1429 |
+
selected = weighted_selection_without_replacement(moves, 1)[0]
|
| 1430 |
+
move = selected[0]
|
| 1431 |
+
prob = selected[1]
|
| 1432 |
+
|
| 1433 |
+
# Find the rank of the selected move
|
| 1434 |
+
selected_rank = next((i+1 for i, (m, _) in enumerate(top_moves) if m.gtp() == move.gtp()), "ERROR: move not found in ranking")
|
| 1435 |
+
|
| 1436 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Selected move {move.gtp()} with probability {prob:.4f}", OUTPUT_DEBUG)
|
| 1437 |
+
ai_thoughts = f"\n{top_moves_str}\n\nPlayed move {move.gtp()} ({prob:.1%}) as the #{selected_rank} top move."
|
| 1438 |
+
self.game.katrain.log(f"[HumanStyleStrategy] Final decision: {move.gtp()}", OUTPUT_DEBUG)
|
| 1439 |
+
return move, ai_thoughts
|
| 1440 |
+
|
| 1441 |
+
def generate_ai_move(game: Game, ai_mode: str, ai_settings: Dict) -> Tuple[Move, GameNode]:
|
| 1442 |
+
"""Generate a move using the selected AI strategy"""
|
| 1443 |
+
game.katrain.log(f"Generate AI move called with mode: {ai_mode}", OUTPUT_DEBUG)
|
| 1444 |
+
|
| 1445 |
+
# Create the appropriate strategy based on mode
|
| 1446 |
+
|
| 1447 |
+
strategy = STRATEGY_REGISTRY[ai_mode](game, ai_settings)
|
| 1448 |
+
|
| 1449 |
+
# Generate the move
|
| 1450 |
+
game.katrain.log(f"Generating move using {strategy.__class__.__name__}", OUTPUT_DEBUG)
|
| 1451 |
+
move, ai_thoughts = strategy.generate_move()
|
| 1452 |
+
|
| 1453 |
+
# Play the move and return
|
| 1454 |
+
game.katrain.log(f"Playing move {move.gtp()} and creating game node", OUTPUT_DEBUG)
|
| 1455 |
+
played_node = game.play(move)
|
| 1456 |
+
game.katrain.log(f"AI thoughts: {ai_thoughts}", OUTPUT_DEBUG)
|
| 1457 |
+
played_node.ai_thoughts = ai_thoughts
|
| 1458 |
+
|
| 1459 |
+
game.katrain.log(f"Move generation complete: {move.gtp()}", OUTPUT_DEBUG)
|
| 1460 |
+
return move, played_node
|
katrain/core/base_katrain.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from kivy import Config
|
| 6 |
+
from kivy.storage.jsonstore import JsonStore
|
| 7 |
+
|
| 8 |
+
from katrain.core.ai import ai_rank_estimation
|
| 9 |
+
from katrain.core.constants import (
|
| 10 |
+
PLAYER_HUMAN,
|
| 11 |
+
PLAYER_AI,
|
| 12 |
+
PLAYING_NORMAL,
|
| 13 |
+
PLAYING_TEACHING,
|
| 14 |
+
OUTPUT_INFO,
|
| 15 |
+
OUTPUT_ERROR,
|
| 16 |
+
OUTPUT_DEBUG,
|
| 17 |
+
AI_DEFAULT,
|
| 18 |
+
CONFIG_MIN_VERSION,
|
| 19 |
+
DATA_FOLDER,
|
| 20 |
+
)
|
| 21 |
+
from katrain.core.utils import find_package_resource
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Player:
|
| 25 |
+
def __init__(self, player="B", player_type=PLAYER_HUMAN, player_subtype=PLAYING_NORMAL, periods_used=0):
|
| 26 |
+
self.player = player
|
| 27 |
+
self.sgf_rank = None
|
| 28 |
+
self.calculated_rank = None
|
| 29 |
+
self.name = ""
|
| 30 |
+
self.update(player_type, player_subtype)
|
| 31 |
+
self.periods_used = periods_used
|
| 32 |
+
|
| 33 |
+
def update(self, player_type=PLAYER_HUMAN, player_subtype=PLAYING_NORMAL):
|
| 34 |
+
self.player_type = player_type
|
| 35 |
+
self.player_subtype = player_subtype
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def ai(self):
|
| 39 |
+
return self.player_type == PLAYER_AI
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def human(self):
|
| 43 |
+
return self.player_type == PLAYER_HUMAN
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def being_taught(self):
|
| 47 |
+
return self.player_type == PLAYER_HUMAN and self.player_subtype == PLAYING_TEACHING
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def strategy(self):
|
| 51 |
+
return self.player_subtype if self.ai else AI_DEFAULT
|
| 52 |
+
|
| 53 |
+
def __str__(self):
|
| 54 |
+
return f"{self.player_type} ({self.player_subtype})"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def parse_version(s):
|
| 58 |
+
parts = [int(p) for p in s.split(".")]
|
| 59 |
+
while len(parts) < 3:
|
| 60 |
+
parts.append(0)
|
| 61 |
+
return parts
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class KaTrainBase:
|
| 65 |
+
USER_CONFIG_FILE = os.path.expanduser(os.path.join(DATA_FOLDER, "config.json"))
|
| 66 |
+
PACKAGE_CONFIG_FILE = "katrain/config.json"
|
| 67 |
+
|
| 68 |
+
"""Settings, logging, and players functionality, so other classes like bots who need a katrain instance can be used without a GUI"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, force_package_config=False, debug_level=None, **kwargs):
|
| 71 |
+
self.debug_level = debug_level or 0
|
| 72 |
+
self.game = None
|
| 73 |
+
|
| 74 |
+
self.logger = lambda message, level=OUTPUT_INFO: self.log(message, level)
|
| 75 |
+
self.config_file = self._load_config(force_package_config=force_package_config)
|
| 76 |
+
self.debug_level = self.config("general/debug_level", OUTPUT_INFO) if debug_level is None else debug_level
|
| 77 |
+
|
| 78 |
+
Config.set("kivy", "log_level", "warning")
|
| 79 |
+
if self.debug_level >= OUTPUT_DEBUG:
|
| 80 |
+
Config.set("kivy", "log_enable", 1)
|
| 81 |
+
Config.set("kivy", "log_level", "debug")
|
| 82 |
+
# if self.debug_level >= OUTPUT_EXTRA_DEBUG:
|
| 83 |
+
# Config.set("kivy", "log_level", "trace")
|
| 84 |
+
self.players_info = {"B": Player("B"), "W": Player("W")}
|
| 85 |
+
self.reset_players()
|
| 86 |
+
|
| 87 |
+
def log(self, message, level=OUTPUT_INFO):
|
| 88 |
+
if level == OUTPUT_ERROR:
|
| 89 |
+
print(f"ERROR: {message}")
|
| 90 |
+
elif self.debug_level >= level:
|
| 91 |
+
print(message)
|
| 92 |
+
|
| 93 |
+
def _load_config(self, force_package_config):
|
| 94 |
+
if len(sys.argv) > 1 and sys.argv[1].endswith("config.json"):
|
| 95 |
+
config_file = os.path.abspath(sys.argv[1])
|
| 96 |
+
self.log(f"Using command line config file {config_file}", OUTPUT_INFO)
|
| 97 |
+
else:
|
| 98 |
+
user_config_file = find_package_resource(self.USER_CONFIG_FILE)
|
| 99 |
+
package_config_file = find_package_resource(self.PACKAGE_CONFIG_FILE)
|
| 100 |
+
if force_package_config:
|
| 101 |
+
config_file = package_config_file
|
| 102 |
+
else:
|
| 103 |
+
try:
|
| 104 |
+
if not os.path.exists(user_config_file):
|
| 105 |
+
self.log("User config does not exist, creating it", OUTPUT_DEBUG)
|
| 106 |
+
parent_dir = os.path.split(user_config_file)[0]
|
| 107 |
+
self.log(f"Creating parent directory if needed: {parent_dir}", OUTPUT_DEBUG)
|
| 108 |
+
os.makedirs(parent_dir, exist_ok=True)
|
| 109 |
+
|
| 110 |
+
self.log(f"Copying package config {package_config_file} to user config {user_config_file}", OUTPUT_DEBUG)
|
| 111 |
+
shutil.copyfile(package_config_file, user_config_file)
|
| 112 |
+
config_file = user_config_file
|
| 113 |
+
self.log(f"Copied package config to local file {config_file}", OUTPUT_INFO)
|
| 114 |
+
else: # user file exists
|
| 115 |
+
try:
|
| 116 |
+
version_str = JsonStore(user_config_file).get("general")["version"]
|
| 117 |
+
version = parse_version(version_str)
|
| 118 |
+
self.log(f"Parsed version: {version}", OUTPUT_DEBUG)
|
| 119 |
+
except Exception as e: # noqa E722 broken file etc
|
| 120 |
+
self.log(f"Failed to read version from user config: {e}", OUTPUT_DEBUG)
|
| 121 |
+
version_str = "0.0.0"
|
| 122 |
+
version = [0, 0, 0]
|
| 123 |
+
min_version = parse_version(CONFIG_MIN_VERSION)
|
| 124 |
+
if version < min_version:
|
| 125 |
+
backup = f"{user_config_file}.{version_str}.backup"
|
| 126 |
+
shutil.copyfile(user_config_file, backup)
|
| 127 |
+
shutil.copyfile(package_config_file, user_config_file)
|
| 128 |
+
self.log(
|
| 129 |
+
f"Copied package config file to {user_config_file} as user file is outdated or broken ({version}<{min_version}). Old version stored as {backup}",
|
| 130 |
+
OUTPUT_INFO,
|
| 131 |
+
)
|
| 132 |
+
config_file = user_config_file
|
| 133 |
+
self.log(f"Using user config file {config_file}", OUTPUT_INFO)
|
| 134 |
+
except Exception as e:
|
| 135 |
+
config_file = package_config_file
|
| 136 |
+
self.log(
|
| 137 |
+
f"Using package config file {config_file} (exception {e} occurred when finding or creating user config)",
|
| 138 |
+
OUTPUT_INFO,
|
| 139 |
+
)
|
| 140 |
+
try:
|
| 141 |
+
self._config_store = JsonStore(config_file, indent=4)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
self.log(f"Failed to load config {config_file}: {e}", OUTPUT_ERROR)
|
| 144 |
+
sys.exit(1)
|
| 145 |
+
self._config = dict(self._config_store)
|
| 146 |
+
return config_file
|
| 147 |
+
|
| 148 |
+
def save_config(self, key=None):
|
| 149 |
+
if key is None:
|
| 150 |
+
for k, v in self._config.items():
|
| 151 |
+
self._config_store.put(k, **v)
|
| 152 |
+
else:
|
| 153 |
+
self._config_store.put(key, **self._config[key])
|
| 154 |
+
|
| 155 |
+
def config(self, setting, default=None):
|
| 156 |
+
try:
|
| 157 |
+
if "/" in setting:
|
| 158 |
+
cat, key = setting.split("/")
|
| 159 |
+
return self._config.get(cat, {}).get(key, default)
|
| 160 |
+
else:
|
| 161 |
+
return self._config.get(setting, default)
|
| 162 |
+
except KeyError:
|
| 163 |
+
self.log(f"Missing configuration option {setting}", OUTPUT_ERROR)
|
| 164 |
+
|
| 165 |
+
def update_player(self, bw, **kwargs):
|
| 166 |
+
self.players_info[bw].update(**kwargs)
|
| 167 |
+
self.update_calculated_ranks()
|
| 168 |
+
|
| 169 |
+
def update_calculated_ranks(self):
|
| 170 |
+
for bw, player_info in self.players_info.items():
|
| 171 |
+
if player_info.player_type == PLAYER_AI:
|
| 172 |
+
settings = self.config(f"ai/{player_info.strategy}")
|
| 173 |
+
player_info.calculated_rank = ai_rank_estimation(player_info.player_subtype, settings)
|
| 174 |
+
else:
|
| 175 |
+
player_info.calculated_rank = None
|
| 176 |
+
|
| 177 |
+
def reset_players(self):
|
| 178 |
+
self.update_player("B")
|
| 179 |
+
self.update_player("W")
|
| 180 |
+
for v in self.players_info.values():
|
| 181 |
+
v.periods_used = 0
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def last_player_info(self) -> Player:
|
| 185 |
+
return self.players_info[self.game.current_node.player]
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def next_player_info(self) -> Player:
|
| 189 |
+
return self.players_info[self.game.current_node.next_player]
|
katrain/core/constants.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_NAME = "KaTrain"
|
| 2 |
+
VERSION = "1.17.1"
|
| 3 |
+
HOMEPAGE = "https://github.com/sanderland/katrain"
|
| 4 |
+
CONFIG_MIN_VERSION = "1.17.0" # keep config files from this version
|
| 5 |
+
ANALYSIS_FORMAT_VERSION = "1.0"
|
| 6 |
+
DATA_FOLDER = "~/.katrain"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
OUTPUT_ERROR = -1
|
| 10 |
+
OUTPUT_KATAGO_STDERR = -0.5
|
| 11 |
+
OUTPUT_INFO = 0
|
| 12 |
+
OUTPUT_DEBUG = 1
|
| 13 |
+
OUTPUT_EXTRA_DEBUG = 2
|
| 14 |
+
|
| 15 |
+
KATAGO_EXCEPTION = "KATAGO-INTERNAL-ERROR"
|
| 16 |
+
|
| 17 |
+
STATUS_ANALYSIS = 1.0 # same priority for analysis/info
|
| 18 |
+
STATUS_INFO = 1.1
|
| 19 |
+
STATUS_TEACHING = 2.0
|
| 20 |
+
STATUS_ERROR = 1000.0
|
| 21 |
+
|
| 22 |
+
ADDITIONAL_MOVE_ORDER = 999
|
| 23 |
+
|
| 24 |
+
PRIORITY_GAME_ANALYSIS = -100
|
| 25 |
+
PRIORITY_SWEEP = -10 # sweep is live, but slow, so deprioritize
|
| 26 |
+
PRIORITY_ALTERNATIVES = 100 # extra analysis, live interaction
|
| 27 |
+
PRIORITY_EQUALIZE = 100
|
| 28 |
+
PRIORITY_EXTRA_ANALYSIS = 100
|
| 29 |
+
PRIORITY_DEFAULT = 1000 # new move, high pri
|
| 30 |
+
PRIORITY_EXTRA_AI_QUERY = 10_000
|
| 31 |
+
|
| 32 |
+
PLAYER_HUMAN, PLAYER_AI = "player:human", "player:ai"
|
| 33 |
+
PLAYER_TYPES = [PLAYER_HUMAN, PLAYER_AI]
|
| 34 |
+
|
| 35 |
+
PLAYING_NORMAL, PLAYING_TEACHING = "game:normal", "game:teach"
|
| 36 |
+
GAME_TYPES = [PLAYING_NORMAL, PLAYING_TEACHING]
|
| 37 |
+
|
| 38 |
+
MODE_PLAY, MODE_ANALYZE = "play", "analyze"
|
| 39 |
+
|
| 40 |
+
AI_DEFAULT = "ai:default"
|
| 41 |
+
AI_HANDICAP = "ai:handicap"
|
| 42 |
+
AI_SCORELOSS = "ai:scoreloss"
|
| 43 |
+
AI_WEIGHTED = "ai:p:weighted"
|
| 44 |
+
AI_JIGO = "ai:jigo"
|
| 45 |
+
AI_ANTIMIRROR = "ai:antimirror"
|
| 46 |
+
AI_POLICY = "ai:policy"
|
| 47 |
+
AI_PICK = "ai:p:pick"
|
| 48 |
+
AI_LOCAL = "ai:p:local"
|
| 49 |
+
AI_TENUKI = "ai:p:tenuki"
|
| 50 |
+
AI_INFLUENCE = "ai:p:influence"
|
| 51 |
+
AI_TERRITORY = "ai:p:territory"
|
| 52 |
+
AI_RANK = "ai:p:rank"
|
| 53 |
+
AI_SIMPLE_OWNERSHIP = "ai:simple"
|
| 54 |
+
AI_SETTLE_STONES = "ai:settle"
|
| 55 |
+
AI_HUMAN = "ai:human"
|
| 56 |
+
AI_PRO = "ai:pro"
|
| 57 |
+
|
| 58 |
+
AI_CONFIG_DEFAULT = AI_RANK
|
| 59 |
+
|
| 60 |
+
AI_STRATEGIES_ENGINE = [AI_DEFAULT, AI_HANDICAP, AI_SCORELOSS, AI_SIMPLE_OWNERSHIP, AI_JIGO, AI_ANTIMIRROR]
|
| 61 |
+
AI_STRATEGIES_PICK = [AI_PICK, AI_LOCAL, AI_TENUKI, AI_INFLUENCE, AI_TERRITORY, AI_RANK]
|
| 62 |
+
AI_STRATEGIES_POLICY = [AI_WEIGHTED, AI_POLICY] + AI_STRATEGIES_PICK
|
| 63 |
+
AI_STRATEGIES = AI_STRATEGIES_ENGINE + AI_STRATEGIES_POLICY + [AI_HUMAN, AI_PRO]
|
| 64 |
+
AI_STRATEGIES_RECOMMENDED_ORDER = [
|
| 65 |
+
AI_DEFAULT,
|
| 66 |
+
AI_HUMAN,
|
| 67 |
+
AI_PRO,
|
| 68 |
+
AI_RANK,
|
| 69 |
+
AI_HANDICAP,
|
| 70 |
+
AI_SIMPLE_OWNERSHIP,
|
| 71 |
+
AI_SCORELOSS,
|
| 72 |
+
AI_POLICY,
|
| 73 |
+
AI_WEIGHTED,
|
| 74 |
+
AI_JIGO,
|
| 75 |
+
AI_ANTIMIRROR,
|
| 76 |
+
AI_PICK,
|
| 77 |
+
AI_LOCAL,
|
| 78 |
+
AI_TENUKI,
|
| 79 |
+
AI_TERRITORY,
|
| 80 |
+
AI_INFLUENCE,
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
AI_STRENGTH = { # dan ranks, backup if model is missing. TODO: remove some?
|
| 84 |
+
AI_DEFAULT: 9,
|
| 85 |
+
AI_ANTIMIRROR: 9,
|
| 86 |
+
AI_POLICY: 5,
|
| 87 |
+
AI_JIGO: float("nan"),
|
| 88 |
+
AI_SCORELOSS: -4,
|
| 89 |
+
AI_WEIGHTED: -4,
|
| 90 |
+
AI_PICK: -7,
|
| 91 |
+
AI_LOCAL: -4,
|
| 92 |
+
AI_TENUKI: -7,
|
| 93 |
+
AI_INFLUENCE: -7,
|
| 94 |
+
AI_TERRITORY: -7,
|
| 95 |
+
AI_RANK: float("nan"),
|
| 96 |
+
AI_SIMPLE_OWNERSHIP: 2,
|
| 97 |
+
AI_SETTLE_STONES: 2,
|
| 98 |
+
AI_HUMAN: float("nan"),
|
| 99 |
+
AI_PRO: float("nan")
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
AI_OPTION_VALUES = {
|
| 103 |
+
"kyu_rank": [(k, f"{k}[strength:kyu]") for k in range(15, 0, -1)]
|
| 104 |
+
+ [(k, f"{1-k}[strength:dan]") for k in range(0, -3, -1)],
|
| 105 |
+
"strength": [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 1],
|
| 106 |
+
"opening_moves": range(0, 51),
|
| 107 |
+
"pick_override": [0, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 0.99, 1],
|
| 108 |
+
"lower_bound": [(v, f"{v:.2%}") for v in [0, 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05]],
|
| 109 |
+
"weaken_fac": [x / 20 for x in range(10, 3 * 20 + 1)],
|
| 110 |
+
"endgame": [x / 100 for x in range(10, 80, 5)],
|
| 111 |
+
"pick_frac": [x / 100 for x in range(0, 101, 5)],
|
| 112 |
+
"pick_n": range(0, 26),
|
| 113 |
+
"stddev": [x / 2 for x in range(21)],
|
| 114 |
+
"line_weight": range(0, 11),
|
| 115 |
+
"threshold": [2, 2.5, 3, 3.5, 4, 4.5],
|
| 116 |
+
"automatic": "bool",
|
| 117 |
+
"pda": [(x / 10, f"{'W' if x<0 else 'B'}+{abs(x/10):.1f}") for x in range(-30, 31)],
|
| 118 |
+
"max_points_lost": [x / 10 for x in range(51)],
|
| 119 |
+
"settled_weight": [x / 4 for x in range(0, 17)],
|
| 120 |
+
"opponent_fac": [x / 10 for x in range(-20, 11)],
|
| 121 |
+
"min_visits": range(1, 10),
|
| 122 |
+
"attach_penalty": [x / 10 for x in range(-10, 51)],
|
| 123 |
+
"tenuki_penalty": [x / 10 for x in range(-10, 51)],
|
| 124 |
+
"human_kyu_rank": [(k, f"{k}[strength:kyu]") for k in range(20, 0, -1)] +
|
| 125 |
+
[(k, f"{1-k}[strength:dan]") for k in range(0, -9,-1)],
|
| 126 |
+
"modern_style": "bool",
|
| 127 |
+
"pro_year": range(1800,2024),
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
AI_KEY_PROPERTIES = {
|
| 131 |
+
"kyu_rank",
|
| 132 |
+
"strength",
|
| 133 |
+
"weaken_fac",
|
| 134 |
+
"pick_frac",
|
| 135 |
+
"pick_n",
|
| 136 |
+
"automatic",
|
| 137 |
+
"max_points_lost",
|
| 138 |
+
"min_visits",
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
CALIBRATED_RANK_ELO = [
|
| 143 |
+
(-21.679482223451032, 18),
|
| 144 |
+
(42.60243194422105, 17),
|
| 145 |
+
(106.88434611189314, 16),
|
| 146 |
+
(171.16626027956522, 15),
|
| 147 |
+
(235.44817444723742, 14),
|
| 148 |
+
(299.7300886149095, 13),
|
| 149 |
+
(364.0120027825817, 12),
|
| 150 |
+
(428.2939169502538, 11),
|
| 151 |
+
(492.5758311179259, 10),
|
| 152 |
+
(556.8577452855981, 9),
|
| 153 |
+
(621.1396594532702, 8),
|
| 154 |
+
(685.4215736209424, 7),
|
| 155 |
+
(749.7034877886144, 6),
|
| 156 |
+
(813.9854019562865, 5),
|
| 157 |
+
(878.2673161239586, 4),
|
| 158 |
+
(942.5492302916308, 3),
|
| 159 |
+
(1006.8311444593029, 2),
|
| 160 |
+
(1071.113058626975, 1),
|
| 161 |
+
(1135.3949727946472, 0),
|
| 162 |
+
(1199.6768869623193, -1),
|
| 163 |
+
(1263.9588011299913, -2),
|
| 164 |
+
(1700, -4),
|
| 165 |
+
]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
AI_WEIGHTED_ELO = [
|
| 169 |
+
(0.5, 1591.5718897531551),
|
| 170 |
+
(1.0, 1269.9896556526198),
|
| 171 |
+
(1.25, 1042.25179764667),
|
| 172 |
+
(1.5, 848.9410084463602),
|
| 173 |
+
(1.75, 630.1483212024823),
|
| 174 |
+
(2, 575.3637091858013),
|
| 175 |
+
(2.5, 410.9747543504796),
|
| 176 |
+
(3.0, 219.8667371799533),
|
| 177 |
+
]
|
| 178 |
+
|
| 179 |
+
AI_SCORELOSS_ELO = [
|
| 180 |
+
(0.0, 539),
|
| 181 |
+
(0.05, 625),
|
| 182 |
+
(0.1, 859),
|
| 183 |
+
(0.2, 1035),
|
| 184 |
+
(0.3, 1201),
|
| 185 |
+
(0.4, 1299),
|
| 186 |
+
(0.5, 1346),
|
| 187 |
+
(0.75, 1374),
|
| 188 |
+
(1.0, 1386),
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
AI_LOCAL_ELO_GRID = [
|
| 193 |
+
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
|
| 194 |
+
[0, 5, 10, 15, 25, 50],
|
| 195 |
+
[
|
| 196 |
+
[-204.0, 791.0, 1154.0, 1372.0, 1402.0, 1473.0, 1700.0, 1700.0],
|
| 197 |
+
[174.0, 1094.0, 1191.0, 1384.0, 1435.0, 1522.0, 1700.0, 1700.0],
|
| 198 |
+
[619.0, 1155.0, 1323.0, 1390.0, 1450.0, 1558.0, 1700.0, 1700.0],
|
| 199 |
+
[975.0, 1289.0, 1332.0, 1401.0, 1461.0, 1575.0, 1700.0, 1700.0],
|
| 200 |
+
[1344.0, 1348.0, 1358.0, 1467.0, 1477.0, 1616.0, 1700.0, 1700.0],
|
| 201 |
+
[1425.0, 1474.0, 1489.0, 1524.0, 1571.0, 1700.0, 1700.0, 1700.0],
|
| 202 |
+
],
|
| 203 |
+
]
|
| 204 |
+
AI_TENUKI_ELO_GRID = [
|
| 205 |
+
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
|
| 206 |
+
[0, 5, 10, 15, 25, 50],
|
| 207 |
+
[
|
| 208 |
+
[47.0, 335.0, 530.0, 678.0, 830.0, 1070.0, 1376.0, 1700.0],
|
| 209 |
+
[99.0, 469.0, 546.0, 707.0, 855.0, 1090.0, 1413.0, 1700.0],
|
| 210 |
+
[327.0, 513.0, 605.0, 745.0, 875.0, 1110.0, 1424.0, 1700.0],
|
| 211 |
+
[429.0, 519.0, 620.0, 754.0, 900.0, 1130.0, 1435.0, 1700.0],
|
| 212 |
+
[492.0, 607.0, 682.0, 797.0, 1000.0, 1208.0, 1454.0, 1700.0],
|
| 213 |
+
[778.0, 830.0, 909.0, 949.0, 1169.0, 1461.0, 1483.0, 1700.0],
|
| 214 |
+
],
|
| 215 |
+
]
|
| 216 |
+
AI_TERRITORY_ELO_GRID = [
|
| 217 |
+
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
|
| 218 |
+
[0, 5, 10, 15, 25, 50],
|
| 219 |
+
[
|
| 220 |
+
[34.0, 383.0, 566.0, 748.0, 980.0, 1264.0, 1527.0, 1700.0],
|
| 221 |
+
[131.0, 450.0, 586.0, 826.0, 995.0, 1280.0, 1537.0, 1700.0],
|
| 222 |
+
[291.0, 517.0, 627.0, 850.0, 1010.0, 1310.0, 1547.0, 1700.0],
|
| 223 |
+
[454.0, 526.0, 696.0, 870.0, 1038.0, 1340.0, 1590.0, 1700.0],
|
| 224 |
+
[491.0, 603.0, 747.0, 890.0, 1050.0, 1390.0, 1635.0, 1700.0],
|
| 225 |
+
[718.0, 841.0, 1039.0, 1076.0, 1332.0, 1523.0, 1700.0, 1700.0],
|
| 226 |
+
],
|
| 227 |
+
]
|
| 228 |
+
AI_INFLUENCE_ELO_GRID = [
|
| 229 |
+
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
|
| 230 |
+
[0, 5, 10, 15, 25, 50],
|
| 231 |
+
[
|
| 232 |
+
[217.0, 439.0, 572.0, 768.0, 960.0, 1227.0, 1449.0, 1521.0],
|
| 233 |
+
[302.0, 551.0, 580.0, 800.0, 1028.0, 1257.0, 1470.0, 1529.0],
|
| 234 |
+
[388.0, 572.0, 619.0, 839.0, 1077.0, 1305.0, 1490.0, 1561.0],
|
| 235 |
+
[467.0, 591.0, 764.0, 878.0, 1097.0, 1390.0, 1530.0, 1591.0],
|
| 236 |
+
[539.0, 622.0, 815.0, 953.0, 1120.0, 1420.0, 1560.0, 1601.0],
|
| 237 |
+
[772.0, 912.0, 958.0, 1145.0, 1318.0, 1511.0, 1577.0, 1623.0],
|
| 238 |
+
],
|
| 239 |
+
]
|
| 240 |
+
AI_PICK_ELO_GRID = [
|
| 241 |
+
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
|
| 242 |
+
[0, 5, 10, 15, 25, 50],
|
| 243 |
+
[
|
| 244 |
+
[-533.0, -515.0, -355.0, 234.0, 650.0, 1147.0, 1546.0, 1700.0],
|
| 245 |
+
[-531.0, -450.0, -69.0, 347.0, 670.0, 1182.0, 1550.0, 1700.0],
|
| 246 |
+
[-450.0, -311.0, 140.0, 459.0, 693.0, 1252.0, 1555.0, 1700.0],
|
| 247 |
+
[-365.0, -82.0, 265.0, 508.0, 864.0, 1301.0, 1619.0, 1700.0],
|
| 248 |
+
[-113.0, 273.0, 363.0, 641.0, 983.0, 1486.0, 1700.0, 1700.0],
|
| 249 |
+
[514.0, 670.0, 870.0, 1128.0, 1305.0, 1550.0, 1700.0, 1700.0],
|
| 250 |
+
],
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
TOP_MOVE_DELTA_SCORE = "top_move_delta_score"
|
| 255 |
+
TOP_MOVE_SCORE = "top_move_score"
|
| 256 |
+
TOP_MOVE_DELTA_WINRATE = "top_move_delta_winrate"
|
| 257 |
+
TOP_MOVE_WINRATE = "top_move_winrate"
|
| 258 |
+
TOP_MOVE_VISITS = "top_move_visits"
|
| 259 |
+
# TOP_MOVE_UTILITY = "top_move_utility"
|
| 260 |
+
# TOP_MOVE_UTILITYLCB = "top_move_utiltiy_lcb"
|
| 261 |
+
# TOP_MOVE_SCORE_STDDEV = "top_move_score_stddev"
|
| 262 |
+
TOP_MOVE_NOTHING = "top_move_nothing"
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
TOP_MOVE_OPTIONS = [
|
| 266 |
+
TOP_MOVE_SCORE,
|
| 267 |
+
TOP_MOVE_DELTA_SCORE,
|
| 268 |
+
TOP_MOVE_WINRATE,
|
| 269 |
+
TOP_MOVE_DELTA_WINRATE,
|
| 270 |
+
TOP_MOVE_VISITS,
|
| 271 |
+
TOP_MOVE_NOTHING,
|
| 272 |
+
# TOP_MOVE_SCORE_STDDEV,
|
| 273 |
+
# TOP_MOVE_UTILITY,
|
| 274 |
+
# TOP_MOVE_UTILITYLCB
|
| 275 |
+
]
|
| 276 |
+
REPORT_DT = 1
|
| 277 |
+
PONDERING_REPORT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|
+
import subprocess
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import traceback
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
|
| 13 |
+
from katrain.core.constants import OUTPUT_DEBUG, OUTPUT_ERROR, OUTPUT_INFO, OUTPUT_KATAGO_STDERR, DATA_FOLDER
|
| 14 |
+
from katrain.core.engine import BaseEngine
|
| 15 |
+
from katrain.core.game import BaseGame
|
| 16 |
+
from katrain.core.lang import i18n
|
| 17 |
+
from katrain.core.sgf_parser import Move
|
| 18 |
+
from katrain.core.utils import find_package_resource
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class KataGoContributeEngine(BaseEngine):
|
| 22 |
+
"""Starts and communicates with the KataGo contribute program"""
|
| 23 |
+
|
| 24 |
+
DEFAULT_MAX_GAMES = 8
|
| 25 |
+
|
| 26 |
+
SHOW_RESULT_TIME = 5
|
| 27 |
+
GIVE_UP_AFTER = 120
|
| 28 |
+
|
| 29 |
+
def __init__(self, katrain):
|
| 30 |
+
super().__init__(katrain, katrain.config("contribute"))
|
| 31 |
+
self.katrain = katrain
|
| 32 |
+
base_dir = os.path.expanduser("~/.katrain/katago_contribute")
|
| 33 |
+
self.katago_process = None
|
| 34 |
+
self.stdout_thread = None
|
| 35 |
+
self.stderr_thread = None
|
| 36 |
+
self.shell = False
|
| 37 |
+
self.active_games = {}
|
| 38 |
+
self.finished_games = set()
|
| 39 |
+
self.showing_game = None
|
| 40 |
+
self.last_advance = 0
|
| 41 |
+
self.move_count = 0
|
| 42 |
+
self.uploaded_games_count = 0
|
| 43 |
+
self.last_move_for_game = defaultdict(int)
|
| 44 |
+
self.visits_count = 0
|
| 45 |
+
self.start_time = 0
|
| 46 |
+
self.server_error = None
|
| 47 |
+
self.paused = False
|
| 48 |
+
self.save_sgf = self.config.get("savesgf", False)
|
| 49 |
+
self.save_path = self.config.get("savepath", "./dist_sgf/")
|
| 50 |
+
self.move_speed = self.config.get("movespeed", 2.0)
|
| 51 |
+
|
| 52 |
+
exe = self.get_engine_path(self.config.get("katago"))
|
| 53 |
+
cacert_path = os.path.join(os.path.split(exe)[0], "cacert.pem")
|
| 54 |
+
if not os.path.isfile(cacert_path):
|
| 55 |
+
try:
|
| 56 |
+
shutil.copyfile(find_package_resource("katrain/KataGo/cacert.pem"), cacert_path)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
self.katrain.log(
|
| 59 |
+
f"Could not copy cacert file ({e}), please add it manually to your katago.exe directory",
|
| 60 |
+
OUTPUT_ERROR,
|
| 61 |
+
)
|
| 62 |
+
cfg = find_package_resource(self.config.get("config"))
|
| 63 |
+
|
| 64 |
+
settings_dict = {
|
| 65 |
+
"username": self.config.get("username"),
|
| 66 |
+
"password": self.config.get("password"),
|
| 67 |
+
"maxSimultaneousGames": self.config.get("maxgames") or self.DEFAULT_MAX_GAMES,
|
| 68 |
+
"includeOwnership": self.config.get("ownership") or False,
|
| 69 |
+
"logGamesAsJson": True,
|
| 70 |
+
"homeDataDir": os.path.expanduser(DATA_FOLDER),
|
| 71 |
+
}
|
| 72 |
+
self.max_buffer_games = 2 * settings_dict["maxSimultaneousGames"]
|
| 73 |
+
settings = {f"{k}={v}" for k, v in settings_dict.items()}
|
| 74 |
+
self.command = shlex.split(
|
| 75 |
+
f'"{exe}" contribute -config "{cfg}" -base-dir "{base_dir}" -override-config {shlex.quote(",".join(settings))}'
|
| 76 |
+
)
|
| 77 |
+
self.start()
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def game_ended(game):
|
| 81 |
+
cn = game.current_node
|
| 82 |
+
if cn.is_pass and cn.analysis_exists:
|
| 83 |
+
moves = cn.candidate_moves
|
| 84 |
+
if moves and moves[0]["move"] == "pass":
|
| 85 |
+
game.play(Move(None, player=game.current_node.next_player)) # play pass
|
| 86 |
+
return game.end_result
|
| 87 |
+
|
| 88 |
+
def advance_showing_game(self):
|
| 89 |
+
current_game = self.active_games.get(self.showing_game)
|
| 90 |
+
if current_game:
|
| 91 |
+
end_result = self.game_ended(current_game)
|
| 92 |
+
if end_result is not None:
|
| 93 |
+
self.finished_games.add(self.showing_game)
|
| 94 |
+
if time.time() - self.last_advance > self.SHOW_RESULT_TIME:
|
| 95 |
+
del self.active_games[self.showing_game]
|
| 96 |
+
if self.save_sgf:
|
| 97 |
+
filename = os.path.join(self.save_path, f"{self.showing_game}.sgf")
|
| 98 |
+
self.katrain.log(current_game.write_sgf(filename, self.katrain.config("trainer")), OUTPUT_INFO)
|
| 99 |
+
|
| 100 |
+
self.katrain.log(f"Game {self.showing_game} finished, finding a new one", OUTPUT_INFO)
|
| 101 |
+
self.showing_game = None
|
| 102 |
+
elif time.time() - self.last_advance > self.move_speed or len(self.active_games) > self.max_buffer_games:
|
| 103 |
+
if current_game.current_node.children:
|
| 104 |
+
current_game.redo(1)
|
| 105 |
+
self.last_advance = time.time()
|
| 106 |
+
self.katrain("update-state")
|
| 107 |
+
elif time.time() - self.last_advance > self.GIVE_UP_AFTER:
|
| 108 |
+
self.katrain.log(
|
| 109 |
+
f"Giving up on game {self.showing_game} which appears stuck, finding a new one", OUTPUT_INFO
|
| 110 |
+
)
|
| 111 |
+
self.showing_game = None
|
| 112 |
+
else:
|
| 113 |
+
if self.active_games:
|
| 114 |
+
self.showing_game = None
|
| 115 |
+
best_count = -1
|
| 116 |
+
for game_id, game in self.active_games.items(): # find game with most moves left to show
|
| 117 |
+
count = 0
|
| 118 |
+
node = game.current_node
|
| 119 |
+
while node.children:
|
| 120 |
+
node = node.children[0]
|
| 121 |
+
count += 1
|
| 122 |
+
if count > best_count:
|
| 123 |
+
best_count = count
|
| 124 |
+
self.showing_game = game_id
|
| 125 |
+
self.last_advance = time.time()
|
| 126 |
+
self.katrain.log(f"Showing game {self.showing_game}, {best_count} moves left to show.", OUTPUT_INFO)
|
| 127 |
+
|
| 128 |
+
self.katrain.game = self.active_games[self.showing_game]
|
| 129 |
+
self.katrain("update-state", redraw_board=True)
|
| 130 |
+
|
| 131 |
+
def status(self):
|
| 132 |
+
return f"Contributing to distributed training\nGames: {self.uploaded_games_count} uploaded, {len(self.active_games)} in buffer, {len(self.finished_games)} shown\n{self.move_count} moves played ({60*self.move_count/(time.time()-self.start_time):.1f}/min, {self.visits_count / (time.time() - self.start_time):.1f} visits/s)\n"
|
| 133 |
+
|
| 134 |
+
def is_idle(self):
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
+
def queries_remaining(self):
|
| 138 |
+
return 1
|
| 139 |
+
|
| 140 |
+
def start(self):
|
| 141 |
+
try:
|
| 142 |
+
self.katrain.log(f"Starting Distributed KataGo with {self.command}", OUTPUT_INFO)
|
| 143 |
+
startupinfo = None
|
| 144 |
+
if hasattr(subprocess, "STARTUPINFO"):
|
| 145 |
+
startupinfo = subprocess.STARTUPINFO()
|
| 146 |
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # stop command box popups on win/pyinstaller
|
| 147 |
+
self.katago_process = subprocess.Popen(
|
| 148 |
+
self.command,
|
| 149 |
+
stdout=subprocess.PIPE,
|
| 150 |
+
stderr=subprocess.PIPE,
|
| 151 |
+
stdin=subprocess.PIPE,
|
| 152 |
+
startupinfo=startupinfo,
|
| 153 |
+
shell=self.shell,
|
| 154 |
+
)
|
| 155 |
+
except (FileNotFoundError, PermissionError, OSError) as e:
|
| 156 |
+
self.katrain.log(
|
| 157 |
+
i18n._("Starting Kata failed").format(command=self.command, error=e),
|
| 158 |
+
OUTPUT_ERROR,
|
| 159 |
+
)
|
| 160 |
+
return # don't start
|
| 161 |
+
self.paused = False
|
| 162 |
+
self.stdout_thread = threading.Thread(target=self._read_stdout_thread, daemon=True)
|
| 163 |
+
self.stderr_thread = threading.Thread(target=self._read_stderr_thread, daemon=True)
|
| 164 |
+
self.stdout_thread.start()
|
| 165 |
+
self.stderr_thread.start()
|
| 166 |
+
|
| 167 |
+
def check_alive(self, os_error="", maybe_open_help=False):
|
| 168 |
+
ok = self.katago_process and self.katago_process.poll() is None
|
| 169 |
+
if not ok:
|
| 170 |
+
if self.katago_process:
|
| 171 |
+
code = self.katago_process and self.katago_process.poll()
|
| 172 |
+
if code == 3221225781:
|
| 173 |
+
died_msg = i18n._("Engine missing DLL")
|
| 174 |
+
else:
|
| 175 |
+
os_error += f"status {code}"
|
| 176 |
+
died_msg = i18n._("Engine died unexpectedly").format(error=os_error)
|
| 177 |
+
if code != 1 and not self.server_error: # deliberate exit, already showed message?
|
| 178 |
+
self.katrain.log(died_msg, OUTPUT_ERROR)
|
| 179 |
+
self.katago_process = None
|
| 180 |
+
return ok
|
| 181 |
+
|
| 182 |
+
def shutdown(self, finish=False):
|
| 183 |
+
process = self.katago_process
|
| 184 |
+
if process:
|
| 185 |
+
self.katago_process.stdin.write(b"forcequit\n")
|
| 186 |
+
self.katago_process.stdin.flush()
|
| 187 |
+
self.katago_process = None
|
| 188 |
+
process.terminate()
|
| 189 |
+
if finish is not None:
|
| 190 |
+
for t in [self.stderr_thread, self.stdout_thread]:
|
| 191 |
+
if t:
|
| 192 |
+
t.join()
|
| 193 |
+
|
| 194 |
+
def graceful_shutdown(self):
|
| 195 |
+
"""respond to esc"""
|
| 196 |
+
if self.katago_process:
|
| 197 |
+
self.katago_process.stdin.write(b"quit\n")
|
| 198 |
+
self.katago_process.stdin.flush()
|
| 199 |
+
self.katrain.log("Finishing games in progress and stopping contribution", OUTPUT_KATAGO_STDERR)
|
| 200 |
+
|
| 201 |
+
def pause(self):
|
| 202 |
+
"""respond to pause"""
|
| 203 |
+
if self.katago_process:
|
| 204 |
+
if not self.paused:
|
| 205 |
+
self.katago_process.stdin.write(b"pause\n")
|
| 206 |
+
self.katago_process.stdin.flush()
|
| 207 |
+
self.katrain.log("Pausing contribution", OUTPUT_KATAGO_STDERR)
|
| 208 |
+
else:
|
| 209 |
+
self.katago_process.stdin.write(b"resume\n")
|
| 210 |
+
self.katago_process.stdin.flush()
|
| 211 |
+
self.katrain.log("Resuming contribution", OUTPUT_KATAGO_STDERR)
|
| 212 |
+
self.paused = not self.paused
|
| 213 |
+
|
| 214 |
+
def _read_stderr_thread(self):
|
| 215 |
+
while self.katago_process is not None:
|
| 216 |
+
try:
|
| 217 |
+
line = self.katago_process.stderr.readline()
|
| 218 |
+
if line:
|
| 219 |
+
try:
|
| 220 |
+
message = line.decode(errors="ignore").strip()
|
| 221 |
+
if any(
|
| 222 |
+
s in message
|
| 223 |
+
for s in ["not status code 200 OK", "Server returned error", "Uncaught exception:"]
|
| 224 |
+
):
|
| 225 |
+
message = message.replace("what():", "").replace("Uncaught exception:", "").strip()
|
| 226 |
+
self.server_error = message # don't be surprised by engine dying
|
| 227 |
+
self.katrain.log(message, OUTPUT_ERROR)
|
| 228 |
+
return
|
| 229 |
+
else:
|
| 230 |
+
self.katrain.log(message, OUTPUT_KATAGO_STDERR)
|
| 231 |
+
except Exception as e:
|
| 232 |
+
print("ERROR in processing KataGo stderr:", line, "Exception", e)
|
| 233 |
+
elif self.katago_process and not self.check_alive():
|
| 234 |
+
return
|
| 235 |
+
except Exception as e:
|
| 236 |
+
self.katrain.log(f"Exception in reading stdout {e}", OUTPUT_DEBUG)
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
def _read_stdout_thread(self):
|
| 240 |
+
while self.katago_process is not None:
|
| 241 |
+
try:
|
| 242 |
+
line = self.katago_process.stdout.readline()
|
| 243 |
+
if line:
|
| 244 |
+
line = line.decode(errors="ignore").strip()
|
| 245 |
+
if line.startswith("{"):
|
| 246 |
+
try:
|
| 247 |
+
analysis = json.loads(line)
|
| 248 |
+
if "gameId" in analysis:
|
| 249 |
+
game_id = analysis["gameId"]
|
| 250 |
+
if game_id in self.finished_games:
|
| 251 |
+
continue
|
| 252 |
+
current_game = self.active_games.get(game_id)
|
| 253 |
+
new_game = current_game is None
|
| 254 |
+
if new_game:
|
| 255 |
+
board_size = [analysis["boardXSize"], analysis["boardYSize"]]
|
| 256 |
+
placements = {
|
| 257 |
+
f"A{bw}": [
|
| 258 |
+
Move.from_gtp(move, pl).sgf(board_size)
|
| 259 |
+
for pl, move in analysis["initialStones"]
|
| 260 |
+
if pl == bw
|
| 261 |
+
]
|
| 262 |
+
for bw in "BW"
|
| 263 |
+
}
|
| 264 |
+
game_properties = {k: v for k, v in placements.items() if v}
|
| 265 |
+
game_properties["SZ"] = f"{board_size[0]}:{board_size[1]}"
|
| 266 |
+
game_properties["KM"] = analysis["rules"]["komi"]
|
| 267 |
+
game_properties["RU"] = json.dumps(analysis["rules"])
|
| 268 |
+
game_properties["PB"] = analysis["blackPlayer"]
|
| 269 |
+
game_properties["PW"] = analysis["whitePlayer"]
|
| 270 |
+
current_game = BaseGame(
|
| 271 |
+
self.katrain, game_properties=game_properties, bypass_config=True
|
| 272 |
+
)
|
| 273 |
+
self.active_games[game_id] = current_game
|
| 274 |
+
last_node = current_game.sync_branch(
|
| 275 |
+
[Move.from_gtp(coord, pl) for pl, coord in analysis["moves"]]
|
| 276 |
+
)
|
| 277 |
+
last_node.set_analysis(analysis)
|
| 278 |
+
if new_game:
|
| 279 |
+
current_game.set_current_node(last_node)
|
| 280 |
+
self.start_time = self.start_time or time.time() - 1
|
| 281 |
+
self.move_count += 1
|
| 282 |
+
self.visits_count += analysis["rootInfo"]["visits"]
|
| 283 |
+
last_move = self.last_move_for_game[game_id]
|
| 284 |
+
self.last_move_for_game[game_id] = time.time()
|
| 285 |
+
dt = self.last_move_for_game[game_id] - last_move if last_move else 0
|
| 286 |
+
self.katrain.log(
|
| 287 |
+
f"[{time.time()-self.start_time:.1f}] Game {game_id} Move {analysis['turnNumber']}: {' '.join(analysis['move'])} Visits {analysis['rootInfo']['visits']} Time {dt:.1f}s\t Moves/min {60*self.move_count/(time.time()-self.start_time):.1f} Visits/s {self.visits_count/(time.time()-self.start_time):.1f}",
|
| 288 |
+
OUTPUT_DEBUG,
|
| 289 |
+
)
|
| 290 |
+
self.katrain("update-state")
|
| 291 |
+
except Exception as e:
|
| 292 |
+
traceback.print_exc()
|
| 293 |
+
self.katrain.log(f"Exception {e} in parsing or processing JSON: {line}", OUTPUT_ERROR)
|
| 294 |
+
elif "uploaded sgf" in line:
|
| 295 |
+
self.uploaded_games_count += 1
|
| 296 |
+
else:
|
| 297 |
+
self.katrain.log(line, OUTPUT_KATAGO_STDERR)
|
| 298 |
+
elif self.katago_process and not self.check_alive(): # stderr will do this
|
| 299 |
+
return
|
| 300 |
+
except Exception as e:
|
| 301 |
+
self.katrain.log(f"Exception in reading stdout {e}", OUTPUT_DEBUG)
|
| 302 |
+
return
|
katrain/core/engine.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import platform
|
| 5 |
+
import queue
|
| 6 |
+
import shlex
|
| 7 |
+
import subprocess
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import traceback
|
| 11 |
+
from typing import Callable, Dict, List, Optional
|
| 12 |
+
|
| 13 |
+
from kivy.utils import platform as kivy_platform
|
| 14 |
+
|
| 15 |
+
from katrain.core.constants import (
|
| 16 |
+
OUTPUT_DEBUG,
|
| 17 |
+
OUTPUT_ERROR,
|
| 18 |
+
OUTPUT_EXTRA_DEBUG,
|
| 19 |
+
OUTPUT_KATAGO_STDERR,
|
| 20 |
+
DATA_FOLDER,
|
| 21 |
+
KATAGO_EXCEPTION,
|
| 22 |
+
PONDERING_REPORT_DT,
|
| 23 |
+
)
|
| 24 |
+
from katrain.core.game_node import GameNode
|
| 25 |
+
from katrain.core.lang import i18n
|
| 26 |
+
from katrain.core.sgf_parser import Move
|
| 27 |
+
from katrain.core.utils import find_package_resource, json_truncate_arrays
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class BaseEngine: # some common elements between analysis and contribute engine
|
| 31 |
+
|
| 32 |
+
RULESETS_ABBR = [
|
| 33 |
+
("jp", "japanese"),
|
| 34 |
+
("cn", "chinese"),
|
| 35 |
+
("ko", "korean"),
|
| 36 |
+
("aga", "aga"),
|
| 37 |
+
("tt", "tromp-taylor"),
|
| 38 |
+
("nz", "new zealand"),
|
| 39 |
+
("stone_scoring", "stone_scoring"),
|
| 40 |
+
]
|
| 41 |
+
RULESETS = {fromkey: name for abbr, name in RULESETS_ABBR for fromkey in [abbr, name]}
|
| 42 |
+
|
| 43 |
+
def __init__(self, katrain, config):
|
| 44 |
+
self.katrain = katrain
|
| 45 |
+
self.config = config
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def get_rules(ruleset):
|
| 49 |
+
if ruleset.strip().startswith("{"):
|
| 50 |
+
try:
|
| 51 |
+
ruleset = json.loads(ruleset)
|
| 52 |
+
except json.JSONDecodeError:
|
| 53 |
+
pass
|
| 54 |
+
if isinstance(ruleset, dict):
|
| 55 |
+
return ruleset
|
| 56 |
+
return KataGoEngine.RULESETS.get(str(ruleset).lower(), "japanese")
|
| 57 |
+
|
| 58 |
+
def advance_showing_game(self):
|
| 59 |
+
pass # avoid transitional error
|
| 60 |
+
|
| 61 |
+
def status(self):
|
| 62 |
+
return "" # avoid transitional error
|
| 63 |
+
|
| 64 |
+
def get_engine_path(self, exe):
|
| 65 |
+
if not exe:
|
| 66 |
+
if kivy_platform == "win":
|
| 67 |
+
exe = "katrain/KataGo/katago.exe"
|
| 68 |
+
elif kivy_platform == "linux":
|
| 69 |
+
exe = "katrain/KataGo/katago"
|
| 70 |
+
else:
|
| 71 |
+
exe = find_package_resource("katrain/KataGo/katago-osx") # github actions built
|
| 72 |
+
if not os.path.isfile(exe) or "arm64" in platform.version().lower():
|
| 73 |
+
exe = "katago" # e.g. MacOS after brewing
|
| 74 |
+
if exe.startswith("katrain"):
|
| 75 |
+
exe = find_package_resource(exe)
|
| 76 |
+
exepath, exename = os.path.split(exe)
|
| 77 |
+
|
| 78 |
+
if exepath and not os.path.isfile(exe):
|
| 79 |
+
self.on_error(i18n._("Kata exe not found").format(exe=exe), "KATAGO-EXE")
|
| 80 |
+
return None
|
| 81 |
+
elif not exepath:
|
| 82 |
+
paths = os.getenv("PATH", ".").split(os.pathsep) + ["/opt/homebrew/bin/"]
|
| 83 |
+
exe_with_paths = [os.path.join(path, exe) for path in paths if os.path.isfile(os.path.join(path, exe))]
|
| 84 |
+
if not exe_with_paths:
|
| 85 |
+
self.on_error(i18n._("Kata exe not found in path").format(exe=exe), "KATAGO-EXE")
|
| 86 |
+
return None
|
| 87 |
+
exe = exe_with_paths[0]
|
| 88 |
+
return exe
|
| 89 |
+
|
| 90 |
+
def on_error(self, message, code, allow_popup):
|
| 91 |
+
print("ERROR", message, code)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class KataGoEngine(BaseEngine):
|
| 95 |
+
"""Starts and communicates with the KataGO analysis engine"""
|
| 96 |
+
|
| 97 |
+
PONDER_KEY = "_kt_continuous"
|
| 98 |
+
|
| 99 |
+
def __init__(self, katrain, config):
|
| 100 |
+
super().__init__(katrain, config)
|
| 101 |
+
|
| 102 |
+
self.allow_recovery = self.config.get("allow_recovery", True) # if false, don't give popups
|
| 103 |
+
self.queries = {} # outstanding query id -> start time and callback
|
| 104 |
+
self.ponder_query = None
|
| 105 |
+
self.query_counter = 0
|
| 106 |
+
self.katago_process = None
|
| 107 |
+
self.base_priority = 0
|
| 108 |
+
self.override_settings = {"reportAnalysisWinratesAs": "BLACK"} # force these settings
|
| 109 |
+
self.analysis_thread = None
|
| 110 |
+
self.stderr_thread = None
|
| 111 |
+
self.write_stdin_thread = None
|
| 112 |
+
self.shell = False
|
| 113 |
+
self.write_queue = queue.Queue()
|
| 114 |
+
self.thread_lock = threading.Lock()
|
| 115 |
+
if config.get("altcommand", ""):
|
| 116 |
+
self.command = config["altcommand"]
|
| 117 |
+
self.shell = True
|
| 118 |
+
else:
|
| 119 |
+
model = find_package_resource(config["model"])
|
| 120 |
+
cfg = find_package_resource(config["config"])
|
| 121 |
+
exe = self.get_engine_path(config.get("katago", "").strip())
|
| 122 |
+
|
| 123 |
+
if not exe:
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
# Add human model to command if provided
|
| 127 |
+
if config.get("humanlike_model", ""):
|
| 128 |
+
human_model_path = find_package_resource(config.get("humanlike_model",""))
|
| 129 |
+
if os.path.isfile(human_model_path):
|
| 130 |
+
self.command = shlex.split(
|
| 131 |
+
f'"{exe}" analysis -model "{model}" -human-model "{human_model_path}" -config "{cfg}" -override-config "homeDataDir={os.path.expanduser(DATA_FOLDER)}"'
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
self.katrain.log(f"Human model not found at {human_model_path}", -1)
|
| 135 |
+
# Fall back to regular command without human model
|
| 136 |
+
self.command = shlex.split(
|
| 137 |
+
f'"{exe}" analysis -model "{model}" -config "{cfg}" -override-config "homeDataDir={os.path.expanduser(DATA_FOLDER)}"'
|
| 138 |
+
)
|
| 139 |
+
else:
|
| 140 |
+
# Regular command without human model
|
| 141 |
+
self.command = shlex.split(
|
| 142 |
+
f'"{exe}" analysis -model "{model}" -config "{cfg}" -override-config "homeDataDir={os.path.expanduser(DATA_FOLDER)}"'
|
| 143 |
+
)
|
| 144 |
+
self.start()
|
| 145 |
+
|
| 146 |
+
def on_error(self, message, code=None, allow_popup=True):
|
| 147 |
+
self.katrain.log(message, OUTPUT_ERROR)
|
| 148 |
+
if self.allow_recovery and allow_popup:
|
| 149 |
+
self.katrain("engine_recovery_popup", message, code)
|
| 150 |
+
|
| 151 |
+
def start(self):
|
| 152 |
+
with self.thread_lock:
|
| 153 |
+
self.write_queue = queue.Queue()
|
| 154 |
+
try:
|
| 155 |
+
self.katrain.log(f"Starting KataGo with {self.command}", OUTPUT_DEBUG)
|
| 156 |
+
startupinfo = None
|
| 157 |
+
if hasattr(subprocess, "STARTUPINFO"):
|
| 158 |
+
startupinfo = subprocess.STARTUPINFO()
|
| 159 |
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # stop command box popups on win/pyinstaller
|
| 160 |
+
self.katago_process = subprocess.Popen(
|
| 161 |
+
self.command,
|
| 162 |
+
startupinfo=startupinfo,
|
| 163 |
+
stdin=subprocess.PIPE,
|
| 164 |
+
stdout=subprocess.PIPE,
|
| 165 |
+
stderr=subprocess.PIPE,
|
| 166 |
+
shell=self.shell,
|
| 167 |
+
)
|
| 168 |
+
except (FileNotFoundError, PermissionError, OSError) as e:
|
| 169 |
+
self.on_error(i18n._("Starting Kata failed").format(command=self.command, error=e), code="c")
|
| 170 |
+
return # don't start
|
| 171 |
+
self.analysis_thread = threading.Thread(target=self._analysis_read_thread, daemon=True)
|
| 172 |
+
self.stderr_thread = threading.Thread(target=self._read_stderr_thread, daemon=True)
|
| 173 |
+
self.write_stdin_thread = threading.Thread(target=self._write_stdin_thread, daemon=True)
|
| 174 |
+
self.analysis_thread.start()
|
| 175 |
+
self.stderr_thread.start()
|
| 176 |
+
self.write_stdin_thread.start()
|
| 177 |
+
|
| 178 |
+
def on_new_game(self):
|
| 179 |
+
self.base_priority += 1
|
| 180 |
+
if not self.is_idle():
|
| 181 |
+
with self.thread_lock:
|
| 182 |
+
self.write_queue = queue.Queue()
|
| 183 |
+
self.terminate_queries(only_for_node=None, lock=False)
|
| 184 |
+
self.ponder_query = None
|
| 185 |
+
self.queries = {}
|
| 186 |
+
|
| 187 |
+
def terminate_queries(self, only_for_node=None, lock=True):
|
| 188 |
+
if lock:
|
| 189 |
+
with self.thread_lock:
|
| 190 |
+
return self.terminate_queries(only_for_node=only_for_node, lock=False)
|
| 191 |
+
for query_id, (_, _, _, _, node) in list(self.queries.items()):
|
| 192 |
+
if only_for_node is None or only_for_node is node:
|
| 193 |
+
self.terminate_query(query_id)
|
| 194 |
+
|
| 195 |
+
def stop_pondering(self):
|
| 196 |
+
pq = self.ponder_query
|
| 197 |
+
if pq:
|
| 198 |
+
self.terminate_query(pq["id"], ignore_further_results=False)
|
| 199 |
+
self.ponder_query = None
|
| 200 |
+
|
| 201 |
+
def terminate_query(self, query_id, ignore_further_results=True):
|
| 202 |
+
self.katrain.log(f"Terminating query {query_id}", OUTPUT_DEBUG)
|
| 203 |
+
|
| 204 |
+
if query_id is not None:
|
| 205 |
+
self.send_query({"action": "terminate", "terminateId": query_id}, None, None)
|
| 206 |
+
if ignore_further_results:
|
| 207 |
+
self.queries.pop(query_id, None)
|
| 208 |
+
|
| 209 |
+
def restart(self):
|
| 210 |
+
self.queries = {}
|
| 211 |
+
self.shutdown(finish=False)
|
| 212 |
+
self.start()
|
| 213 |
+
|
| 214 |
+
def check_alive(self, os_error="", exception_if_dead=False, maybe_open_recovery=False):
|
| 215 |
+
ok = self.katago_process and self.katago_process.poll() is None
|
| 216 |
+
if not ok and exception_if_dead:
|
| 217 |
+
if self.katago_process:
|
| 218 |
+
code = self.katago_process and self.katago_process.poll()
|
| 219 |
+
if code == 3221225781:
|
| 220 |
+
died_msg = i18n._("Engine missing DLL")
|
| 221 |
+
else:
|
| 222 |
+
died_msg = i18n._("Engine died unexpectedly").format(error=f"{os_error} status {code}")
|
| 223 |
+
if code != 1: # deliberate exit
|
| 224 |
+
self.on_error(died_msg, code, allow_popup=maybe_open_recovery)
|
| 225 |
+
self.katago_process = None # return from threads
|
| 226 |
+
else:
|
| 227 |
+
self.katrain.log(i18n._("Engine died unexpectedly").format(error=os_error), OUTPUT_DEBUG)
|
| 228 |
+
return ok
|
| 229 |
+
|
| 230 |
+
def wait_to_finish(self):
|
| 231 |
+
while self.queries and self.katago_process and self.katago_process.poll() is None:
|
| 232 |
+
time.sleep(0.1)
|
| 233 |
+
|
| 234 |
+
def shutdown(self, finish=False):
|
| 235 |
+
process = self.katago_process
|
| 236 |
+
if finish and process:
|
| 237 |
+
self.wait_to_finish()
|
| 238 |
+
if process:
|
| 239 |
+
self.katago_process = None
|
| 240 |
+
self.katrain.log("Terminating KataGo process", OUTPUT_DEBUG)
|
| 241 |
+
process.terminate()
|
| 242 |
+
self.katrain.log("Terminated KataGo process", OUTPUT_DEBUG)
|
| 243 |
+
if finish is not None: # don't care if exiting app
|
| 244 |
+
for t in [self.write_stdin_thread, self.analysis_thread, self.stderr_thread]:
|
| 245 |
+
if t:
|
| 246 |
+
t.join()
|
| 247 |
+
|
| 248 |
+
def is_idle(self):
|
| 249 |
+
return not self.queries and self.write_queue.empty()
|
| 250 |
+
|
| 251 |
+
def queries_remaining(self):
|
| 252 |
+
return len(self.queries) + int(not self.write_queue.empty())
|
| 253 |
+
|
| 254 |
+
def _read_stderr_thread(self):
|
| 255 |
+
while self.katago_process is not None:
|
| 256 |
+
try:
|
| 257 |
+
line = self.katago_process.stderr.readline()
|
| 258 |
+
if line:
|
| 259 |
+
if b"Uncaught exception" in line or b"what()" in line: # linux=what
|
| 260 |
+
msg = f"KataGo Engine Failed: {line.decode(errors='ignore')[9:].strip()}"
|
| 261 |
+
self.on_error(msg, KATAGO_EXCEPTION)
|
| 262 |
+
return
|
| 263 |
+
try:
|
| 264 |
+
self.katrain.log(line.decode(errors="ignore").strip(), OUTPUT_KATAGO_STDERR)
|
| 265 |
+
except Exception as e:
|
| 266 |
+
print("ERROR in processing KataGo stderr:", line, "Exception", e)
|
| 267 |
+
elif not self.check_alive(exception_if_dead=True):
|
| 268 |
+
return
|
| 269 |
+
except Exception as e:
|
| 270 |
+
self.katrain.log(f"Exception in reading stderr: {e}", OUTPUT_DEBUG)
|
| 271 |
+
return
|
| 272 |
+
|
| 273 |
+
def _analysis_read_thread(self):
|
| 274 |
+
while self.katago_process is not None:
|
| 275 |
+
try:
|
| 276 |
+
line = self.katago_process.stdout.readline().strip()
|
| 277 |
+
if self.katago_process and not line:
|
| 278 |
+
if not self.check_alive(exception_if_dead=True, maybe_open_recovery=True):
|
| 279 |
+
return
|
| 280 |
+
except OSError as e:
|
| 281 |
+
self.check_alive(os_error=str(e), exception_if_dead=True, maybe_open_recovery=True)
|
| 282 |
+
return
|
| 283 |
+
|
| 284 |
+
if b"Uncaught exception" in line:
|
| 285 |
+
msg = f"KataGo Engine Failed: {line.decode(errors='ignore')}"
|
| 286 |
+
self.on_error(msg, KATAGO_EXCEPTION)
|
| 287 |
+
return
|
| 288 |
+
if not line:
|
| 289 |
+
continue
|
| 290 |
+
try:
|
| 291 |
+
analysis = json.loads(line)
|
| 292 |
+
if "id" not in analysis:
|
| 293 |
+
self.katrain.log(f"Error without ID {analysis} received from KataGo", OUTPUT_ERROR)
|
| 294 |
+
continue
|
| 295 |
+
query_id = analysis["id"]
|
| 296 |
+
if query_id not in self.queries:
|
| 297 |
+
if analysis.get("action") != "terminate":
|
| 298 |
+
self.katrain.log(
|
| 299 |
+
f"Query result {query_id} discarded -- recent new game or node reset?", OUTPUT_DEBUG
|
| 300 |
+
)
|
| 301 |
+
continue
|
| 302 |
+
callback, error_callback, start_time, next_move, _ = self.queries[query_id]
|
| 303 |
+
if "error" in analysis:
|
| 304 |
+
del self.queries[query_id]
|
| 305 |
+
if error_callback:
|
| 306 |
+
error_callback(analysis)
|
| 307 |
+
elif not (next_move and "Illegal move" in analysis["error"]): # sweep
|
| 308 |
+
self.katrain.log(f"{analysis} received from KataGo", OUTPUT_ERROR)
|
| 309 |
+
elif "warning" in analysis:
|
| 310 |
+
self.katrain.log(f"{analysis} received from KataGo", OUTPUT_DEBUG)
|
| 311 |
+
elif "terminateId" in analysis:
|
| 312 |
+
self.katrain.log(f"{analysis} received from KataGo", OUTPUT_DEBUG)
|
| 313 |
+
else:
|
| 314 |
+
partial_result = analysis.get("isDuringSearch", False)
|
| 315 |
+
if not partial_result:
|
| 316 |
+
del self.queries[query_id]
|
| 317 |
+
time_taken = time.time() - start_time
|
| 318 |
+
results_exist = not analysis.get("noResults", False)
|
| 319 |
+
self.katrain.log(
|
| 320 |
+
f"[{time_taken:.1f}][{query_id}][{'....' if partial_result else 'done'}] KataGo analysis received: {len(analysis.get('moveInfos',[]))} candidate moves, {analysis['rootInfo']['visits'] if results_exist else 'n/a'} visits",
|
| 321 |
+
OUTPUT_DEBUG,
|
| 322 |
+
)
|
| 323 |
+
self.katrain.log(json_truncate_arrays(analysis), OUTPUT_EXTRA_DEBUG)
|
| 324 |
+
try:
|
| 325 |
+
if callback and results_exist:
|
| 326 |
+
callback(analysis, partial_result)
|
| 327 |
+
except Exception as e:
|
| 328 |
+
self.katrain.log(f"Error in engine callback for query {query_id}: {e}", OUTPUT_ERROR)
|
| 329 |
+
traceback.print_exc()
|
| 330 |
+
if getattr(self.katrain, "update_state", None): # easier mocking etc
|
| 331 |
+
self.katrain.update_state()
|
| 332 |
+
except Exception as e:
|
| 333 |
+
self.katrain.log(f"Unexpected exception {e} while processing KataGo output {line}", OUTPUT_ERROR)
|
| 334 |
+
traceback.print_exc()
|
| 335 |
+
|
| 336 |
+
def _write_stdin_thread(self): # flush only in a thread since it returns only when the other program reads
|
| 337 |
+
while self.katago_process is not None:
|
| 338 |
+
try:
|
| 339 |
+
query, callback, error_callback, next_move, node = self.write_queue.get(block=True, timeout=0.1)
|
| 340 |
+
except queue.Empty:
|
| 341 |
+
continue
|
| 342 |
+
with self.thread_lock:
|
| 343 |
+
if "id" not in query:
|
| 344 |
+
self.query_counter += 1
|
| 345 |
+
query["id"] = f"QUERY:{str(self.query_counter)}"
|
| 346 |
+
|
| 347 |
+
ponder = query.pop(self.PONDER_KEY, False)
|
| 348 |
+
if ponder: # handle pondering in here to be in lock and such
|
| 349 |
+
pq = self.ponder_query or {}
|
| 350 |
+
# basically we handle pondering by just asking for these queries a lot and ignoring duplicates
|
| 351 |
+
# when a different ponder query comes in, e.g. due to selecting a roi or different node, switch
|
| 352 |
+
differences = {
|
| 353 |
+
k: (pq.get(k), query.get(k))
|
| 354 |
+
for k in (query.keys() | pq.keys()) - {"id", "maxVisits", "reportDuringSearchEvery"}
|
| 355 |
+
if pq.get(k) != query.get(k)
|
| 356 |
+
}
|
| 357 |
+
if differences:
|
| 358 |
+
self.stop_pondering()
|
| 359 |
+
query["maxVisits"] = 10_000_000
|
| 360 |
+
query["reportDuringSearchEvery"] = PONDERING_REPORT_DT
|
| 361 |
+
self.ponder_query = query
|
| 362 |
+
else:
|
| 363 |
+
continue
|
| 364 |
+
|
| 365 |
+
terminate = query.get("action") == "terminate"
|
| 366 |
+
if not terminate:
|
| 367 |
+
self.queries[query["id"]] = (callback, error_callback, time.time(), next_move, node)
|
| 368 |
+
tag = "ponder " if ponder else ("terminate " if terminate else "")
|
| 369 |
+
self.katrain.log(f"Sending {tag}query {query['id']}: {json.dumps(query)}", OUTPUT_DEBUG)
|
| 370 |
+
try:
|
| 371 |
+
self.katago_process.stdin.write((json.dumps(query) + "\n").encode())
|
| 372 |
+
self.katago_process.stdin.flush()
|
| 373 |
+
except OSError as e:
|
| 374 |
+
self.katrain.log(f"Exception in writing to katago: {e}", OUTPUT_DEBUG)
|
| 375 |
+
return # some other thread will take care of this
|
| 376 |
+
|
| 377 |
+
def send_query(self, query, callback, error_callback, next_move=None, node=None):
|
| 378 |
+
self.write_queue.put((query, callback, error_callback, next_move, node))
|
| 379 |
+
|
| 380 |
+
def request_analysis(
|
| 381 |
+
self,
|
| 382 |
+
analysis_node: GameNode,
|
| 383 |
+
callback: Callable,
|
| 384 |
+
error_callback: Optional[Callable] = None,
|
| 385 |
+
visits: int = None,
|
| 386 |
+
analyze_fast: bool = False,
|
| 387 |
+
time_limit=True,
|
| 388 |
+
find_alternatives: bool = False,
|
| 389 |
+
region_of_interest: Optional[List] = None,
|
| 390 |
+
priority: int = 0,
|
| 391 |
+
ponder=False, # infinite visits, cancellable
|
| 392 |
+
ownership: Optional[bool] = None,
|
| 393 |
+
next_move: Optional[GameNode] = None,
|
| 394 |
+
extra_settings: Optional[Dict] = None,
|
| 395 |
+
include_policy=True,
|
| 396 |
+
report_every: Optional[float] = None,
|
| 397 |
+
):
|
| 398 |
+
nodes = analysis_node.nodes_from_root
|
| 399 |
+
moves = [m for node in nodes for m in node.moves]
|
| 400 |
+
initial_stones = [m for node in nodes for m in node.placements]
|
| 401 |
+
clear_placements = [m for node in nodes for m in node.clear_placements]
|
| 402 |
+
if clear_placements: # TODO: support these
|
| 403 |
+
self.katrain.log(f"Not analyzing node {analysis_node} as there are AE commands in the path", OUTPUT_DEBUG)
|
| 404 |
+
return
|
| 405 |
+
|
| 406 |
+
if next_move:
|
| 407 |
+
moves.append(next_move)
|
| 408 |
+
if ownership is None:
|
| 409 |
+
ownership = self.config["_enable_ownership"] and not next_move
|
| 410 |
+
|
| 411 |
+
if visits is None:
|
| 412 |
+
visits = self.config["max_visits"]
|
| 413 |
+
if analyze_fast and self.config.get("fast_visits"):
|
| 414 |
+
visits = self.config["fast_visits"]
|
| 415 |
+
|
| 416 |
+
size_x, size_y = analysis_node.board_size
|
| 417 |
+
|
| 418 |
+
if find_alternatives:
|
| 419 |
+
avoid = [
|
| 420 |
+
{
|
| 421 |
+
"moves": list(analysis_node.analysis["moves"].keys()),
|
| 422 |
+
"player": analysis_node.next_player,
|
| 423 |
+
"untilDepth": 1,
|
| 424 |
+
}
|
| 425 |
+
]
|
| 426 |
+
elif region_of_interest:
|
| 427 |
+
xmin, xmax, ymin, ymax = region_of_interest
|
| 428 |
+
avoid = [
|
| 429 |
+
{
|
| 430 |
+
"moves": [
|
| 431 |
+
Move((x, y)).gtp()
|
| 432 |
+
for x in range(0, size_x)
|
| 433 |
+
for y in range(0, size_y)
|
| 434 |
+
if x < xmin or x > xmax or y < ymin or y > ymax
|
| 435 |
+
],
|
| 436 |
+
"player": player,
|
| 437 |
+
"untilDepth": 1, # tried a large number here, or 2, but this seems more natural
|
| 438 |
+
}
|
| 439 |
+
for player in "BW"
|
| 440 |
+
]
|
| 441 |
+
else:
|
| 442 |
+
avoid = []
|
| 443 |
+
|
| 444 |
+
settings = copy.copy(self.override_settings)
|
| 445 |
+
settings["wideRootNoise"] = self.config["wide_root_noise"]
|
| 446 |
+
if time_limit:
|
| 447 |
+
settings["maxTime"] = self.config["max_time"]
|
| 448 |
+
|
| 449 |
+
query = {
|
| 450 |
+
"rules": self.get_rules(analysis_node.ruleset),
|
| 451 |
+
"priority": self.base_priority + priority,
|
| 452 |
+
"analyzeTurns": [len(moves)],
|
| 453 |
+
"maxVisits": visits,
|
| 454 |
+
"komi": analysis_node.komi,
|
| 455 |
+
"boardXSize": size_x,
|
| 456 |
+
"boardYSize": size_y,
|
| 457 |
+
"includeOwnership": ownership and not next_move,
|
| 458 |
+
"includeMovesOwnership": ownership and not next_move,
|
| 459 |
+
"includePolicy": include_policy,
|
| 460 |
+
"initialStones": [[m.player, m.gtp()] for m in initial_stones],
|
| 461 |
+
"initialPlayer": analysis_node.initial_player,
|
| 462 |
+
"moves": [[m.player, m.gtp()] for m in moves],
|
| 463 |
+
"overrideSettings": {**settings, **(extra_settings or {})},
|
| 464 |
+
self.PONDER_KEY: ponder,
|
| 465 |
+
}
|
| 466 |
+
if report_every is not None:
|
| 467 |
+
query["reportDuringSearchEvery"] = report_every
|
| 468 |
+
if avoid:
|
| 469 |
+
query["avoidMoves"] = avoid
|
| 470 |
+
self.send_query(query, callback, error_callback, next_move, analysis_node)
|
| 471 |
+
analysis_node.analysis_visits_requested = max(analysis_node.analysis_visits_requested, visits)
|
katrain/core/game.py
ADDED
|
@@ -0,0 +1,803 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
from datetime import datetime
|
| 7 |
+
from typing import Dict, List, Optional, Union
|
| 8 |
+
|
| 9 |
+
from kivy.clock import Clock
|
| 10 |
+
|
| 11 |
+
from katrain.core.constants import (
|
| 12 |
+
OUTPUT_DEBUG,
|
| 13 |
+
OUTPUT_EXTRA_DEBUG,
|
| 14 |
+
OUTPUT_INFO,
|
| 15 |
+
PLAYER_AI,
|
| 16 |
+
PLAYER_HUMAN,
|
| 17 |
+
PROGRAM_NAME,
|
| 18 |
+
SGF_INTERNAL_COMMENTS_MARKER,
|
| 19 |
+
STATUS_ANALYSIS,
|
| 20 |
+
STATUS_ERROR,
|
| 21 |
+
STATUS_INFO,
|
| 22 |
+
STATUS_TEACHING,
|
| 23 |
+
PRIORITY_GAME_ANALYSIS,
|
| 24 |
+
PRIORITY_EXTRA_ANALYSIS,
|
| 25 |
+
PRIORITY_SWEEP,
|
| 26 |
+
PRIORITY_ALTERNATIVES,
|
| 27 |
+
PRIORITY_EQUALIZE,
|
| 28 |
+
PRIORITY_DEFAULT,
|
| 29 |
+
)
|
| 30 |
+
from katrain.core.engine import KataGoEngine
|
| 31 |
+
from katrain.core.game_node import GameNode
|
| 32 |
+
from katrain.core.lang import i18n, rank_label
|
| 33 |
+
from katrain.core.sgf_parser import SGF, Move
|
| 34 |
+
from katrain.core.utils import var_to_grid, weighted_selection_without_replacement
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class IllegalMoveException(Exception):
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class KaTrainSGF(SGF):
|
| 42 |
+
_NODE_CLASS = GameNode
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class BaseGame:
|
| 46 |
+
"""Represents a game of go, including an implementation of capture rules."""
|
| 47 |
+
|
| 48 |
+
DEFAULT_PROPERTIES = {"GM": 1, "FF": 4}
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
katrain,
|
| 53 |
+
move_tree: GameNode = None,
|
| 54 |
+
game_properties: Optional[Dict] = None,
|
| 55 |
+
sgf_filename=None,
|
| 56 |
+
bypass_config=False, # TODO: refactor?
|
| 57 |
+
):
|
| 58 |
+
self.katrain = katrain
|
| 59 |
+
self._lock = threading.Lock()
|
| 60 |
+
self.game_id = datetime.strftime(datetime.now(), "%Y-%m-%d %H %M %S")
|
| 61 |
+
self.sgf_filename = sgf_filename
|
| 62 |
+
|
| 63 |
+
self.insert_mode = False
|
| 64 |
+
self.external_game = False # not generated by katrain at some point
|
| 65 |
+
|
| 66 |
+
if move_tree:
|
| 67 |
+
self.root = move_tree
|
| 68 |
+
self.external_game = PROGRAM_NAME not in self.root.get_property("AP", "")
|
| 69 |
+
handicap = int(self.root.handicap)
|
| 70 |
+
num_starting_moves_black = 0
|
| 71 |
+
node = self.root
|
| 72 |
+
while node.children:
|
| 73 |
+
node = node.children[0]
|
| 74 |
+
if node.player == "B":
|
| 75 |
+
num_starting_moves_black += 1
|
| 76 |
+
else:
|
| 77 |
+
break
|
| 78 |
+
|
| 79 |
+
if (
|
| 80 |
+
handicap >= 2
|
| 81 |
+
and not self.root.placements
|
| 82 |
+
and not (num_starting_moves_black == handicap)
|
| 83 |
+
and not (self.root.children and self.root.children[0].placements)
|
| 84 |
+
): # not really according to sgf, and not sure if still needed, last clause for fox
|
| 85 |
+
self.root.place_handicap_stones(handicap)
|
| 86 |
+
else:
|
| 87 |
+
default_properties = {**Game.DEFAULT_PROPERTIES, "DT": self.game_id}
|
| 88 |
+
if not bypass_config:
|
| 89 |
+
default_properties.update(
|
| 90 |
+
{
|
| 91 |
+
"SZ": katrain.config("game/size"),
|
| 92 |
+
"KM": katrain.config("game/komi"),
|
| 93 |
+
"RU": katrain.config("game/rules"),
|
| 94 |
+
}
|
| 95 |
+
)
|
| 96 |
+
self.root = GameNode(
|
| 97 |
+
properties={
|
| 98 |
+
**default_properties,
|
| 99 |
+
**(game_properties or {}),
|
| 100 |
+
}
|
| 101 |
+
)
|
| 102 |
+
handicap = katrain.config("game/handicap")
|
| 103 |
+
if not bypass_config and handicap:
|
| 104 |
+
self.root.place_handicap_stones(handicap)
|
| 105 |
+
|
| 106 |
+
if not self.root.get_property("RU"): # if rules missing in sgf, inherit current
|
| 107 |
+
self.root.set_property("RU", katrain.config("game/rules"))
|
| 108 |
+
|
| 109 |
+
self.set_current_node(self.root)
|
| 110 |
+
self.main_time_used = 0
|
| 111 |
+
|
| 112 |
+
# restore shortcuts
|
| 113 |
+
shortcut_id_to_node = {node.get_property("KTSID", None): node for node in self.root.nodes_in_tree}
|
| 114 |
+
for node in self.root.nodes_in_tree:
|
| 115 |
+
shortcut_id = node.get_property("KTSF", None)
|
| 116 |
+
if shortcut_id and shortcut_id in shortcut_id_to_node:
|
| 117 |
+
shortcut_id_to_node[shortcut_id].add_shortcut(node)
|
| 118 |
+
|
| 119 |
+
# -- move tree functions --
|
| 120 |
+
def _init_state(self):
|
| 121 |
+
board_size_x, board_size_y = self.board_size
|
| 122 |
+
self.board = [
|
| 123 |
+
[-1 for _x in range(board_size_x)] for _y in range(board_size_y)
|
| 124 |
+
] # type: List[List[int]] # board pos -> chain id
|
| 125 |
+
self.chains = [] # type: List[List[Move]] # chain id -> chain
|
| 126 |
+
self.prisoners = [] # type: List[Move]
|
| 127 |
+
self.last_capture = [] # type: List[Move]
|
| 128 |
+
|
| 129 |
+
def _calculate_groups(self):
|
| 130 |
+
with self._lock:
|
| 131 |
+
self._init_state()
|
| 132 |
+
try:
|
| 133 |
+
for node in self.current_node.nodes_from_root:
|
| 134 |
+
for m in node.move_with_placements:
|
| 135 |
+
self._validate_move_and_update_chains(
|
| 136 |
+
m, True
|
| 137 |
+
) # ignore ko since we didn't know if it was forced
|
| 138 |
+
if node.clear_placements: # handle AE by playing all moves left from empty board
|
| 139 |
+
clear_coords = {c.coords for c in node.clear_placements}
|
| 140 |
+
stones = [m for c in self.chains for m in c if m.coords not in clear_coords]
|
| 141 |
+
self._init_state()
|
| 142 |
+
for m in stones:
|
| 143 |
+
self._validate_move_and_update_chains(m, True)
|
| 144 |
+
except IllegalMoveException as e:
|
| 145 |
+
raise Exception(f"Unexpected illegal move ({str(e)})")
|
| 146 |
+
|
| 147 |
+
def _validate_move_and_update_chains(self, move: Move, ignore_ko: bool):
|
| 148 |
+
board_size_x, board_size_y = self.board_size
|
| 149 |
+
|
| 150 |
+
def neighbours(moves):
|
| 151 |
+
return {
|
| 152 |
+
self.board[m.coords[1] + dy][m.coords[0] + dx]
|
| 153 |
+
for m in moves
|
| 154 |
+
for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]
|
| 155 |
+
if 0 <= m.coords[0] + dx < board_size_x and 0 <= m.coords[1] + dy < board_size_y
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
ko_or_snapback = len(self.last_capture) == 1 and self.last_capture[0] == move
|
| 159 |
+
self.last_capture = []
|
| 160 |
+
|
| 161 |
+
if move.is_pass:
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
if self.board[move.coords[1]][move.coords[0]] != -1:
|
| 165 |
+
raise IllegalMoveException("Space occupied")
|
| 166 |
+
|
| 167 |
+
# merge chains connected by this move, or create a new one
|
| 168 |
+
nb_chains = list({c for c in neighbours([move]) if c >= 0 and self.chains[c][0].player == move.player})
|
| 169 |
+
if nb_chains:
|
| 170 |
+
this_chain = nb_chains[0]
|
| 171 |
+
self.board = [[nb_chains[0] if sq in nb_chains else sq for sq in line] for line in self.board]
|
| 172 |
+
for oc in nb_chains[1:]:
|
| 173 |
+
self.chains[nb_chains[0]] += self.chains[oc]
|
| 174 |
+
self.chains[oc] = []
|
| 175 |
+
self.chains[nb_chains[0]].append(move)
|
| 176 |
+
else:
|
| 177 |
+
this_chain = len(self.chains)
|
| 178 |
+
self.chains.append([move])
|
| 179 |
+
self.board[move.coords[1]][move.coords[0]] = this_chain
|
| 180 |
+
|
| 181 |
+
# check captures
|
| 182 |
+
opp_nb_chains = {c for c in neighbours([move]) if c >= 0 and self.chains[c][0].player != move.player}
|
| 183 |
+
for c in opp_nb_chains:
|
| 184 |
+
if -1 not in neighbours(self.chains[c]): # no liberties
|
| 185 |
+
self.last_capture += self.chains[c]
|
| 186 |
+
for om in self.chains[c]:
|
| 187 |
+
self.board[om.coords[1]][om.coords[0]] = -1
|
| 188 |
+
self.chains[c] = []
|
| 189 |
+
if ko_or_snapback and len(self.last_capture) == 1 and not ignore_ko:
|
| 190 |
+
raise IllegalMoveException("Ko")
|
| 191 |
+
self.prisoners += self.last_capture
|
| 192 |
+
|
| 193 |
+
# suicide: check rules and throw exception if needed
|
| 194 |
+
if -1 not in neighbours(self.chains[this_chain]):
|
| 195 |
+
rules = self.rules
|
| 196 |
+
if len(self.chains[this_chain]) == 1: # even in new zealand rules, single stone suicide is not allowed
|
| 197 |
+
raise IllegalMoveException("Single stone suicide")
|
| 198 |
+
elif (isinstance(rules, str) and rules in ["tromp-taylor", "new zealand"]) or (
|
| 199 |
+
isinstance(rules, dict) and rules.get("suicide", False)
|
| 200 |
+
):
|
| 201 |
+
self.last_capture += self.chains[this_chain]
|
| 202 |
+
for om in self.chains[this_chain]:
|
| 203 |
+
self.board[om.coords[1]][om.coords[0]] = -1
|
| 204 |
+
self.chains[this_chain] = []
|
| 205 |
+
self.prisoners += self.last_capture
|
| 206 |
+
else: # suicide not allowed by rules
|
| 207 |
+
raise IllegalMoveException("Suicide")
|
| 208 |
+
|
| 209 |
+
# Play a Move from the current position, raise IllegalMoveException if invalid.
|
| 210 |
+
def play(self, move: Move, ignore_ko: bool = False):
|
| 211 |
+
board_size_x, board_size_y = self.board_size
|
| 212 |
+
if not move.is_pass and not (0 <= move.coords[0] < board_size_x and 0 <= move.coords[1] < board_size_y):
|
| 213 |
+
raise IllegalMoveException(f"Move {move} outside of board coordinates")
|
| 214 |
+
try:
|
| 215 |
+
self._validate_move_and_update_chains(move, ignore_ko)
|
| 216 |
+
except IllegalMoveException:
|
| 217 |
+
self._calculate_groups()
|
| 218 |
+
raise
|
| 219 |
+
with self._lock:
|
| 220 |
+
played_node = self.current_node.play(move)
|
| 221 |
+
self.current_node = played_node
|
| 222 |
+
return played_node
|
| 223 |
+
|
| 224 |
+
# Insert a list of moves from root, often just adding one.
|
| 225 |
+
def sync_branch(self, moves: List[Move]):
|
| 226 |
+
node = self.root
|
| 227 |
+
with self._lock:
|
| 228 |
+
for move in moves:
|
| 229 |
+
node = node.play(move)
|
| 230 |
+
return node
|
| 231 |
+
|
| 232 |
+
def set_current_node(self, node):
|
| 233 |
+
self.current_node = node
|
| 234 |
+
self._calculate_groups()
|
| 235 |
+
|
| 236 |
+
def undo(self, n_times=1, stop_on_mistake=None):
|
| 237 |
+
break_on_branch = False
|
| 238 |
+
cn = self.current_node # avoid race conditions
|
| 239 |
+
break_on_main_branch = False
|
| 240 |
+
last_branching_node = cn
|
| 241 |
+
if n_times == "branch":
|
| 242 |
+
n_times = 9999
|
| 243 |
+
break_on_branch = True
|
| 244 |
+
elif n_times == "main-branch":
|
| 245 |
+
n_times = 9999
|
| 246 |
+
break_on_main_branch = True
|
| 247 |
+
for move in range(n_times):
|
| 248 |
+
if (
|
| 249 |
+
stop_on_mistake is not None
|
| 250 |
+
and cn.points_lost is not None
|
| 251 |
+
and cn.points_lost >= stop_on_mistake
|
| 252 |
+
and self.katrain.players_info[cn.player].player_type != PLAYER_AI
|
| 253 |
+
):
|
| 254 |
+
self.set_current_node(cn.parent)
|
| 255 |
+
return
|
| 256 |
+
previous_cn = cn
|
| 257 |
+
if cn.shortcut_from:
|
| 258 |
+
cn = cn.shortcut_from
|
| 259 |
+
elif not cn.is_root:
|
| 260 |
+
cn = cn.parent
|
| 261 |
+
else:
|
| 262 |
+
break # root
|
| 263 |
+
if break_on_branch and len(cn.children) > 1:
|
| 264 |
+
break
|
| 265 |
+
elif break_on_main_branch and cn.ordered_children[0] != previous_cn: # implies > 1 child
|
| 266 |
+
last_branching_node = cn
|
| 267 |
+
if break_on_main_branch:
|
| 268 |
+
cn = last_branching_node
|
| 269 |
+
if cn is not self.current_node:
|
| 270 |
+
self.set_current_node(cn)
|
| 271 |
+
|
| 272 |
+
def redo(self, n_times=1, stop_on_mistake=None):
|
| 273 |
+
cn = self.current_node # avoid race conditions
|
| 274 |
+
for move in range(n_times):
|
| 275 |
+
if cn.children:
|
| 276 |
+
child = cn.ordered_children[0]
|
| 277 |
+
shortcut_to = [m for m, v in cn.shortcuts_to if child == v] # are we about to go to a shortcut node?
|
| 278 |
+
if shortcut_to:
|
| 279 |
+
child = shortcut_to[0]
|
| 280 |
+
cn = child
|
| 281 |
+
if (
|
| 282 |
+
move > 0
|
| 283 |
+
and stop_on_mistake is not None
|
| 284 |
+
and cn.points_lost is not None
|
| 285 |
+
and cn.points_lost >= stop_on_mistake
|
| 286 |
+
and self.katrain.players_info[cn.player].player_type != PLAYER_AI
|
| 287 |
+
):
|
| 288 |
+
self.set_current_node(cn.parent)
|
| 289 |
+
return
|
| 290 |
+
if stop_on_mistake is None:
|
| 291 |
+
self.set_current_node(cn)
|
| 292 |
+
|
| 293 |
+
@property
|
| 294 |
+
def komi(self):
|
| 295 |
+
return self.root.komi
|
| 296 |
+
|
| 297 |
+
@property
|
| 298 |
+
def board_size(self):
|
| 299 |
+
return self.root.board_size
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def stones(self):
|
| 303 |
+
with self._lock:
|
| 304 |
+
return sum(self.chains, [])
|
| 305 |
+
|
| 306 |
+
@property
|
| 307 |
+
def end_result(self):
|
| 308 |
+
if self.current_node.end_state:
|
| 309 |
+
return self.current_node.end_state
|
| 310 |
+
if self.current_node.parent and self.current_node.is_pass and self.current_node.parent.is_pass:
|
| 311 |
+
return self.manual_score or i18n._("board-game-end")
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def prisoner_count(
|
| 315 |
+
self,
|
| 316 |
+
) -> Dict: # returns prisoners that are of a certain colour as {B: black stones captures, W: white stones captures}
|
| 317 |
+
return {player: sum([m.player == player for m in self.prisoners]) for player in Move.PLAYERS}
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def rules(self):
|
| 321 |
+
return KataGoEngine.get_rules(self.root.ruleset)
|
| 322 |
+
|
| 323 |
+
@property
|
| 324 |
+
def manual_score(self):
|
| 325 |
+
rules = self.rules
|
| 326 |
+
if (
|
| 327 |
+
not self.current_node.ownership
|
| 328 |
+
or str(rules).lower() not in ["jp", "japanese"]
|
| 329 |
+
or not self.current_node.parent
|
| 330 |
+
or not self.current_node.parent.ownership
|
| 331 |
+
):
|
| 332 |
+
if not self.current_node.score:
|
| 333 |
+
return None
|
| 334 |
+
return self.current_node.format_score(round(2 * self.current_node.score) / 2) + "?"
|
| 335 |
+
board_size_x, board_size_y = self.board_size
|
| 336 |
+
mean_ownership = [(c + p) / 2 for c, p in zip(self.current_node.ownership, self.current_node.parent.ownership)]
|
| 337 |
+
ownership_grid = var_to_grid(mean_ownership, (board_size_x, board_size_y))
|
| 338 |
+
stones = {m.coords: m.player for m in self.stones}
|
| 339 |
+
lo_threshold = 0.15
|
| 340 |
+
hi_threshold = 0.85
|
| 341 |
+
max_unknown = 10
|
| 342 |
+
max_dame = 4 * (board_size_x + board_size_y)
|
| 343 |
+
|
| 344 |
+
def japanese_score_square(square, owner):
|
| 345 |
+
player = stones.get(square, None)
|
| 346 |
+
if (
|
| 347 |
+
(player == "B" and owner > hi_threshold)
|
| 348 |
+
or (player == "W" and owner < -hi_threshold)
|
| 349 |
+
or abs(owner) < lo_threshold
|
| 350 |
+
):
|
| 351 |
+
return 0 # dame or own stones
|
| 352 |
+
if player is None and abs(owner) >= hi_threshold:
|
| 353 |
+
return round(owner) # surrounded empty intersection
|
| 354 |
+
if (player == "B" and owner < -hi_threshold) or (player == "W" and owner > hi_threshold):
|
| 355 |
+
return 2 * round(owner) # captured stone
|
| 356 |
+
return math.nan # unknown!
|
| 357 |
+
|
| 358 |
+
scored_squares = [
|
| 359 |
+
japanese_score_square((x, y), ownership_grid[y][x])
|
| 360 |
+
for y in range(board_size_y)
|
| 361 |
+
for x in range(board_size_x)
|
| 362 |
+
]
|
| 363 |
+
num_sq = {t: sum([s == t for s in scored_squares]) for t in [-2, -1, 0, 1, 2]}
|
| 364 |
+
num_unkn = sum(math.isnan(s) for s in scored_squares)
|
| 365 |
+
prisoners = self.prisoner_count
|
| 366 |
+
score = sum([t * n for t, n in num_sq.items()]) + prisoners["W"] - prisoners["B"] - self.komi
|
| 367 |
+
self.katrain.log(
|
| 368 |
+
f"Manual Scoring: {num_sq} score by square with {num_unkn} unknown, {prisoners} captures, and {self.komi} komi -> score = {score}",
|
| 369 |
+
OUTPUT_DEBUG,
|
| 370 |
+
)
|
| 371 |
+
if num_unkn > max_unknown or (num_sq[0] - len(stones)) > max_dame:
|
| 372 |
+
return None
|
| 373 |
+
return self.current_node.format_score(score)
|
| 374 |
+
|
| 375 |
+
def __repr__(self):
|
| 376 |
+
return (
|
| 377 |
+
"\n".join("".join(self.chains[c][0].player if c >= 0 else "-" for c in line) for line in self.board)
|
| 378 |
+
+ f"\ncaptures: {self.prisoner_count}"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
def update_root_properties(self):
|
| 382 |
+
def player_name(player_info):
|
| 383 |
+
if player_info.name and player_info.player_type == PLAYER_HUMAN:
|
| 384 |
+
return player_info.name
|
| 385 |
+
else:
|
| 386 |
+
return f"{i18n._(player_info.player_type)} ({i18n._(player_info.player_subtype)}){SGF_INTERNAL_COMMENTS_MARKER}"
|
| 387 |
+
|
| 388 |
+
root_properties = self.root.properties
|
| 389 |
+
x_properties = {}
|
| 390 |
+
for bw in "BW":
|
| 391 |
+
if not self.external_game:
|
| 392 |
+
x_properties["P" + bw] = player_name(self.katrain.players_info[bw])
|
| 393 |
+
player_info = self.katrain.players_info[bw]
|
| 394 |
+
if player_info.player_type == PLAYER_AI:
|
| 395 |
+
x_properties[bw + "R"] = rank_label(player_info.calculated_rank)
|
| 396 |
+
if "+" in str(self.end_result):
|
| 397 |
+
x_properties["RE"] = self.end_result
|
| 398 |
+
self.root.properties = {**root_properties, **{k: [v] for k, v in x_properties.items()}}
|
| 399 |
+
|
| 400 |
+
def generate_filename(self):
|
| 401 |
+
self.update_root_properties()
|
| 402 |
+
player_names = {
|
| 403 |
+
bw: re.sub(r"[\u200b\u3164'<>:\"/\\|?*]", "", self.root.get_property("P" + bw, bw)) for bw in "BW"
|
| 404 |
+
}
|
| 405 |
+
base_game_name = f"{PROGRAM_NAME}_{player_names['B']} vs {player_names['W']}"
|
| 406 |
+
return f"{base_game_name} {self.game_id}.sgf"
|
| 407 |
+
|
| 408 |
+
def write_sgf(self, filename: str, trainer_config: Optional[Dict] = None):
|
| 409 |
+
if trainer_config is None:
|
| 410 |
+
trainer_config = self.katrain.config("trainer", {})
|
| 411 |
+
save_feedback = trainer_config.get("save_feedback", False)
|
| 412 |
+
eval_thresholds = trainer_config["eval_thresholds"]
|
| 413 |
+
save_analysis = trainer_config.get("save_analysis", False)
|
| 414 |
+
save_marks = trainer_config.get("save_marks", False)
|
| 415 |
+
self.update_root_properties()
|
| 416 |
+
show_dots_for = {
|
| 417 |
+
bw: trainer_config.get("eval_show_ai", True) or self.katrain.players_info[bw].human for bw in "BW"
|
| 418 |
+
}
|
| 419 |
+
sgf = self.root.sgf(
|
| 420 |
+
save_comments_player=show_dots_for,
|
| 421 |
+
save_comments_class=save_feedback,
|
| 422 |
+
eval_thresholds=eval_thresholds,
|
| 423 |
+
save_analysis=save_analysis,
|
| 424 |
+
save_marks=save_marks,
|
| 425 |
+
)
|
| 426 |
+
self.sgf_filename = filename
|
| 427 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 428 |
+
with open(filename, "w", encoding="utf-8") as f:
|
| 429 |
+
f.write(sgf)
|
| 430 |
+
return i18n._("sgf written").format(file_name=filename)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class Game(BaseGame):
|
| 434 |
+
"""Extensions related to analysis etc."""
|
| 435 |
+
|
| 436 |
+
def __init__(
|
| 437 |
+
self,
|
| 438 |
+
katrain,
|
| 439 |
+
engine: Union[Dict, KataGoEngine],
|
| 440 |
+
move_tree: GameNode = None,
|
| 441 |
+
analyze_fast=False,
|
| 442 |
+
game_properties: Optional[Dict] = None,
|
| 443 |
+
sgf_filename=None,
|
| 444 |
+
):
|
| 445 |
+
super().__init__(
|
| 446 |
+
katrain=katrain, move_tree=move_tree, game_properties=game_properties, sgf_filename=sgf_filename
|
| 447 |
+
)
|
| 448 |
+
if not isinstance(engine, Dict):
|
| 449 |
+
engine = {"B": engine, "W": engine}
|
| 450 |
+
self.engines = engine
|
| 451 |
+
|
| 452 |
+
self.insert_mode = False
|
| 453 |
+
self.insert_after = None
|
| 454 |
+
self.region_of_interest = None
|
| 455 |
+
|
| 456 |
+
threading.Thread(
|
| 457 |
+
target=lambda: self.analyze_all_nodes(analyze_fast=analyze_fast, even_if_present=False),
|
| 458 |
+
daemon=True,
|
| 459 |
+
).start() # return faster, but bypass Kivy Clock
|
| 460 |
+
|
| 461 |
+
def analyze_all_nodes(self, priority=PRIORITY_GAME_ANALYSIS, analyze_fast=False, even_if_present=True):
|
| 462 |
+
for node in self.root.nodes_in_tree:
|
| 463 |
+
# forced, or not present, or something went wrong in loading
|
| 464 |
+
if even_if_present or not node.analysis_from_sgf or not node.load_analysis():
|
| 465 |
+
node.clear_analysis()
|
| 466 |
+
node.analyze(self.engines[node.next_player], priority=priority, analyze_fast=analyze_fast)
|
| 467 |
+
|
| 468 |
+
def set_current_node(self, node):
|
| 469 |
+
if self.insert_mode:
|
| 470 |
+
self.katrain.controls.set_status(i18n._("finish inserting before navigating"), STATUS_ERROR)
|
| 471 |
+
return
|
| 472 |
+
super().set_current_node(node)
|
| 473 |
+
|
| 474 |
+
def undo(self, n_times=1, stop_on_mistake=None):
|
| 475 |
+
if self.insert_mode: # in insert mode, undo = delete
|
| 476 |
+
cn = self.current_node # avoid race conditions
|
| 477 |
+
if n_times == 1 and cn not in self.insert_after.nodes_from_root:
|
| 478 |
+
cn.parent.children = [c for c in cn.parent.children if c != cn]
|
| 479 |
+
self.current_node = cn.parent
|
| 480 |
+
self._calculate_groups()
|
| 481 |
+
return
|
| 482 |
+
super().undo(n_times=n_times, stop_on_mistake=stop_on_mistake)
|
| 483 |
+
|
| 484 |
+
def reset_current_analysis(self):
|
| 485 |
+
cn = self.current_node
|
| 486 |
+
engine = self.engines[cn.next_player]
|
| 487 |
+
engine.terminate_queries(cn)
|
| 488 |
+
cn.clear_analysis()
|
| 489 |
+
cn.analyze(engine)
|
| 490 |
+
|
| 491 |
+
def redo(self, n_times=1, stop_on_mistake=None):
|
| 492 |
+
if self.insert_mode:
|
| 493 |
+
return
|
| 494 |
+
super().redo(n_times=n_times, stop_on_mistake=stop_on_mistake)
|
| 495 |
+
|
| 496 |
+
def set_insert_mode(self, mode):
|
| 497 |
+
if mode == "toggle":
|
| 498 |
+
mode = not self.insert_mode
|
| 499 |
+
if mode == self.insert_mode:
|
| 500 |
+
return
|
| 501 |
+
self.insert_mode = mode
|
| 502 |
+
if mode:
|
| 503 |
+
children = self.current_node.ordered_children
|
| 504 |
+
if not children:
|
| 505 |
+
self.insert_mode = False
|
| 506 |
+
else:
|
| 507 |
+
self.insert_after = self.current_node.ordered_children[0]
|
| 508 |
+
self.katrain.controls.set_status(i18n._("starting insert mode"), STATUS_INFO)
|
| 509 |
+
else:
|
| 510 |
+
copy_from_node = self.insert_after
|
| 511 |
+
copy_to_node = self.current_node
|
| 512 |
+
num_copied = 0
|
| 513 |
+
if copy_to_node != self.insert_after.parent:
|
| 514 |
+
above_insertion_root = self.insert_after.parent.nodes_from_root
|
| 515 |
+
already_inserted_moves = [
|
| 516 |
+
n.move for n in copy_to_node.nodes_from_root if n not in above_insertion_root and n.move
|
| 517 |
+
]
|
| 518 |
+
try:
|
| 519 |
+
while True:
|
| 520 |
+
for m in copy_from_node.move_with_placements:
|
| 521 |
+
if m not in already_inserted_moves:
|
| 522 |
+
self._validate_move_and_update_chains(m, True)
|
| 523 |
+
# this inserts
|
| 524 |
+
copy_to_node = GameNode(
|
| 525 |
+
parent=copy_to_node, properties=copy.deepcopy(copy_from_node.properties)
|
| 526 |
+
)
|
| 527 |
+
num_copied += 1
|
| 528 |
+
if not copy_from_node.children:
|
| 529 |
+
break
|
| 530 |
+
copy_from_node = copy_from_node.ordered_children[0]
|
| 531 |
+
except IllegalMoveException:
|
| 532 |
+
pass # illegal move = stop
|
| 533 |
+
self._calculate_groups() # recalculate groups
|
| 534 |
+
self.katrain.controls.set_status(
|
| 535 |
+
i18n._("ending insert mode").format(num_copied=num_copied), STATUS_INFO
|
| 536 |
+
)
|
| 537 |
+
self.analyze_all_nodes(analyze_fast=True, even_if_present=False)
|
| 538 |
+
else:
|
| 539 |
+
self.katrain.controls.set_status("", STATUS_INFO)
|
| 540 |
+
self.katrain.controls.move_tree.insert_node = self.insert_after if self.insert_mode else None
|
| 541 |
+
self.katrain.controls.move_tree.redraw()
|
| 542 |
+
self.katrain.update_state(redraw_board=True)
|
| 543 |
+
|
| 544 |
+
# Play a Move from the current position, raise IllegalMoveException if invalid.
|
| 545 |
+
def play(self, move: Move, ignore_ko: bool = False, analyze=True):
|
| 546 |
+
played_node = super().play(move, ignore_ko)
|
| 547 |
+
if analyze:
|
| 548 |
+
if self.region_of_interest:
|
| 549 |
+
played_node.analyze(self.engines[played_node.next_player], analyze_fast=True)
|
| 550 |
+
played_node.analyze(self.engines[played_node.next_player], region_of_interest=self.region_of_interest)
|
| 551 |
+
else:
|
| 552 |
+
played_node.analyze(self.engines[played_node.next_player])
|
| 553 |
+
return played_node
|
| 554 |
+
|
| 555 |
+
def set_region_of_interest(self, region_of_interest):
|
| 556 |
+
x1, x2, y1, y2 = region_of_interest
|
| 557 |
+
xmin, xmax = min(x1, x2), max(x1, x2)
|
| 558 |
+
ymin, ymax = min(y1, y2), max(y1, y2)
|
| 559 |
+
szx, szy = self.board_size
|
| 560 |
+
if not (xmin == xmax and ymin == ymax) and not (xmax - xmin + 1 >= szx and ymax - ymin + 1 >= szy):
|
| 561 |
+
self.region_of_interest = [xmin, xmax, ymin, ymax]
|
| 562 |
+
else:
|
| 563 |
+
self.region_of_interest = None
|
| 564 |
+
self.katrain.controls.set_status("", OUTPUT_INFO)
|
| 565 |
+
|
| 566 |
+
def analyze_extra(self, mode, **kwargs):
|
| 567 |
+
stones = {s.coords for s in self.stones}
|
| 568 |
+
cn = self.current_node
|
| 569 |
+
|
| 570 |
+
if mode == "stop":
|
| 571 |
+
self.katrain.pondering = False
|
| 572 |
+
for e in set(self.engines.values()):
|
| 573 |
+
e.stop_pondering()
|
| 574 |
+
e.terminate_queries()
|
| 575 |
+
return
|
| 576 |
+
|
| 577 |
+
engine = self.engines[cn.next_player]
|
| 578 |
+
|
| 579 |
+
if mode == "ponder":
|
| 580 |
+
cn.analyze(
|
| 581 |
+
engine,
|
| 582 |
+
ponder=True,
|
| 583 |
+
priority=PRIORITY_EXTRA_ANALYSIS,
|
| 584 |
+
region_of_interest=self.region_of_interest,
|
| 585 |
+
time_limit=False,
|
| 586 |
+
)
|
| 587 |
+
return
|
| 588 |
+
|
| 589 |
+
if mode == "extra":
|
| 590 |
+
visits = cn.analysis_visits_requested + engine.config["max_visits"]
|
| 591 |
+
self.katrain.controls.set_status(i18n._("extra analysis").format(visits=visits), STATUS_ANALYSIS)
|
| 592 |
+
cn.analyze(
|
| 593 |
+
engine,
|
| 594 |
+
visits=visits,
|
| 595 |
+
priority=PRIORITY_EXTRA_ANALYSIS,
|
| 596 |
+
region_of_interest=self.region_of_interest,
|
| 597 |
+
time_limit=False,
|
| 598 |
+
)
|
| 599 |
+
return
|
| 600 |
+
|
| 601 |
+
if mode == "game":
|
| 602 |
+
nodes = self.root.nodes_in_tree
|
| 603 |
+
only_mistakes = kwargs.get("mistakes_only", False)
|
| 604 |
+
move_range = kwargs.get("move_range", None)
|
| 605 |
+
if move_range:
|
| 606 |
+
if move_range[1] < move_range[0]:
|
| 607 |
+
move_range = reversed(move_range)
|
| 608 |
+
threshold = self.katrain.config("trainer/eval_thresholds")[-4]
|
| 609 |
+
if "visits" in kwargs:
|
| 610 |
+
visits = kwargs["visits"]
|
| 611 |
+
else:
|
| 612 |
+
min_visits = min(node.analysis_visits_requested for node in nodes)
|
| 613 |
+
visits = min_visits + engine.config["max_visits"]
|
| 614 |
+
for node in nodes:
|
| 615 |
+
max_point_loss = max(c.points_lost or 0 for c in [node] + node.children)
|
| 616 |
+
if only_mistakes and max_point_loss <= threshold:
|
| 617 |
+
continue
|
| 618 |
+
if move_range and (not node.depth - 1 in range(move_range[0], move_range[1] + 1)):
|
| 619 |
+
continue
|
| 620 |
+
node.analyze(engine, visits=visits, priority=-1_000_000, time_limit=False, report_every=None)
|
| 621 |
+
if not move_range:
|
| 622 |
+
self.katrain.controls.set_status(i18n._("game re-analysis").format(visits=visits), STATUS_ANALYSIS)
|
| 623 |
+
else:
|
| 624 |
+
self.katrain.controls.set_status(
|
| 625 |
+
i18n._("move range analysis").format(
|
| 626 |
+
start_move=move_range[0], end_move=move_range[1], visits=visits
|
| 627 |
+
),
|
| 628 |
+
STATUS_ANALYSIS,
|
| 629 |
+
)
|
| 630 |
+
return
|
| 631 |
+
|
| 632 |
+
elif mode == "sweep":
|
| 633 |
+
board_size_x, board_size_y = self.board_size
|
| 634 |
+
|
| 635 |
+
if cn.analysis_exists:
|
| 636 |
+
policy_grid = (
|
| 637 |
+
var_to_grid(self.current_node.policy, size=(board_size_x, board_size_y))
|
| 638 |
+
if self.current_node.policy
|
| 639 |
+
else None
|
| 640 |
+
)
|
| 641 |
+
analyze_moves = sorted(
|
| 642 |
+
[
|
| 643 |
+
Move(coords=(x, y), player=cn.next_player)
|
| 644 |
+
for x in range(board_size_x)
|
| 645 |
+
for y in range(board_size_y)
|
| 646 |
+
if (policy_grid is None and (x, y) not in stones) or policy_grid[y][x] >= 0
|
| 647 |
+
],
|
| 648 |
+
key=lambda mv: -policy_grid[mv.coords[1]][mv.coords[0]],
|
| 649 |
+
)
|
| 650 |
+
else:
|
| 651 |
+
analyze_moves = [
|
| 652 |
+
Move(coords=(x, y), player=cn.next_player)
|
| 653 |
+
for x in range(board_size_x)
|
| 654 |
+
for y in range(board_size_y)
|
| 655 |
+
if (x, y) not in stones
|
| 656 |
+
]
|
| 657 |
+
visits = engine.config["fast_visits"]
|
| 658 |
+
self.katrain.controls.set_status(i18n._("sweep analysis").format(visits=visits), STATUS_ANALYSIS)
|
| 659 |
+
priority = PRIORITY_SWEEP
|
| 660 |
+
elif mode in ["equalize", "alternative", "local"]:
|
| 661 |
+
if not cn.analysis_complete and mode != "local":
|
| 662 |
+
self.katrain.controls.set_status(i18n._("wait-before-extra-analysis"), STATUS_INFO, self.current_node)
|
| 663 |
+
return
|
| 664 |
+
if mode == "alternative": # also do a quick update on current candidates so it doesn't look too weird
|
| 665 |
+
self.katrain.controls.set_status(i18n._("alternative analysis"), STATUS_ANALYSIS)
|
| 666 |
+
cn.analyze(engine, priority=PRIORITY_ALTERNATIVES, time_limit=False, find_alternatives="alternative")
|
| 667 |
+
visits = engine.config["fast_visits"]
|
| 668 |
+
else: # equalize
|
| 669 |
+
visits = max(d["visits"] for d in cn.analysis["moves"].values())
|
| 670 |
+
self.katrain.controls.set_status(i18n._("equalizing analysis").format(visits=visits), STATUS_ANALYSIS)
|
| 671 |
+
priority = PRIORITY_EQUALIZE
|
| 672 |
+
analyze_moves = [Move.from_gtp(gtp, player=cn.next_player) for gtp, _ in cn.analysis["moves"].items()]
|
| 673 |
+
else:
|
| 674 |
+
raise ValueError("Invalid analysis mode")
|
| 675 |
+
|
| 676 |
+
for move in analyze_moves:
|
| 677 |
+
if cn.analysis["moves"].get(move.gtp(), {"visits": 0})["visits"] < visits:
|
| 678 |
+
cn.analyze(
|
| 679 |
+
engine, priority=priority, visits=visits, refine_move=move, time_limit=False
|
| 680 |
+
) # explicitly requested so take as long as you need
|
| 681 |
+
|
| 682 |
+
def selfplay(self, until_move, target_b_advantage=None):
|
| 683 |
+
cn = self.current_node
|
| 684 |
+
|
| 685 |
+
if target_b_advantage is not None:
|
| 686 |
+
analysis_kwargs = {"visits": max(25, self.katrain.config("engine/fast_visits"))}
|
| 687 |
+
engine_settings = {"wideRootNoise": 0.03}
|
| 688 |
+
else:
|
| 689 |
+
analysis_kwargs = engine_settings = {}
|
| 690 |
+
|
| 691 |
+
def set_analysis(node, result):
|
| 692 |
+
node.set_analysis(result)
|
| 693 |
+
analyze_and_play(node)
|
| 694 |
+
|
| 695 |
+
def request_analysis_for_node(node):
|
| 696 |
+
self.engines[node.player].request_analysis(
|
| 697 |
+
node,
|
| 698 |
+
callback=lambda result, _partial: set_analysis(node, result),
|
| 699 |
+
priority=PRIORITY_DEFAULT,
|
| 700 |
+
analyze_fast=True,
|
| 701 |
+
extra_settings=engine_settings,
|
| 702 |
+
**analysis_kwargs,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
def analyze_and_play(node):
|
| 706 |
+
nonlocal cn, engine_settings
|
| 707 |
+
candidates = node.candidate_moves
|
| 708 |
+
if self.katrain.game is not self:
|
| 709 |
+
return # a new game happened
|
| 710 |
+
ai_thoughts = "Move generated by AI self-play\n"
|
| 711 |
+
if until_move != "end" and target_b_advantage is not None: # setup pos
|
| 712 |
+
if node.depth >= until_move or candidates[0]["move"] == "pass":
|
| 713 |
+
self.set_current_node(node)
|
| 714 |
+
return
|
| 715 |
+
target_score = cn.score + (node.depth - cn.depth + 1) * (target_b_advantage - cn.score) / (
|
| 716 |
+
until_move - cn.depth
|
| 717 |
+
)
|
| 718 |
+
max_loss = 5
|
| 719 |
+
stddev = min(3, 0.5 + (until_move - node.depth) * 0.15)
|
| 720 |
+
ai_thoughts += f"Selecting moves aiming at score {target_score:.1f} +/- {stddev:.2f} with < {max_loss} points lost\n"
|
| 721 |
+
if abs(node.score - target_score) < 3 * stddev:
|
| 722 |
+
weighted_cands = [
|
| 723 |
+
(
|
| 724 |
+
move,
|
| 725 |
+
math.exp(-0.5 * (abs(move["scoreLead"] - target_score) / stddev) ** 2)
|
| 726 |
+
* math.exp(-0.5 * (min(0, move["pointsLost"]) / max_loss) ** 2),
|
| 727 |
+
)
|
| 728 |
+
for i, move in enumerate(candidates)
|
| 729 |
+
if move["pointsLost"] < max_loss or i == 0
|
| 730 |
+
]
|
| 731 |
+
move_info = weighted_selection_without_replacement(weighted_cands, 1)[0][0]
|
| 732 |
+
for move, wt in weighted_cands:
|
| 733 |
+
self.katrain.log(
|
| 734 |
+
f"{'* ' if move_info == move else ' '} {move['move']} {move['scoreLead']} {wt}",
|
| 735 |
+
OUTPUT_EXTRA_DEBUG,
|
| 736 |
+
)
|
| 737 |
+
ai_thoughts += f"Move option: {move['move']} score {move['scoreLead']:.2f} loss {move['pointsLost']:.2f} weight {wt:.3e}\n"
|
| 738 |
+
else: # we're a bit lost, far away from target, just push it closer
|
| 739 |
+
move_info = min(candidates, key=lambda move: abs(move["scoreLead"] - target_score))
|
| 740 |
+
self.katrain.log(
|
| 741 |
+
f"* Played {move_info['move']} {move_info['scoreLead']} because score deviation between current score {node.score} and target score {target_score} > {3*stddev}",
|
| 742 |
+
OUTPUT_EXTRA_DEBUG,
|
| 743 |
+
)
|
| 744 |
+
ai_thoughts += f"Move played to close difference between score {node.score:.1f} and target {target_score:.1f} quickly."
|
| 745 |
+
|
| 746 |
+
self.katrain.log(
|
| 747 |
+
f"Self-play until {until_move} target {target_b_advantage}: {len(candidates)} candidates -> move {move_info['move']} score {move_info['scoreLead']} point loss {move_info['pointsLost']}",
|
| 748 |
+
OUTPUT_DEBUG,
|
| 749 |
+
)
|
| 750 |
+
move = Move.from_gtp(move_info["move"], player=node.next_player)
|
| 751 |
+
elif candidates: # just selfplay to end
|
| 752 |
+
move = Move.from_gtp(candidates[0]["move"], player=node.next_player)
|
| 753 |
+
else: # 1 visit etc
|
| 754 |
+
polmoves = node.policy_ranking
|
| 755 |
+
move = polmoves[0][1] if polmoves else Move(None)
|
| 756 |
+
if move.is_pass:
|
| 757 |
+
if self.current_node == cn:
|
| 758 |
+
self.set_current_node(node)
|
| 759 |
+
return
|
| 760 |
+
new_node = GameNode(parent=node, move=move)
|
| 761 |
+
new_node.ai_thoughts = ai_thoughts
|
| 762 |
+
if until_move != "end" and target_b_advantage is not None:
|
| 763 |
+
self.set_current_node(new_node)
|
| 764 |
+
self.katrain.controls.set_status(
|
| 765 |
+
i18n._("setup game status message").format(move=new_node.depth, until_move=until_move),
|
| 766 |
+
STATUS_INFO,
|
| 767 |
+
)
|
| 768 |
+
else:
|
| 769 |
+
if node != cn:
|
| 770 |
+
node.remove_shortcut()
|
| 771 |
+
cn.add_shortcut(new_node)
|
| 772 |
+
|
| 773 |
+
self.katrain.controls.move_tree.redraw_tree_trigger()
|
| 774 |
+
request_analysis_for_node(new_node)
|
| 775 |
+
|
| 776 |
+
request_analysis_for_node(cn)
|
| 777 |
+
|
| 778 |
+
def analyze_undo(self, node):
|
| 779 |
+
train_config = self.katrain.config("trainer")
|
| 780 |
+
move = node.move
|
| 781 |
+
if node != self.current_node or node.auto_undo is not None or not node.analysis_complete or not move:
|
| 782 |
+
return
|
| 783 |
+
points_lost = node.points_lost
|
| 784 |
+
thresholds = train_config["eval_thresholds"]
|
| 785 |
+
num_undo_prompts = train_config["num_undo_prompts"]
|
| 786 |
+
i = 0
|
| 787 |
+
while i < len(thresholds) and points_lost < thresholds[i]:
|
| 788 |
+
i += 1
|
| 789 |
+
num_undos = num_undo_prompts[i] if i < len(num_undo_prompts) else 0
|
| 790 |
+
if num_undos == 0:
|
| 791 |
+
undo = False
|
| 792 |
+
elif num_undos < 1: # probability
|
| 793 |
+
undo = int(node.undo_threshold < num_undos) and len(node.parent.children) == 1
|
| 794 |
+
else:
|
| 795 |
+
undo = len(node.parent.children) <= num_undos
|
| 796 |
+
|
| 797 |
+
node.auto_undo = undo
|
| 798 |
+
if undo:
|
| 799 |
+
self.undo(1)
|
| 800 |
+
self.katrain.controls.set_status(
|
| 801 |
+
i18n._("teaching undo message").format(move=move.gtp(), points_lost=points_lost), STATUS_TEACHING
|
| 802 |
+
)
|
| 803 |
+
self.katrain.update_state()
|