miniosl

miniosl, facade as a Python module.

Many functions are imported from minioslcc implemented in C++20.

class miniosl.UI(init: str | BaseState | MiniRecord = '', *, prefer_text=None, default_format='usi')[source]

general interface for shogi state (State , board position + pieces in hand), enhanced with move history (MiniRecord) and other utilities

Parameters:
  • init – initial contents handled by load_record()

  • prefer_text – preference of state visualization

  • default_format – preference in __str__

make the initial state in shogi

>>> shogi = miniosl.UI()

or read csa/usi file (local or web)

>>> url = 'http://live4.computer-shogi.org/wcsc33/kifu/WCSC33+F7_1-900-5F+dlshogi+Ryfamate+20230505161013.csa'
>>> shogi = miniosl.UI(url)
>>> _ = shogi.go(10)
>>> print(shogi.to_csa(), end='')
P1-KY-KE * -KI *  * -GI-KE-KY
P2 * -HI-GI * -OU * -KI-KA * 
P3-FU * -FU-FU-FU-FU-FU-FU-FU
P4 *  *  *  *  *  *  *  *  * 
P5 * -FU *  *  *  *  * +FU * 
P6+FU *  *  *  *  *  *  *  * 
P7 * +FU+FU+FU+FU+FU+FU * +FU
P8 * +KA+KI *  *  * +GI+HI * 
P9+KY+KE+GI * +OU+KI * +KE+KY
+
analyze()[source]

evaluate all positions in the current game

count_hand(color: Player, ptype: Ptype) int[source]

number of pieces in hand

eval(verbose=False) Tuple[ndarray, list][source]

return value and policy for current state.

need to call load_eval() in advance

first()[source]

go to the first state in the history

follow_opening(nth: int = 0)[source]

make a move following the opening db

game_play()[source]

make an interactive widget for playing in colab

genmove()[source]

generate legal moves in the state

genmove_check()[source]

generate legal moves giving check to the opponent

genmove_ja() list[str][source]

generate legal moves in Japanese

go(step)[source]

make moves (step > 0) or unmake moves (step < 0)

in_check()[source]

return whether king of the side to move is in check

in_checkmate()[source]

return whether king of the side to move is in checkmate

ipywidget()[source]

make an interactive widget for viewing record in colab

ipywidget_slider()[source]

make an interactive widget for colab or jupyter notebooks

last()[source]

go to the last state in the history

last_move() Move | None[source]

the last move played or None

last_to() Square | None[source]

the destination square of the last move or None

>>> shogi = miniosl.UI()
>>> shogi.last_to()
>>> _ = shogi.make_move('+2726FU')
>>> shogi.last_to() == miniosl.Square(2, 6)
True
load_eval(path: str = '', device: str = '', torch_cfg: dict = {})[source]

load parameters of evaluation function from file

parameters will be passed to inference.load().

load_opening_tree(filename)[source]

load opening db

load_record(src: str | BaseState | MiniRecord = '')[source]

load a game record from various sources.

Parameters:

srcBaseState or MiniRecord or URL or filepath containing .csa or usi.

load_record_set(path: str, idx: int)[source]

load idx-th game record in RecordSet

Parameters:

path – filepath for .npz generated by RecordSet.save_npz() or sfen text

make_move(move)[source]

make a move in the current state

make_opening_db_from_sfen(filename: str, threshold: int = 100)[source]

make opening tree from sfen records, and save in npz

mcts(budget: int = 100, report: int = 4, *, batch_size=1, resume_root=None)[source]

run mcts - budegt: number of simulations - report: number of (interim) report during search

opening_moves()[source]

retrieve or show opening moves.

Note: need to load data by load_opening_tree() in advance

previous_repeat_index() int[source]

the latest repeating state the history

pv_to_ja(pv: list[minioslcc.Move]) list[str][source]

show moves in Japanese

repeat_count() int[source]

number of occurrence of the state in the history

replay(idx: int, show_hint: bool = False)[source]

move to idx-th state in the history

show_features(plane_id: int | str, *args, **kwargs)[source]

visualize features in matplotlib.

Parameters:

plane_id'pieces' | 'hands' | 'lastmove' | 'long' | 'safety', or integer id (in internal representation)

show_top8_moves(verbose=False)[source]

suggest top8 moves by policy

to_anim(*args, **kwargs)[source]

make matplotlib animation showing current game record

to_csa() str[source]

show state in csa

to_img(*args, **kwargs)[source]

show state in matplotlib image

Returns:

an image shown in colab or jupyter notebooks

to_move(move_rep: str) Move[source]

interpret string as a Move

to_np_cover() array[source]

make planes to show a square is covered (1) or not (0)

to_np_pack() array[source]

compress state information

to_np_state_feature() array[source]

