PGN to FEN (with Evaluation)?

Discussion of chess software programming and technical issues.

Moderator: Ras

matthewlai
Posts: 793
Joined: Sun Aug 03, 2014 4:48 am
Location: London, UK

Re: PGN to FEN (with Evaluation)?

Post by matthewlai »

This should do it:

Code: Select all

#!/usr/bin/env python3

import chess
import sys

from chess import pgn

def PrintNode(gameNode):
	if len(gameNode.variations) > 0:
		print(gameNode.board().epd(sm = gameNode.variations[0].move, c0 = gameNode.variations[0].comment))
	else:
		print(gameNode.board().epd())

if len(sys.argv) != 2:
	print("Usage: " + sys.argv[0] + " <PGN file>")
	sys.exit(1)

if sys.argv[1] == '-':
    pgn = sys.stdin
else:
    pgn = open(sys.argv[1])

game = chess.pgn.read_game(pgn)
while game != None:
	
	gameNode = game
	while len(gameNode.variations):
		PrintNode(gameNode)
		gameNode = gameNode.variations[0]
    
	# for the last node (no variations)
	PrintNode(gameNode)
        
	game = chess.pgn.read_game(pgn)

Code: Select all

sudo pip3 install python-chess
python3 pgn2epd.py input.pgn > output.epd
If you are processing very large files and performance matters, you'll probably want to grab the latest version of the python-chess library from github. I submitted a patch last week that makes it much faster.
Disclosure: I work for DeepMind on the AlphaZero project, but everything I say here is personal opinion and does not reflect the views of DeepMind / Alphabet.
User avatar
Steve Maughan
Posts: 1262
Joined: Wed Mar 08, 2006 8:28 pm
Location: Florida, USA

Re: PGN to FEN (with Evaluation)?

Post by Steve Maughan »

HI Matthew,

Python Chess Library - it sounds fantastic! It may just be a good enough reason to dip my toe in the waters of Python.

Many thanks!

Steve
http://www.chessprogramming.net - Maverick Chess Engine
Jesse Gersenson
Posts: 593
Joined: Sat Aug 20, 2011 9:43 am

Re: PGN to FEN (with Evaluation)?

Post by Jesse Gersenson »

pgn-extract can convert a pgn to epd/fen. Here is the help file:
http://www.cs.kent.ac.uk/people/staff/d ... /help.html

Here's a start in bash:

Code: Select all

~$ pgn-extract -Wepd test.pgn |cut -d' ' -f1,2,3,4>tmp

Code: Select all

#!/bin/bash
while read p; do
motor=maverick
fen="position fen $p" 
echo $p
(echo "$fen";sleep 0.01;echo 'go depth 47'; sleep 1;echo 'quit';)|./$motor|grep "cp "|tail -1|sed 's/.*cp //g'|sed 's/ nps.*//g';
done <tmp
Outputs the fen and score in cp:
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -
37
rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq -
-22
rnbqkbnr/pp1ppppp/8/2p5/8/5N2/PPPPPPPP/RNBQKB1R w KQkq c6
38
...