make tensor of feature for the current state (w/o history).

  • 44ch each 9x9 channel is responsible for a specific piece type and color - where each element is 1 (0) for existence (absent) of the piece for the first 30ch - filled by the same value indicating number of hand pieces for the latter 14ch

  • 13ch for heuristic features

to_usi() str[source]

show state in usi

to_usi_history() str[source]

show the history in usi

>>> shogi = miniosl.UI()
>>> _ = shogi.make_move('+2726FU')
>>> _ = shogi.make_move('-3334FU')
>>> shogi.to_usi()
'sfen lnsgkgsnl/1r5b1/pppppp1pp/6p2/9/7P1/PPPPPPP1P/1B5R1/LNSGKGSNL b - 1'
>>> shogi.to_usi_history()
'startpos moves 2g2f 3c3d'
turn() Player[source]

side to move

unmake_move()[source]

undo the last move

Training with torch

class miniosl.StandardNetwork(*, in_channels: int, channels: int, out_channels: int, auxout_channels: int, num_blocks: int, value_head_hidden: int = 256, broadcast_every: int = 3)[source]

Bases: PVNetwork

Standard residual networks with bottleneck architecture

Parameters:
  • in_channels – number of channels in input features,

  • channels – number of channels in main body,

  • out_channels – number of channels in policy_head,

  • auxout_channels – number of channels in miscellaneous output,

  • value_head_hidden – hidden units in the last layer in the value head

forward(x: Tensor) Tuple[Tensor, Tensor, Tensor][source]

take a batch of input features and return a batch of [policies, values, misc].

class miniosl.GameDataset(window_size: int, block_unit: int, batch_with_collate: bool = True)[source]

Bases: Dataset

dataset for training.

  • sample position by game index (a random position in the game record is returned)

  • keep the latest GameRecordBlock s (e.g., 50) as in MuZero

Parameters:
  • window_size – number of game records to keep

  • block_unit – number of game records for a block, that is a unit in add/replace oporation

  • batch_with_collate – need to specify collate_fn=lambda indices: dataset.collate(indices) for trainloader, if (and only if) True

add(new_block)[source]

add or replace the oldest one with new_block

block_id() int[source]

number of block added so far

collate(indices)[source]
make_block(compress_and_rm=True, strict=True)[source]

a helper function to make a block

reshape_item(item)[source]
sample_id(index)[source]
stored_game_records()[source]
unit_size() int[source]

number of records in a GameRecordBlock

Handle game records

see also Game record section, MiniRecord and RecordSet

miniosl.load_record_set(path: str, name: str = '', *, limit: int | None = None)[source]

load miniosl.RecordSet from npz file

Visualization

_images/shogi.png
miniosl.state_to_img(state: BaseState, *, decorate: bool = False, plane: ndarray | None = None, plane_color: str = 'orange', last_move_ja: str = '', last_to: Square | None = None, move_number: int = 0, repeat_distance: int = 0, repeat_count: int = 0, flip_if_white: bool = False, id: int = 4081) Figure[source]

make ShogiFig object including matplotlib figure as .fig

Parameters:
  • state – state,

  • decorate – highlight king location and piece covers for each color,

  • plane – 9x9 numpy array to make a mark on squares,

  • last_move_ja – last move in japanese,

  • last_to – the destination square of the last move,

  • move_number – ply in a game record,

  • repeat_distance – distance to the latest same position,

  • repeat_count – number of the occurrence of this state,

  • flip_if_whiterotate180() if white to move

class miniosl.ShogiFig(state: BaseState, last_move_ja: str = '', move_number: int = 0, id: int = 4081)[source]

data holding state and matplotlib objects

use self.fig for completed image.

make_move(move: Move | str)[source]

update board and figure

Use external engines

class miniosl.UsiProcess(path_and_args: list[str], setoptions: list[str] = ['setoption name Threads value 1', 'setoption name USI_Hash value 16'], cwd: str | None = None)[source]

Proxy for usi process

create process, initilaze its options and wait until readyok

Parameters:

path_and_args – list of path and argments

close() bool[source]

finish process

search(position: str, limit: str) dict[source]

search: give position with go commands, and wait bestmove

Returns hash contains “info”

Parameters:
  • position – e.g., 'startpos'

  • limit – e.g., 'byoyomi 1000'

class miniosl.UsiPlayer(engine: UsiProcess)[source]

bridge between usi engine and CPUPlayer for self-play with GameArray.

name(self: minioslcc.SingleCPUPlayer) str[source]
think(self: minioslcc.SingleCPUPlayer, arg0: str) minioslcc.Move[source]
class miniosl.CPUPlayer

adaptor for PlayerArray

Parameters:
  • player – object descendant of SingleCPUPlayer

  • greedy – indicating greedy behavior

Note

if you give a player implemented in Python, please make sure its lifetime

name(self: minioslcc.CPUPlayer) str