repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
Ludii
|
Ludii-master/Player/src/app/views/players/PlayerView.java
|
package app.views.players;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import app.PlayerApp;
import app.utils.SettingsExhibition;
import app.views.View;
import game.Game;
import other.context.Context;
import util.PlaneType;
//-----------------------------------------------------------------------------
/**
* View area containing all specific player views
*
* @author Matthew.Stephenson and cambolbro and Eric.Piette
*/
public class PlayerView extends View
{
/** Player areas/sections/pages. */
public List<PlayerViewUser> playerSections = new ArrayList<>();
/** Font. */
public Font playerNameFont = new Font("Arial", Font.PLAIN, 16);
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public PlayerView(final PlayerApp app, final boolean portraitMode, final boolean exhibitionMode)
{
super(app);
playerSections.clear();
final Game game = app.contextSnapshot().getContext(app).game();
final int numPlayers = game.players().count();
final int maxHandHeight = 100; // Maximum height of a player's hand.
final double maxPanelPercentageHeight = 0.7; // Maximum height of the entire panel (as percentage of app height).
int boardSize = app.height();
if (SettingsExhibition.exhibitionVersion)
boardSize = app.getPanels().get(0).placement().width; // Allows for custom board sizes.
int startX = boardSize + 8;
int startY = 8;
int width = app.width() - boardSize;
int height = Math.min(maxHandHeight, (int)(app.height()*maxPanelPercentageHeight/numPlayers));
if (SettingsExhibition.exhibitionVersion)
{
startY += 40;
}
if (app.manager().isWebApp() && portraitMode && numPlayers <= 4)
playerNameFont = new Font("Arial", Font.PLAIN, 32);
if (portraitMode)
{
boardSize = app.width();
startX = 8;
startY = app.manager().isWebApp() ? boardSize + 88 : boardSize + 48; // +40 for the height of the toolView, +80 on mobile
width = boardSize - 8;
height = Math.min(maxHandHeight, (int)((app.height() - boardSize)*maxPanelPercentageHeight/numPlayers));
}
if (exhibitionMode)
{
for (int pid = 1; pid <= numPlayers; pid++)
{
final int x0 = startX + 5;
int y0 = 75;
if (pid == 2)
y0 = 600;
width = 600;
height = 150;
final Rectangle place = new Rectangle(x0, y0, width, (int) (height * 0.7));
final PlayerViewUser playerPage = new PlayerViewUser(app, place, pid, this);
app.getPanels().add(playerPage);
playerSections.add(playerPage);
}
}
else
{
// create a specific user page for each player.
for (int pid = 1; pid <= numPlayers; pid++)
{
final int x0 = startX;
final int y0 = startY + (pid-1) * height;
final Rectangle place = new Rectangle(x0, y0, width, height);
final PlayerViewUser playerPage = new PlayerViewUser(app, place, pid, this);
app.getPanels().add(playerPage);
playerSections.add(playerPage);
}
}
// create the shared player pages (if it exists)
if (app.contextSnapshot().getContext(app).hasSharedPlayer())
{
Rectangle place = new Rectangle(0, 0, boardSize, boardSize/10);
// Place the shared hand in different location for exhibition app.
if (app.settingsPlayer().usingMYOGApp())
{
//place = new Rectangle(415, 280, 180, 130); // last argument changes piece size
place = new Rectangle(360, 280, 180, 130); // last argument changes piece size
}
if (SettingsExhibition.exhibitionVersion)
{
if (app.contextSnapshot().getContext(app).game().name().contains("Senet"))
place = new Rectangle(0, 90, boardSize, boardSize/7);
else
place = new Rectangle(0, -90, boardSize, boardSize/7);
}
final PlayerViewShared naturePlayerPage = new PlayerViewShared(app, place, numPlayers + 1, this);
app.getPanels().add(naturePlayerPage);
playerSections.add(naturePlayerPage);
}
final int playerPanelWidth = app.width() - boardSize;
final int playerPanelHeight = numPlayers * height + 24;
placement.setBounds(boardSize, 0, playerPanelWidth, playerPanelHeight);
}
//-------------------------------------------------------------------------
/**
* Draw player details and hand/dice/deck of the player.
* @param g2d
*/
@Override
public void paint(final Graphics2D g2d)
{
for (final PlayerViewUser p : playerSections)
p.paint(g2d);
paintDebug(g2d, Color.PINK);
}
//-------------------------------------------------------------------------
/**
* Get the Maximum width of all player names (including extras).
*/
public int maximalPlayerNameWidth(final Context context, final Graphics2D g2d)
{
int numUsers = playerSections.size();
if (app.contextSnapshot().getContext(app).hasSharedPlayer())
numUsers -= 1;
int maxNameWidth = 0;
for (int panelIndex = 0; panelIndex < numUsers; panelIndex++)
{
final String stringNameAndExtras = playerSections.get(panelIndex).getNameAndExtrasString(context, g2d);
final Rectangle2D bounds = playerNameFont.getStringBounds(stringNameAndExtras, g2d.getFontRenderContext());
maxNameWidth = Math.max((int) bounds.getWidth(), maxNameWidth);
}
return maxNameWidth;
}
//-------------------------------------------------------------------------
public void paintHand(final Graphics2D g2d, final Context context, final Rectangle place, final int handIndex)
{
app.bridge().getContainerStyle(handIndex).setPlacement(context, place);
if (app.settingsPlayer().showPieces())
app.bridge().getContainerStyle(handIndex).draw(g2d, PlaneType.COMPONENTS, context);
app.bridge().getContainerStyle(handIndex).draw(g2d, PlaneType.INDICES, context);
app.bridge().getContainerStyle(handIndex).draw(g2d, PlaneType.POSSIBLEMOVES, context);
}
}
| 5,903 | 31.262295 | 124 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/players/PlayerViewShared.java
|
package app.views.players;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import app.PlayerApp;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Panel showing the Shared pieces
*
* @author Matthew.Stephenson and cambolbro and Eric.Piette
*/
public class PlayerViewShared extends PlayerViewUser
{
/**
* Constructor.
*/
public PlayerViewShared(final PlayerApp app, final Rectangle rect, final int pid, final PlayerView playerView)
{
super(app, rect, pid, playerView);
}
//-------------------------------------------------------------------------
@Override
public void paint(final Graphics2D g2d)
{
// Add border around shared hand for exhibition app.
// if (app.settingsPlayer().usingExhibitionApp() && app.manager().ref().context().board().numSites() > 1)
// {
// g2d.setColor(Color.WHITE);
// g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER));
// g2d.fillRoundRect(350, placement.y+30, placement.width+5, placement.height-60, 40, 40);
// }
if (hand != null)
{
final Context context = app.contextSnapshot().getContext(app);
final Rectangle containerPlacement = new Rectangle((placement.x), placement.y - placement.height/2, (placement.width), placement.height);
playerView.paintHand(g2d, context, containerPlacement, hand.index());
}
paintDebug(g2d, Color.ORANGE);
}
//-------------------------------------------------------------------------
}
| 1,539 | 27.518519 | 140 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/players/PlayerViewUser.java
|
package app.views.players;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import app.PlayerApp;
import app.utils.GUIUtil;
import app.utils.SVGUtil;
import app.utils.SettingsExhibition;
import app.utils.Spinner;
import app.views.View;
import game.Game;
import game.equipment.Equipment;
import game.equipment.container.Container;
import game.functions.ints.IntFunction;
import game.types.state.GameType;
import graphics.svg.SVGtoImage;
import manager.ai.AIUtil;
import metadata.graphics.util.ScoreDisplayInfo;
import metadata.graphics.util.WhenScoreType;
import metadata.graphics.util.colour.ColourRoutines;
import other.AI;
import other.context.Context;
import other.model.SimultaneousMove;
//-----------------------------------------------------------------------------
/**
* Panel showing a specific player's status and details.
*
* @author Matthew.Stephenson and cambolbro and Eric.Piette
*/
public class PlayerViewUser extends View
{
/** Player index: 1, 2, ... 0 is shared. */
protected int playerId = 0;
/** PlayerView object that generated this UserView. */
public PlayerView playerView;
/** Container associated with this view. */
Container hand = null;
/** Store a spinner for this player, to represent if an AI is thinking about a move for it. */
public Spinner spinner = null;
protected static Color moverTextColour = new Color(50, 50, 50);
protected static Color nonMoverTextColour = new Color(215, 215, 215);
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public PlayerViewUser(final PlayerApp app, final Rectangle rect, final int pid, final PlayerView playerView)
{
super(app);
this.playerView = playerView;
playerId = pid;
determineHand(app.contextSnapshot().getContext(app).equipment());
placement = rect;
if (SettingsExhibition.exhibitionVersion)
{
if (SettingsExhibition.exhibitionVersion)
{
placement.y += 30 * playerId;
}
moverTextColour = new Color(220,220,220);
nonMoverTextColour = new Color(100,100,100);
this.playerView.playerNameFont = new Font("Arial", Font.PLAIN, 30);
}
}
//-------------------------------------------------------------------------
@Override
public void paint(final Graphics2D g2d)
{
final Context context = app.contextSnapshot().getContext(app);
final int mover = context.state().mover();
final ArrayList<Integer> winnerNumbers = getWinnerNumbers(context);
int componentPushBufferX = 0;
if (!app.settingsPlayer().usingMYOGApp())
{
drawColourSwatch(g2d, mover, winnerNumbers, context);
drawPlayerName(g2d, mover, winnerNumbers, context);
if (!SettingsExhibition.exhibitionVersion)
drawAIFace(g2d);
final int swatchWidth = app.playerSwatchList()[playerId].width;
final int maxNameWidth = playerView.maximalPlayerNameWidth(context, g2d);
componentPushBufferX = (int) (swatchWidth + maxNameWidth + app.playerNameList()[playerId].getHeight()*2);
if (AIUtil.anyAIPlayer(app.manager()))
componentPushBufferX += playerView.playerNameFont.getSize()*3;
}
if (hand != null)
{
final int containerMarginWidth = (int) (0.05 * placement.height);
final Rectangle containerPlacement = new Rectangle(
placement.x + componentPushBufferX + containerMarginWidth,
placement.y - placement.height/2,
placement.width - componentPushBufferX - containerMarginWidth*2,
placement.height
);
playerView.paintHand(g2d, context, containerPlacement, hand.index());
}
if (!SettingsExhibition.exhibitionVersion)
drawAISpinner(g2d, context);
paintDebug(g2d, Color.RED);
}
//-------------------------------------------------------------------------
/**
* Draw Swatch showing player number and colour.
*/
private void drawColourSwatch(final Graphics2D g2d, final int mover, final ArrayList<Integer> winnerNumbers, final Context context)
{
g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
final int discR = (int)(0.275 * placement.height);
final int cx = placement.x + discR;
final int cy = placement.y + placement.height / 2;
final Color fillColour = app.bridge().settingsColour().playerColour(context, playerId);
final boolean fullColour =
app.contextSnapshot().getContext(app).trial().over() && winnerNumbers.contains(Integer.valueOf(playerId))
||
!app.contextSnapshot().getContext(app).trial().over() && playerId == mover
||
SettingsExhibition.exhibitionVersion;
final int fcr = fillColour.getRed();
final int fcg = fillColour.getGreen();
final int fcb = fillColour.getBlue();
// Draw a coloured ring around the swatch if network game to represent player is online/offline
if (app.manager().settingsNetwork().getActiveGameId() != 0)
{
Color markerColour = Color.RED;
if (app.manager().settingsNetwork().onlinePlayers()[playerId] == true)
{
markerColour = Color.GREEN;
}
g2d.setColor(markerColour);
g2d.fillArc(cx-discR-4, cy-discR-4, discR*2+8, discR*2+8, 0, 360);
}
// Draw faint outline
if (fullColour)
g2d.setColor(new Color(63, 63, 63));
else
g2d.setColor(new Color(215, 215, 215));
g2d.fillArc(cx-discR-2, cy-discR-2, discR*2+4, discR*2+4, 0, 360);
if (app.playerSwatchHover()[playerId])
{
// Draw faded colour
final int rr = fcr + (int) ((255 - fcr) * 0.5);
final int gg = fcg + (int) ((255 - fcg) * 0.5);
final int bb = fcb + (int) ((255 - fcb) * 0.5);
g2d.setColor(new Color(rr, gg, bb));
}
else
{
if (fullColour)
{
g2d.setColor(fillColour);
}
else
{
// Draw faded colour
final int rr = fcr + (int) ((255 - fcr) * 0.75);
final int gg = fcg + (int) ((255 - fcg) * 0.75);
final int bb = fcb + (int) ((255 - fcb) * 0.75);
g2d.setColor(new Color(rr, gg, bb));
}
}
g2d.fillArc(cx-discR, cy-discR, discR*2, discR*2, 0, 360);
if (app.playerSwatchHover()[playerId])
{
g2d.setColor(new Color(150, 150, 150));
}
else
{
if (playerId == mover || app.contextSnapshot().getContext(app).model() instanceof SimultaneousMove)
g2d.setColor(moverTextColour);
else
g2d.setColor(nonMoverTextColour);
}
// Draw the player number
final Font oldFont = g2d.getFont();
final Font indexFont = new Font("Arial", Font.BOLD, (int)(1.0 * discR));
g2d.setFont(indexFont);
final String str = "" + playerId;
final Rectangle2D bounds = indexFont.getStringBounds(str, g2d.getFontRenderContext());
final int tx = cx - (int)(0.5 * bounds.getWidth());
final int ty = cy + (int)(0.3 * bounds.getHeight()) + 1;
final Color contrastColour = ColourRoutines.getContrastColorFavourLight(fillColour);
if (fullColour)
g2d.setColor(contrastColour);
else
g2d.setColor(new Color(Math.max(contrastColour.getRed(), 215), Math.max(contrastColour.getGreen(), 215), Math.max(contrastColour.getBlue(), 215)));
g2d.drawString(str, tx, ty);
g2d.setFont(oldFont);
// Indicate if player is no longer active in game
final boolean gameOver = context.trial().over();
if (!context.active(playerId) && !gameOver)
{
// Player not active -- strike through
g2d.setColor(new Color(255, 255, 255));
g2d.setStroke(new BasicStroke(7, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2d.drawLine(cx-20, cy-20, cx+20, cy+20);
g2d.drawLine(cx-20, cy+20, cx+20, cy-20);
}
app.playerSwatchList()[playerId] = new Rectangle(cx-discR, cy-discR, discR*2, discR*2);
}
//-------------------------------------------------------------------------
/**
* Draws the player's name.
*/
private void drawPlayerName(final Graphics2D g2d, final int mover, final ArrayList<Integer> winnerNumbers, final Context context)
{
g2d.setFont(playerView.playerNameFont);
final String stringNameAndExtras = getNameAndExtrasString(context, g2d);
final Rectangle2D bounds = playerView.playerNameFont.getStringBounds(stringNameAndExtras, g2d.getFontRenderContext());
final Rectangle2D square = app.playerSwatchList()[playerId];
final Point2D drawPosn = new Point2D.Double(square.getCenterX() + square.getWidth(), square.getCenterY());
// Determine name and comboBox placement
final int strNameY = (int) (drawPosn.getY() + bounds.getHeight()/3);
final int strNameX = (int) drawPosn.getX();
// Determine the colour of the player name
if (!context.trial().over() || !winnerNumbers.contains(Integer.valueOf(playerId)))
{
if (app.playerNameHover()[playerId])
{
g2d.setColor(new Color(150, 150, 150));
}
else
{
if (playerId == mover || app.contextSnapshot().getContext(app).model() instanceof SimultaneousMove)
g2d.setColor(moverTextColour);
else
g2d.setColor(nonMoverTextColour);
}
}
else
{
// Show winner
g2d.setColor(Color.red);
}
final Rectangle NameAndExtrasBounds = bounds.getBounds();
NameAndExtrasBounds.x = strNameX;
NameAndExtrasBounds.y = (int) (strNameY - bounds.getHeight());
app.playerNameList()[playerId] = NameAndExtrasBounds;
if (SettingsExhibition.exhibitionVersion)
{
try(InputStream in = getClass().getResourceAsStream("/National-Regular.ttf"))
{
g2d.setFont(Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(32f));
}
catch (final Exception e)
{
e.printStackTrace();
}
}
g2d.drawString(stringNameAndExtras, strNameX, strNameY);
}
//-------------------------------------------------------------------------
/**
* Draw AI face with expression showing positional estimate.
*/
void drawAIFace(final Graphics2D g2d)
{
final AI ai = app.manager().aiSelected()[app.manager().playerToAgent(playerId)].ai();
if (ai != null)
{
final double happinessValue = ai.estimateValue();
String imagePath = "/svg/faces/symbola_cool.svg";
if (happinessValue < -0.8)
imagePath = "/svg/faces/symbola_sad.svg";
else if (happinessValue < -0.5)
imagePath = "/svg/faces/symbola_scared.svg";
else if (happinessValue < -0.2)
imagePath = "/svg/faces/symbola_worried.svg";
else if (happinessValue < 0.2)
imagePath = "/svg/faces/symbola_neutral.svg";
else if (happinessValue < 0.5)
imagePath = "/svg/faces/symbola_pleased.svg";
else if (happinessValue < 0.8)
imagePath = "/svg/faces/symbola_happy.svg";
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(imagePath))))
{
final Rectangle2D nameRect = app.playerNameList()[playerId];
final double r = playerView.playerNameFont.getSize();
final SVGGraphics2D svg = new SVGGraphics2D((int)r, (int) r);
SVGtoImage.loadFromReader(svg, reader, new Rectangle2D.Double(0,0,r,r), Color.BLACK, Color.WHITE, 0);
final Point2D drawPosn = new Point2D.Double(nameRect.getX() + nameRect.getWidth() + g2d.getFont().getSize()/5, nameRect.getCenterY() - g2d.getFont().getSize()/5);
g2d.drawImage(SVGUtil.createSVGImage(svg.getSVGDocument(), (int) r, (int) r), (int) drawPosn.getX(), (int) drawPosn.getY(), null);
reader.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Start the spinner for each AI that is thinking/moving.
*/
private void drawAISpinner(final Graphics2D g2d, final Context context)
{
if (app.manager().isWebApp())
return;
if (app.settingsPlayer().usingMYOGApp())
{
//System.out.println("Creating spinner...");
if (spinner == null)
spinner = new Spinner(new Rectangle2D.Double(905, 335, 100, 100));
spinner.setDotRadius(4);
}
else
{
final Rectangle2D nameRect = app.playerNameList()[playerId];
final double r = playerView.playerNameFont.getSize();
final Point2D drawPosn = new Point2D.Double(nameRect.getX() + nameRect.getWidth() + r + 15, nameRect.getCenterY() - 3);
if (SettingsExhibition.exhibitionVersion)
drawPosn.setLocation(drawPosn.getX() + 30, drawPosn.getY());
if (spinner == null || drawPosn.getX() != spinner.originalRect().getX())
spinner = new Spinner(new Rectangle2D.Double(drawPosn.getX(),drawPosn.getY(), r, r));
}
if (spinner != null)
{
// if (context.state().mover() == playerId)
// {
// System.out.println("Mover menu name is: " + app.manager().aiSelected()[app.manager().playerToAgent(playerId)].menuItemName() );
// System.out.println("liveAIs is: " + app.manager().liveAIs());
// }
if
(
context.state().mover() == playerId
&&
!app.manager().aiSelected()[app.manager().playerToAgent(playerId)].menuItemName().equals("Human")
&&
app.manager().liveAIs() != null
&&
!app.manager().liveAIs().isEmpty()
)
spinner.startSpinner();
else
spinner.stopSpinner();
}
spinner.drawSpinner(g2d);
}
//-------------------------------------------------------------------------
/**
* Check if the mouse position is over any items that have hover colours
*/
@Override
public void mouseOverAt(final Point pixel)
{
// Check if mouse is over player swatch.
for (int i = 0; i < app.playerSwatchList().length; i++)
{
final Rectangle rectangle = app.playerSwatchList()[i];
final boolean overlap = GUIUtil.pointOverlapsRectangle(pixel, rectangle);
if (app.playerSwatchHover()[i] != overlap)
{
app.playerSwatchHover()[i] = overlap;
app.repaint(rectangle.getBounds());
}
}
// Check if mouse is over player name.
for (int i = 0; i < app.playerNameList().length; i++)
{
final Rectangle rectangle = app.playerNameList()[i];
final boolean overlap = GUIUtil.pointOverlapsRectangle(pixel, rectangle);
if (app.playerNameHover()[i] != overlap)
{
app.playerNameHover()[i] = overlap;
app.repaint(rectangle.getBounds());
}
}
}
//-------------------------------------------------------------------------
/**
* Gets the complete string to be printed for this player, including name, score, algorithm, etc.
*/
@SuppressWarnings("unused")
public String getNameAndExtrasString(final Context context, final Graphics2D g2d)
{
final Context instanceContext = context.currentInstanceContext();
final Game instance = instanceContext.game();
final int playerIndex = app.manager().playerToAgent(playerId);
final Font playerNameFont = g2d.getFont();
String strName = app.manager().aiSelected()[playerIndex].name();
// if Metadata overrides this, then include this metadata name.
final String metadataName = context.game().metadata().graphics().playerName(context, playerIndex);
if (metadataName != null)
strName += " (" + metadataName + ")";
// Assemble the extra details string with scores etc.
String strExtras = "";
String strAIName = "";
if (app.manager().aiSelected()[playerIndex].ai() != null)
strAIName += " (" + app.manager().aiSelected()[playerIndex].ai().friendlyName() + ") ";
if (app.manager().aiSelected()[playerIndex].ai() != null && SettingsExhibition.exhibitionVersion)
{
strName = "AI";
strAIName = "";
}
// Score
final ScoreDisplayInfo scoreDisplayInfo = instance.metadata().graphics().scoreDisplayInfo(instanceContext, playerId);
if (scoreDisplayInfo.scoreReplacement() != null)
{
if
(
scoreDisplayInfo.showScore() == WhenScoreType.Always ||
(scoreDisplayInfo.showScore() == WhenScoreType.AtEnd && instanceContext.trial().over())
)
{
final IntFunction replacementScoreFunction = scoreDisplayInfo.scoreReplacement();
replacementScoreFunction.preprocess(instance);
final int replacementScore = replacementScoreFunction.eval(instanceContext);
strExtras += " (" + replacementScore;
}
}
else if ((instance.gameFlags() & GameType.Score) != 0L)
{
if
(
scoreDisplayInfo.showScore() == WhenScoreType.Always ||
(scoreDisplayInfo.showScore() == WhenScoreType.AtEnd && instanceContext.trial().over())
)
{
strExtras += " (" + instanceContext.score(playerId);
}
}
strExtras += scoreDisplayInfo.scoreSuffix();
if (context.isAMatch())
{
if (strExtras.equals(""))
strExtras += " (";
else
strExtras += " : ";
strExtras += context.score(playerId);
}
if (!strExtras.equals(""))
strExtras += ")";
if (app.contextSnapshot().getContext(app).game().requiresBet())
strExtras += " $" + context.state().amount(playerId);
if (app.contextSnapshot().getContext(app).game().requiresTeams())
strExtras += " Team " + app.contextSnapshot().getContext(app).state().getTeam(playerId);
if (app.manager().settingsNetwork().playerTimeRemaining()[app.manager().playerToAgent(playerId)-1] > 0)
strExtras += " Time: " + app.manager().settingsNetwork().playerTimeRemaining()[app.contextSnapshot().getContext(app).state().playerToAgent(playerId)-1] + "s";
strName += strAIName;
// cut string off at a specified pixel width
final int maxLengthPixels = g2d.getFont().getSize() > 20 ? 250 : 200; // More pixels allocated if font is large (i.e. Mobile)
String shortendedString = "";
for (int i = 0; i < strName.length(); i++)
{
shortendedString += strName.charAt(i);
final int stringWidth = (int) playerNameFont.getStringBounds(shortendedString, g2d.getFontRenderContext()).getWidth();
if (stringWidth > maxLengthPixels)
{
shortendedString = shortendedString.substring(0, i-2);
shortendedString += "...";
strName = shortendedString;
break;
}
}
return strName + strExtras;
}
//-------------------------------------------------------------------------
/**
* Returns all the players who are winners, can be multiple if a team game.
*/
private static ArrayList<Integer> getWinnerNumbers(final Context context)
{
final Game game = context.game();
final ArrayList<Integer> winnerNumbers = new ArrayList<>();
final int firstWinner = (context.trial().status() == null) ? 0 : context.trial().status().winner();
if (game.requiresTeams())
{
final int winningTeam = context.state().getTeam(firstWinner);
for (int i = 1; i < game.players().size(); i++)
if (context.state().getTeam(i) == winningTeam)
winnerNumbers.add(Integer.valueOf(i));
}
else
{
winnerNumbers.add(Integer.valueOf(firstWinner));
}
return winnerNumbers;
}
//-------------------------------------------------------------------------
/**
* Determine the hand container associated with this view.
*/
private void determineHand(final Equipment equipment)
{
for (int i = 0; i < equipment.containers().length; i++)
if (equipment.containers()[i].isHand())
if ((equipment.containers()[i]).owner() == playerId)
hand = equipment.containers()[i];
}
//-------------------------------------------------------------------------
@Override
public int containerIndex()
{
if (hand == null)
return -1;
return hand.index();
}
//-------------------------------------------------------------------------
/**
* @return Player index.
*/
public int playerId()
{
return playerId;
}
}
| 19,450 | 30.834697 | 167 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/ToolButton.java
|
package app.views.tools;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import app.PlayerApp;
import app.utils.SettingsExhibition;
import game.rules.play.moves.Moves;
import other.action.Action;
import other.context.Context;
import other.move.Move;
//-----------------------------------------------------------------------------
/**
* Tool panel button.
*
* @author Matthew.Stephenson and cambolbro
*/
public abstract class ToolButton
{
protected final PlayerApp app;
/** Button name. */
protected String name = "?";
/** Default Button colour. */
protected static Color buttonColour = new Color(50, 50, 50);
/** Rollover button colour */
protected static Color rolloverButtonColour = new Color(127, 127, 127);
/** Default grayed out / invalid Button colour. */
protected static Color invalidButtonColour = new Color(220,220,220);
/** Rectangle bounding box for button */
protected Rectangle rect = new Rectangle();
/** Whether or not a mouse is over the button */
protected boolean mouseOver = false;
/** Tooltip message for when cursor is over this button. */
protected String tooltipMessage = "Default Message";
protected int buttonIndex = -1;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param name
* @param cx
* @param cy
*/
public ToolButton(final PlayerApp app, final String name, final int cx, final int cy, final int sx, final int sy, final int buttonIndex)
{
this.app = app;
this.name = name;
this.buttonIndex = buttonIndex;
rect.x = cx;
rect.y = cy;
rect.width = sx;
rect.height = sy;
if (SettingsExhibition.exhibitionVersion)
{
buttonColour = new Color(220,220,220);
invalidButtonColour = new Color(100,100,100);
rect.width *= 2;
rect.height *= 2;
}
}
//-------------------------------------------------------------------------
/**
* @return Button name.
*/
public String name()
{
return name;
}
//-------------------------------------------------------------------------
/**
* @param x
* @param y
*/
public void setPosition(final int x, final int y)
{
rect.x = x;
rect.y = y;
}
/**
* Scale toolbar buttons depending on type of device.
* @return 2 for mobile device, 1 for everything else.
*/
public double scaleForDevice()
{
// Based on default toolbar height for desktop player of 32 pixels.
return rect.getHeight() / 32.0;
}
//-------------------------------------------------------------------------
/**
* @param g2d
*/
public abstract void draw(final Graphics2D g2d);
//-------------------------------------------------------------------------
/**
* Execute the button press.
*/
public abstract void press();
//-------------------------------------------------------------------------
/**
* @param x X screen pixel.
* @param y Y screen pixel.
* @return Whether the specified point hits this button.
*/
public boolean hit(final int x, final int y)
{
return (x >= rect.x) && (x <= rect.x + rect.width) && (y >= rect.y) && y <= (rect.y + rect.height);
}
//-------------------------------------------------------------------------
/**
* Set if the mouse if over the button.
*/
public void setMouseOver(final boolean b)
{
mouseOver = b;
}
/**
* If the mouse cursor is over the button.
*/
public boolean mouseOver()
{
return mouseOver;
}
/**
* The bounding box of the button.
*/
public Rectangle rect()
{
return rect;
}
/**
* The tooltip message when the cursor hovers over the button
*/
public String tooltipMessage()
{
return tooltipMessage;
}
/**
* If the button is enabled and can be pressed. True by default.
*/
@SuppressWarnings("static-method")
protected boolean isEnabled()
{
return true;
}
//-------------------------------------------------------------------------
/**
* Set temporary message to all legal actions.
*/
protected void showPossibleMovesTemporaryMessage()
{
final Context context = app.contextSnapshot().getContext(app);
final Moves legal = context.moves(context);
final ArrayList<String> allOtherMoveDescriptions = new ArrayList<String>();
for (final Move move : legal.moves())
{
for (int i = 0; i < move.actions().size(); i++)
{
if (move.actions().get(i).isDecision())
{
final Action decisionAction = move.actions().get(i);
final String desc = decisionAction.getDescription();
if (!allOtherMoveDescriptions.contains(desc))
allOtherMoveDescriptions.add(desc);
break;
}
}
}
if (allOtherMoveDescriptions.size() > 0)
{
String tempMessageString = "You may ";
if (legal.moves().size() == 1)
tempMessageString = "You must ";
for (final String s : allOtherMoveDescriptions)
tempMessageString += s + " or ";
tempMessageString = tempMessageString.substring(0, tempMessageString.length()-4);
tempMessageString += ".";
app.setTemporaryMessage(tempMessageString);
}
}
//-------------------------------------------------------------------------
/**
* The colour of the button.
*/
protected Color getButtonColour()
{
if (isEnabled())
{
if (mouseOver)
return rolloverButtonColour;
else
return buttonColour;
}
else
return invalidButtonColour;
}
}
| 5,370 | 21.567227 | 137 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/ToolView.java
|
package app.views.tools;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import app.PlayerApp;
import app.utils.GameUtil;
import app.utils.SettingsExhibition;
import app.views.View;
import app.views.tools.buttons.ButtonBack;
import app.views.tools.buttons.ButtonEnd;
import app.views.tools.buttons.ButtonForward;
import app.views.tools.buttons.ButtonInfo;
import app.views.tools.buttons.ButtonOther;
import app.views.tools.buttons.ButtonPass;
import app.views.tools.buttons.ButtonPlayPause;
import app.views.tools.buttons.ButtonQuit;
import app.views.tools.buttons.ButtonSettings;
import app.views.tools.buttons.ButtonShow;
import app.views.tools.buttons.ButtonStart;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.location.FullLocation;
import other.move.Move;
//-----------------------------------------------------------------------------
/**
* View showing the tool buttons.
* @author Matthew.Stephenson and cambolbro
*/
public class ToolView extends View
{
/** List of buttons. */
public List<ToolButton> buttons = new ArrayList<>();
/** Index values for each of the tool buttons, determines the order drawn from left to right. */
public static final int START_BUTTON_INDEX = 0;
public static final int BACK_BUTTON_INDEX = 1;
public static final int PLAY_BUTTON_INDEX = 2;
public static final int FORWARD_BUTTON_INDEX = 3;
public static final int END_BUTTON_INDEX = 4;
public static final int PASS_BUTTON_INDEX = 5;
public static final int OTHER_BUTTON_INDEX = 6;
public static final int SHOW_BUTTON_INDEX = 7;
public static final int SETTINGS_BUTTON_INDEX = 8;
public static final int INFO_BUTTON_INDEX = 9;
public static final int QUIT_BUTTON_INDEX = 10;
// WebApp only
// public static final int CYCLE_AI_INDEX = 8;
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public ToolView(final PlayerApp app, final boolean portraitMode)
{
super(app);
int toolHeight = 40;
if (portraitMode && app.manager().isWebApp())
toolHeight = 80;
int boardSize = app.height();
int startX = boardSize;
int startY = app.height() - toolHeight;
int width = app.width() - boardSize - toolHeight;
if (SettingsExhibition.exhibitionVersion)
{
startX = 450;
startY = 950;
}
if (portraitMode)
{
boardSize = app.width();
startX = 0;
startY = boardSize + 8;
width = app.width() - toolHeight;
}
placement.setBounds(startX, startY, width, toolHeight);
drawButtons(toolHeight);
}
//-------------------------------------------------------------------------
@SuppressWarnings("unused")
public void drawButtons(final int toolHeight)
{
int cx = placement.x;
final int cy = placement.y;
final int sx = placement.height - 8;
final int sy = placement.height - 8;
buttons.add(new ButtonStart(app, cx, cy, sx, sy, START_BUTTON_INDEX));
buttons.add(new ButtonBack(app, cx, cy, sx, sy, BACK_BUTTON_INDEX));
buttons.add(new ButtonPlayPause(app, cx, cy, sx, sy, PLAY_BUTTON_INDEX));
buttons.add(new ButtonForward(app, cx, cy, sx, sy, FORWARD_BUTTON_INDEX));
buttons.add(new ButtonEnd(app, cx, cy, sx, sy, END_BUTTON_INDEX));
buttons.add(new ButtonPass(app, cx, cy, sx, sy, PASS_BUTTON_INDEX));
if (!SettingsExhibition.exhibitionVersion)
{
if (otherButtonShown(app.manager().ref().context()))
buttons.add(new ButtonOther(app, cx, cy, sx, sy, OTHER_BUTTON_INDEX));
else
buttons.add(null);
buttons.add(new ButtonShow(app, cx, cy, sx, sy, SHOW_BUTTON_INDEX));
if (!app.manager().isWebApp())
{
buttons.add(new ButtonSettings(app, cx, cy, sx, sy, SETTINGS_BUTTON_INDEX));
buttons.add(new ButtonInfo(app, cx, cy, sx, sy, INFO_BUTTON_INDEX));
}
}
else
{
buttons.add(new ButtonQuit(app, cx, cy, sx, sy, QUIT_BUTTON_INDEX));
}
double spacing = placement.width / (double) buttons.size();
if (SettingsExhibition.exhibitionVersion)
spacing = 50;
for (int b = 0; b < buttons.size(); b++)
{
if (buttons.get(b) == null)
continue; // is spacer
cx = placement.x + (int) ((b + 0.25) * spacing) + 10;
buttons.get(b).setPosition(cx, cy);
// Don't show any buttons except the pass and reset buttons
if (SettingsExhibition.exhibitionVersion && buttons.get(b).buttonIndex != PASS_BUTTON_INDEX && buttons.get(b).buttonIndex != START_BUTTON_INDEX)
buttons.get(b).setPosition(-1000, -1000);
}
}
//-------------------------------------------------------------------------
@Override
public void paint(final Graphics2D g2d)
{
for (final ToolButton button : buttons)
if (button != null)
button.draw(g2d);
paintDebug(g2d, Color.BLUE);
}
//-------------------------------------------------------------------------
/**
* Handle click on tool panel.
* @param pixel
*/
public void clickAt(final Point pixel)
{
for (final ToolButton button : buttons)
if (button != null && button.hit(pixel.x, pixel.y))
button.press();
}
//-------------------------------------------------------------------------
@Override
public void mouseOverAt(final Point pixel)
{
// See if mouse is over any of the tool buttons
for (final ToolButton button : buttons)
{
if (button == null)
continue;
if (button.hit(pixel.x, pixel.y))
{
if (button.mouseOver() != true)
{
button.setMouseOver(true);
app.repaint(button.rect());
}
}
else
{
if (button.mouseOver() != false)
{
button.setMouseOver(false);
app.repaint(button.rect());
}
}
}
}
//-------------------------------------------------------------------------
public static void jumpToMove(final PlayerApp app, final int moveToJumpTo)
{
app.manager().settingsManager().setAgentsPaused(app.manager(), true);
app.settingsPlayer().setWebGameResultValid(false);
final Context context = app.manager().ref().context();
// Store the previous saved trial, and reload it after resetting the game.
final List<Move> allMoves = app.manager().ref().context().trial().generateCompleteMovesList();
allMoves.addAll(app.manager().undoneMoves());
GameUtil.resetGame(app, true);
app.manager().settingsManager().setAgentsPaused(app.manager(), true);
final int moveToJumpToWithSetup;
if (moveToJumpTo == 0)
moveToJumpToWithSetup = context.currentInstanceContext().trial().numInitialPlacementMoves();
else
moveToJumpToWithSetup = moveToJumpTo;
final List<Move> newDoneMoves = allMoves.subList(0, moveToJumpToWithSetup);
final List<Move> newUndoneMoves = allMoves.subList(moveToJumpToWithSetup, allMoves.size());
app.manager().ref().makeSavedMoves(app.manager(), newDoneMoves);
app.manager().setUndoneMoves(newUndoneMoves);
// this is just a tiny bit hacky, but makes sure MCTS won't reuse incorrect tree after going back in Trial
context.game().incrementGameStartCount();
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
GameUtil.resetUIVariables(app);
}
//-------------------------------------------------------------------------
/**
* @return If the Other button should be shown for this game.
*/
private static boolean otherButtonShown(final Context context)
{
if (context.game().booleanConcepts().get(Concept.BetDecision.id()))
return true;
if (context.game().booleanConcepts().get(Concept.VoteDecision.id()))
return true;
if (context.game().booleanConcepts().get(Concept.SetNextPlayer.id()))
return true;
if (context.game().booleanConcepts().get(Concept.ChooseTrumpSuitDecision.id()))
return true;
if (context.game().booleanConcepts().get(Concept.SwapOption.id()))
return true;
if (context.game().booleanConcepts().get(Concept.SwapOption.id()))
return true;
if (context.game().booleanConcepts().get(Concept.SwapPlayersDecision.id()))
return true;
if (context.game().booleanConcepts().get(Concept.ProposeDecision.id()))
return true;
return false;
}
//-------------------------------------------------------------------------
}
| 8,243 | 29.420664 | 147 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonBack.java
|
package app.views.tools.buttons;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.views.tools.ToolButton;
import app.views.tools.ToolView;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Settings button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonBack extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param backButtonIndex
*/
public ButtonBack(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int backButtonIndex)
{
super(app, "Back", cx, cy, sx, sy, backButtonIndex);
tooltipMessage = "Back a Move";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
g2d.setStroke(new BasicStroke((float)(3 * scale), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
final GeneralPath path = new GeneralPath();
path.moveTo(cx + 5 * scale, cy + 7 * scale);
path.lineTo(cx - 5 * scale, cy);
path.lineTo(cx + 5 * scale, cy - 7 * scale);
g2d.draw(path);
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
final Context context = app.manager().ref().context();
final int numInitialPlacementMoves = context.currentInstanceContext().trial().numInitialPlacementMoves();
if
(
(
context.currentSubgameIdx() > 1
||
context.trial().numMoves() > numInitialPlacementMoves
)
&&
app.manager().settingsNetwork().getActiveGameId() == 0
)
return true;
return false;
}
//-------------------------------------------------------------------------
@Override
// Goes back a single action in the trial
public void press()
{
if (isEnabled())
{
final Context context = app.manager().ref().context();
//context.game().undo(context);
ToolView.jumpToMove(app, context.trial().numMoves() - 1);
}
}
//-------------------------------------------------------------------------
}
| 2,548 | 25.010204 | 122 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonCycleAI.java
|
package app.views.tools.buttons;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
//import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.views.tools.ToolButton;
import main.Constants;
import manager.ai.AIUtil;
import other.location.FullLocation;
//-----------------------------------------------------------------------------
/**
* Cycle AI button.
*
* @author Matthew.Stephenson
*/
public class ButtonCycleAI extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param settingsButtonIndex
*/
public ButtonCycleAI(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int settingsButtonIndex)
{
super(app, "Cycle AI", cx, cy, sx, sy, settingsButtonIndex);
tooltipMessage = "Preferences";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final int cx = (int) rect.getCenterX();
final int cy = (int) rect.getCenterY();
g2d.setColor(getButtonColour());
final Font oldFont = g2d.getFont();
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
final int r = (int)(10 * scale);
g2d.fillArc(cx - r, cy - r, 2 * r + 1, 2 * r + 1, 0, 360);
final int fontSize = (int)(17 * scale);
final int flags = Font.ITALIC | Font.BOLD;
final Font font = new Font("Arial", flags, fontSize);
g2d.setFont(font);
g2d.setColor(Color.white);
g2d.drawString("c", cx - (int)(3 * scale), cy + (int)(6 * scale));
g2d.setFont(oldFont);
}
//-------------------------------------------------------------------------
@Override
// displays the settings popup
public void press()
{
AIUtil.cycleAgents(app.manager());
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
}
//-------------------------------------------------------------------------
}
| 2,155 | 25.95 | 129 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonEnd.java
|
package app.views.tools.buttons;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.utils.TrialUtil;
import app.views.tools.ToolButton;
import app.views.tools.ToolView;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Settings button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonEnd extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param sx
* @param sy
* @param endButtonIndex
*/
public ButtonEnd(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int endButtonIndex)
{
super(app, "End", cx, cy, sx, sy, endButtonIndex);
tooltipMessage = "Forward to End";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
g2d.setStroke(new BasicStroke((float)(3 * scale), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
GeneralPath path = new GeneralPath();
path.moveTo(cx - 10 * scale, cy + 7 * scale);
path.lineTo(cx, cy);
path.lineTo(cx - 10 * scale, cy - 7 * scale);
g2d.draw(path);
g2d.setStroke(new BasicStroke((float)(2 * scale), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
path = new GeneralPath();
path.moveTo(cx + 4 * scale, cy + 9 * scale);
path.lineTo(cx + 4 * scale, cy - 9 * scale);
g2d.draw(path);
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
if
(
app.manager().undoneMoves().size() > 0
&&
app.manager().settingsNetwork().getActiveGameId() == 0
)
return true;
return false;
}
//-------------------------------------------------------------------------
// Goes to the end (last) location of the match
@Override
public void press()
{
if (isEnabled())
{
Context context = app.manager().ref().context();
// Go forward one move first.
ToolView.jumpToMove(app, context.trial().numMoves() + 1);
context = app.manager().ref().context();
ToolView.jumpToMove(app, TrialUtil.getInstanceEndIndex(app.manager(), context));
}
}
//-------------------------------------------------------------------------
}
| 2,743 | 24.886792 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonForward.java
|
package app.views.tools.buttons;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.views.tools.ToolButton;
import app.views.tools.ToolView;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Settings button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonForward extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param forwardButtonIndex
*/
public ButtonForward(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int forwardButtonIndex)
{
super(app, "Forward", cx, cy, sx, sy, forwardButtonIndex);
tooltipMessage = "Forward a Move";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
g2d.setStroke(new BasicStroke((float)(3 * scale), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
final GeneralPath path = new GeneralPath();
path.moveTo(cx - 5 * scale, cy + 7 * scale);
path.lineTo(cx + 5 * scale, cy);
path.lineTo(cx - 5 * scale, cy - 7 * scale);
g2d.draw(path);
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
if
(
app.manager().undoneMoves().size() > 0
&&
app.manager().settingsNetwork().getActiveGameId() == 0
)
return true;
return false;
}
//-------------------------------------------------------------------------
@Override
// Goes forward a single action in the current trial
public void press()
{
if (isEnabled())
{
final Context context = app.manager().ref().context();
ToolView.jumpToMove(app, context.trial().numMoves() + 1);
}
}
//-------------------------------------------------------------------------
}
| 2,310 | 24.395604 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonInfo.java
|
package app.views.tools.buttons;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import app.PlayerApp;
import app.views.tools.ToolButton;
import main.Constants;
import other.location.FullLocation;
//-----------------------------------------------------------------------------
/**
* Settings button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonInfo extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param infoButtonIndex
*/
public ButtonInfo(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int infoButtonIndex)
{
super(app, "Info", cx, cy, sx, sy, infoButtonIndex);
tooltipMessage = "Info";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final int cx = (int) rect.getCenterX();
final int cy = (int) rect.getCenterY();
g2d.setColor(getButtonColour());
final Font oldFont = g2d.getFont();
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
final int r = (int)(10 * scale);
g2d.fillArc(cx - r, cy - r, 2 * r + 1, 2 * r + 1, 0, 360);
final int fontSize = (int)(17 * scale);
final int flags = Font.ITALIC | Font.BOLD;
final Font font = new Font("Arial", flags, fontSize);
g2d.setFont(font);
g2d.setColor(Color.white);
g2d.drawString("i", cx - (int)(3 * scale), cy + (int)(6 * scale));
g2d.setFont(oldFont);
}
//-------------------------------------------------------------------------
@Override
// displays the information popup
public void press()
{
app.showInfoDialog();
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
}
//-------------------------------------------------------------------------
}
| 2,060 | 25.766234 | 122 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonOther.java
|
package app.views.tools.buttons;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import app.PlayerApp;
import app.views.tools.ToolButton;
import game.rules.play.moves.Moves;
import main.collections.FastArrayList;
import other.context.Context;
import other.move.Move;
//-----------------------------------------------------------------------------
/**
* Generic button for "other" operations that don't have a button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonOther extends ToolButton
{
FastArrayList<Move> otherPossibleMoves = new FastArrayList<>();
//-------------------------------------------------------------------------
/**
* Constructor.
* @param otherButtonIndex
*/
public ButtonOther(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int otherButtonIndex)
{
super(app, "Other", cx, cy, sx, sy, otherButtonIndex);
tooltipMessage = "Miscellaneous";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
final double r = 2.75 * scale;
g2d.fill(new Ellipse2D.Double(cx-r, cy-r-9 * scale, 2*r, 2*r));
g2d.fill(new Ellipse2D.Double(cx-r, cy-r, 2*r, 2*r));
g2d.fill(new Ellipse2D.Double(cx-r, cy-r+9 * scale, 2*r, 2*r));
if (otherPossibleMoves.size() > 0)
showPossibleMovesTemporaryMessage();
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
otherPossibleMoves.clear();
final Context context = app.contextSnapshot().getContext(app);
final Moves legal = context.moves(context);
for (final Move m : legal.moves())
if (m.isOtherMove())
otherPossibleMoves.add(m);
if (otherPossibleMoves.size() > 0)
return true;
return false;
}
//-------------------------------------------------------------------------
// The user wants to either pass or indicate "end of turn".
@Override
public void press()
{
if (isEnabled())
app.showOtherDialog(otherPossibleMoves);
}
//-------------------------------------------------------------------------
}
| 2,508 | 26.571429 | 124 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonPass.java
|
package app.views.tools.buttons;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.move.MoveHandler;
import app.views.tools.ToolButton;
import game.rules.play.moves.Moves;
import other.context.Context;
import other.move.Move;
//-----------------------------------------------------------------------------
/**
* Pass button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonPass extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
* @param passButtonIndex
*/
public ButtonPass(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int passButtonIndex)
{
super(app, "Pass", cx, cy, sx, sy, passButtonIndex);
tooltipMessage = "Pass/End Move";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
//g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
final GeneralPath path = new GeneralPath();
path.moveTo( cx - 15 * scale, cy + 10 * scale);
path.curveTo(cx - 15 * scale, cy, cx - 8 * scale, cy - 7 * scale, cx + 2 * scale, cy - 7 * scale);
path.lineTo( cx, cy - 12 * scale);
path.lineTo( cx + 15 * scale, cy - 5 * scale);
path.lineTo( cx, cy + 2 * scale);
path.lineTo( cx + 2 * scale, cy - 3 * scale);
path.curveTo(cx - 7 * scale, cy - 3 * scale, cx - 13 * scale, cy + 6 * scale, cx - 15 * scale, cy + 10 * scale);
g2d.fill(path);
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
boolean canPass = false;
final Context context = app.contextSnapshot().getContext(app);
final Moves legal = context.moves(context);
for (final Move m : legal.moves())
{
if (m.isPass() && (app.manager().settingsNetwork().getNetworkPlayerNumber() == m.mover() || app.manager().settingsNetwork().getNetworkPlayerNumber() == 0))
canPass = true;
// If going from one game to the next in a match, use the pass button to trigger this.
if (m.containsNextInstance())
canPass = true;
}
// If going backwards in a trial and have no moves, then need to show the pass button.
// if (legal.moves().size() == 0 && !app.contextSnapshot().getContext(app).trial().over() && app.manager().undoneMoves().size() > 0)
// canPass = true;
if (canPass)
{
showPossibleMovesTemporaryMessage();
return true;
}
return false;
}
//-------------------------------------------------------------------------
// The user wants to either pass or indicate "end of turn".
@Override
public void press()
{
if (isEnabled())
{
MoveHandler.tryGameMove(app, null, null, true, -1);
}
}
//-------------------------------------------------------------------------
}
| 3,249 | 29.092593 | 158 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonPlayPause.java
|
package app.views.tools.buttons;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.views.tools.ToolButton;
import game.types.play.ModeType;
import main.Constants;
import manager.ai.AIUtil;
import other.location.FullLocation;
//-----------------------------------------------------------------------------
/**
* Play/Pause button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonPlayPause extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param playButtonIndex
*/
public ButtonPlayPause(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int playButtonIndex)
{
super(app, "PlayPause", cx, cy, sx, sy, playButtonIndex);
tooltipMessage = "Player/Pause";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
//g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
GeneralPath path = new GeneralPath();
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
if (app.manager().settingsManager().agentsPaused())
{
// Display Play Symbol
path.moveTo(cx + 9 * scale, cy);
path.lineTo(cx - 7 * scale, cy - 9 * scale);
path.lineTo(cx - 7 * scale, cy + 9 * scale);
g2d.fill(path);
}
else
{
// Display Pause Symbol
path.moveTo(cx - 7 * scale , cy + 9 * scale );
path.lineTo(cx - 7 * scale , cy - 9 * scale );
path.lineTo(cx - 2 * scale , cy - 9 * scale );
path.lineTo(cx - 2 * scale , cy + 9 * scale );
g2d.fill(path);
path = new GeneralPath();
path.moveTo(cx + 2 * scale , cy + 9 * scale );
path.lineTo(cx + 2 * scale , cy - 9 * scale );
path.lineTo(cx + 7 * scale , cy - 9 * scale );
path.lineTo(cx + 7 * scale , cy + 9 * scale );
g2d.fill(path);
}
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
if (app.manager().ref().context().game().mode().mode().equals(ModeType.Simulation))
return true;
if (AIUtil.anyAIPlayer(app.manager()) && (app.manager().settingsNetwork().getActiveGameId() == 0 || app.manager().settingsNetwork().getOnlineAIAllowed()))
return true;
return false;
}
//-------------------------------------------------------------------------
@Override
// Either pauses or resumes the agents playing the game
public void press()
{
if (isEnabled())
{
if (!app.manager().settingsManager().agentsPaused())
{
app.manager().settingsManager().setAgentsPaused(app.manager(), true);
}
else
{
app.manager().settingsManager().setAgentsPaused(app.manager(), false);
app.manager().ref().nextMove(app.manager(), false);
}
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
}
}
//-------------------------------------------------------------------------
}
| 3,324 | 27.418803 | 156 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonQuit.java
|
package app.views.tools.buttons;
import java.awt.Font;
import java.awt.Graphics2D;
import app.PlayerApp;
import app.views.tools.ToolButton;
//-----------------------------------------------------------------------------
/**
* Quit button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonQuit extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param quitButtonIndex
*/
public ButtonQuit(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int quitButtonIndex)
{
super(app, "Quit", cx, cy, sx, sy, quitButtonIndex);
tooltipMessage = "Quit";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final int cx = (int) rect.getCenterX();
final int cy = (int) rect.getCenterY() + 5;
g2d.setColor(getButtonColour());
final Font oldFont = g2d.getFont();
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
final int fontSize = (int)(26 * scale);
final int flags = Font.BOLD;
final Font font = new Font("Arial", flags, fontSize);
g2d.setFont(font);
g2d.setColor(getButtonColour());
g2d.drawString("X", cx - (int)(3 * scale), cy + (int)(6 * scale));
g2d.setFont(oldFont);
}
//-------------------------------------------------------------------------
@Override
// displays the information popup
public void press()
{
System.exit(0);
}
//-------------------------------------------------------------------------
}
| 1,775 | 24.371429 | 122 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonSettings.java
|
package app.views.tools.buttons;
import java.awt.Color;
import java.awt.Graphics2D;
//import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.views.tools.ToolButton;
import main.Constants;
import other.location.FullLocation;
//-----------------------------------------------------------------------------
/**
* Settings button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonSettings extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param settingsButtonIndex
*/
public ButtonSettings(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int settingsButtonIndex)
{
super(app, "Settings", cx, cy, sx, sy, settingsButtonIndex);
tooltipMessage = "Preferences";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final int cx = (int) rect.getCenterX();
final int cy = (int) rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
final int d = (int)(10 * scale);
final int dd = (int)(7 * scale);
g2d.drawLine(cx - d, cy, cx + d, cy);
g2d.drawLine(cx, cy - d, cx, cy + d);
g2d.drawLine(cx - dd, cy - dd, cx + dd, cy + dd);
g2d.drawLine(cx - dd, cy + dd, cx + dd, cy - dd);
final int r = 7;
g2d.fillArc(cx - r, cy - r, 2 * r + 1, 2 * r + 1, 0, 360);
final int rr = 3;
g2d.setColor(Color.white);
g2d.fillArc(cx - rr, cy - rr, 2 * rr + 1, 2 * rr + 1, 0, 360);
}
//-------------------------------------------------------------------------
@Override
// displays the settings popup
public void press()
{
app.showSettingsDialog();
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
}
//-------------------------------------------------------------------------
}
| 2,135 | 25.7 | 130 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonShow.java
|
package app.views.tools.buttons;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import app.PlayerApp;
import app.views.tools.ToolButton;
//-----------------------------------------------------------------------------
/**
* Show button.
*
* @author cambolbro and Matthew.Stephenson
*/
public class ButtonShow extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param infoButtonIndex
*/
public ButtonShow(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int infoButtonIndex)
{
super(app, "Show", cx, cy, sx, sy, infoButtonIndex);
tooltipMessage = "Show moves";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final int cx = (int) rect.getCenterX();
final int cy = (int) rect.getCenterY();
g2d.setColor(getButtonColour());
final Font oldFont = g2d.getFont();
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
final int r = (int)(10 * scale);
g2d.fillArc(cx - r, cy - r, 2 * r + 1, 2 * r + 1, 0, 360);
final int fontSize = (int)(17 * scale);
final int flags = Font.BOLD;
final Font font = new Font("Arial", flags, fontSize);
g2d.setFont(font);
g2d.setColor(Color.white);
final String str = "?";
final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(str, g2d);
final int tx = (int)(cx - bounds.getWidth() / 2 + 0 * scale);
final int ty = (int)(cy + bounds.getHeight() / 2 - 3 * scale);
g2d.drawString(str, tx, ty);
g2d.setFont(oldFont);
}
//-------------------------------------------------------------------------
// Toggles the "Show Legal Moves" setting on/off.
@Override
public void press()
{
app.bridge().settingsVC().setShowPossibleMoves(!app.bridge().settingsVC().showPossibleMoves());
app.resetMenuGUI();
}
//-------------------------------------------------------------------------
}
| 2,256 | 25.552941 | 122 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/tools/buttons/ButtonStart.java
|
package app.views.tools.buttons;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import app.PlayerApp;
import app.utils.TrialUtil;
import app.views.tools.ToolButton;
import app.views.tools.ToolView;
import other.context.Context;
/**
* Settings button.
*
* @author Matthew.Stephenson and cambolbro
*/
public class ButtonStart extends ToolButton
{
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param cx
* @param cy
* @param startButtonIndex
*/
public ButtonStart(final PlayerApp app, final int cx, final int cy, final int sx, final int sy, final int startButtonIndex)
{
super(app, "Start", cx, cy, sx, sy, startButtonIndex);
tooltipMessage = "Back to Start";
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d)
{
final double cx = rect.getCenterX();
final double cy = rect.getCenterY();
g2d.setColor(getButtonColour());
// Determine button scale, so that buttons are scaled up on the mobile version.
// The desktop version assume a toolbar height of 32 pixels, this should be 64 for mobile version.
final double scale = scaleForDevice();
g2d.setStroke(new BasicStroke((float)(3 * scale), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
GeneralPath path = new GeneralPath();
path.moveTo(cx + 10 * scale, cy + 7 * scale);
path.lineTo(cx, cy);
path.lineTo(cx + 10 * scale , cy - 7 * scale);
g2d.draw(path);
g2d.setStroke(new BasicStroke((2), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
path = new GeneralPath();
path.moveTo(cx - 4 * scale, cy + 9 * scale);
path.lineTo(cx - 4 * scale, cy - 9 * scale);
g2d.draw(path);
}
//-------------------------------------------------------------------------
@Override
protected boolean isEnabled()
{
final Context context = app.manager().ref().context();
final int numInitialPlacementMoves = context.currentInstanceContext().trial().numInitialPlacementMoves();
if
(
(
context.currentSubgameIdx() > 1
||
context.trial().numMoves() > numInitialPlacementMoves
)
&&
app.manager().settingsNetwork().getActiveGameId() == 0
)
return true;
return false;
}
//-------------------------------------------------------------------------
// Goes to the start (first) location of the current trial
@Override
public void press()
{
if (isEnabled())
{
Context context = app.manager().ref().context();
// Go back one move first.
ToolView.jumpToMove(app, context.trial().numMoves() - 1);
context = app.manager().ref().context();
ToolView.jumpToMove(app, TrialUtil.getInstanceStartIndex(context));
}
}
//-------------------------------------------------------------------------
}
| 2,848 | 25.37963 | 124 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/AutoIndenter.java
|
package supplementary;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import main.StringRoutines;
/**
* Convenience class to run auto indenter for .luds and .defs.
* @author cambolbro
*/
public final class AutoIndenter
{
private static final String indentString = " ";
//-------------------------------------------------------------------------
/**
* Call this to automatically indent all .lud and .def files.
*/
public static void main(final String[] args)
{
indentFilesNicely();
}
//-------------------------------------------------------------------------
/**
* Nicely indents all .lud and .def files.
* Destructively modifies files, but should be safe to use any number of times.
*/
public static void indentFilesNicely()
{
// 1. Indent all .lud files nicely
indentFilesNicelyFrom("../Common/res/lud");
// 2. Indent all .def files nicely
indentFilesNicelyFrom("../Common/res/def");
// 3. Indent all AI metadata .def files nicely
indentFilesNicelyFrom("../Common/res/def_ai");
}
/**
* Nicely indents all files from the specified folder and below.
*/
public static void indentFilesNicelyFrom(final String folderPath)
{
final List<File> files = new ArrayList<File>();
final List<File> dirs = new ArrayList<File>();
final File folder = new File(folderPath);
dirs.add(folder);
for (int i = 0; i < dirs.size(); ++i)
{
final File dir = dirs.get(i);
for (final File file : dir.listFiles())
{
if (file.isDirectory())
dirs.add(file);
else
files.add(file);
}
}
for (final File file : files)
{
final String absolutePath = file.getAbsolutePath();
if (absolutePath.contains("/test/dennis/") || absolutePath.contains("\\test\\dennis\\"))
continue;
indentFileNicely(absolutePath);
}
System.out.println(files.size() + " files found from "+ folderPath + ".");
}
//-------------------------------------------------------------------------
/**
* Nicely indents the specified .lud or .def file.
*/
public static void indentFileNicely(final String path)
{
// if (!path.contains("/Hex.lud"))
// return;
System.out.println("Indenting " + path + " nicely...");
final File fileToBeModified = new File(path);
final List<String> lines = new ArrayList<String>();
// Read lines in
try (final BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(fileToBeModified), StandardCharsets.UTF_8)))
{
String line = reader.readLine();
while (line != null)
{
lines.add(new String(line));
line = reader.readLine();
}
}
catch (final IOException e) { e.printStackTrace(); }
// Left justify all lines
for (int n = 0; n < lines.size(); n++)
{
String str = lines.get(n);
final int c = 0;
while (c < str.length() && (str.charAt(c) == ' ' || str.charAt(c) == '\t'))
str = str.substring(1);
lines.remove(n);
lines.add(n, str);
}
//moveDefinesToTop(lines);
//insertSeparators(lines);
//extractAIMetadataToDefine(lines);
removeDoubleEmptyLines(lines);
indentLines(lines);
try (final BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(fileToBeModified), StandardCharsets.UTF_8)))
{
for (final String result : lines)
writer.write(result + "\n");
}
catch (final IOException e) { e.printStackTrace(); }
}
//-------------------------------------------------------------------------
/**
* Moves any (define ...) clause to the top of the list.
*/
final static void moveDefinesToTop(final List<String> lines)
{
final List<String> defines = new ArrayList<String>();
int brackets = 0;
boolean isDefine = false;
int n = 0;
while (n < lines.size())
{
final String str = lines.get(n);
final int numOpen = StringRoutines.numChar(str, '('); // don't count curly braces!
final int numClose = StringRoutines.numChar(str, ')');
final int difference = numOpen - numClose;
final boolean lineHasDefineString = str.contains("(define ");
if (lineHasDefineString)
{
isDefine = true;
brackets = 0;
}
if (isDefine)
{
// Remove this line and store it
if (lineHasDefineString && defines.size() > 0)
defines.add(""); // add an empty line above each define clause
defines.add(new String(str));
lines.remove(n);
}
else
{
// Move to next line
n++;
}
if (lineHasDefineString && difference == 0)
{
// Define occurs on single line
isDefine = false;
brackets = 0;
}
if (difference < 0)
{
// Unindent from this line
brackets += difference;
if (brackets < 0)
brackets = 0;
if (isDefine && brackets == 0)
{
isDefine = false;
}
}
else if (difference > 0)
{
brackets += difference; // indent from next line
}
}
// Prepend defines at start of file
for (int d = defines.size()-1; d >= 0; d--)
lines.add(0, defines.get(d));
}
//-------------------------------------------------------------------------
/**
* Extracts the first (ai ...) clause and moves it to a .def file in res/def_ai.
*/
final static void extractAIMetadataToDefine(final List<String> lines)
{
final List<String> define = new ArrayList<String>();
int brackets = 0;
boolean isAI = false;
String gameName = "";
for (final String line : lines)
if (line.contains("(game "))
{
gameName = StringRoutines.gameName(line);
break;
}
int n = 0;
while (n < lines.size())
{
final String str = lines.get(n);
final int numOpen = StringRoutines.numChar(str, '('); // don't count curly braces!
final int numClose = StringRoutines.numChar(str, ')');
final int difference = numOpen - numClose;
final boolean lineHasAIString = str.contains("(ai ");
if (lineHasAIString)
{
isAI = true;
brackets = 1;
define.add("(define \"" + gameName + "_ai\""); // open the define
lines.add(n+1, "\"" + gameName + "_ai\""); // add define entry point in .lud
n += 2;
continue;
}
if (difference < 0)
{
// Unindent from this line
brackets += difference;
if (brackets < 0)
brackets = 0;
if (isAI && brackets == 0)
{
define.add(")"); // close define
isAI = false;
}
}
else if (difference > 0)
{
brackets += difference; // indent from next line
}
if (isAI)
{
// Add this line to the .def and remove it from the .lud
define.add(new String(str));
lines.remove(n);
}
else
{
// Move to next line
n++;
}
}
// Save define to new file in res/def_ai
final String outFilePath = "../Common/res/def_ai/" + gameName + "_ai.def";
try (final FileWriter writer = new FileWriter(outFilePath))
{
for (final String result : define)
writer.write(result + "\n");
}
catch (final IOException e) { e.printStackTrace(); }
}
//-------------------------------------------------------------------------
/**
* Removes double empty lines.
*/
final static void removeDoubleEmptyLines(final List<String> lines)
{
int n = 1;
while (n < lines.size())
{
if (lines.get(n).equals("") && lines.get(n-1).equals(""))
lines.remove(n);
else
n++;
}
}
//-------------------------------------------------------------------------
/**
* Inserts separators above key sections.
*/
final static void insertSeparators(final List<String> lines)
{
boolean optionFound = false;
boolean rulesetsFound = false;
for (int n = 2; n < lines.size(); n++) // skip first couple of lines
{
final String str = lines.get(n);
if
(
str.contains("(game ")
||
str.contains("(metadata ")
||
str.contains("(option ") && !optionFound
||
str.contains("(rulesets ") && !rulesetsFound
)
{
lines.add(n, "");
lines.add(n, "//------------------------------------------------------------------------------");
lines.add(n, "");
if (str.contains("(option "))
optionFound = true;
if (str.contains("(rulesets "))
rulesetsFound = true;
n += 3;
}
}
}
//-------------------------------------------------------------------------
/**
* Nicely indents the specified lines of a .lud or .def file.
*/
final static void indentLines(final List<String> lines)
{
int indent = 0;
for (int n = 0; n < lines.size(); n++)
{
String str = lines.get(n);
final int numOpen = StringRoutines.numChar(str, '('); // don't count curly braces!
final int numClose = StringRoutines.numChar(str, ')');
final int difference = numOpen - numClose;
if (difference < 0)
{
// Unindent from this line
indent += difference;
if (indent < 0)
indent = 0;
}
for (int step = 0; step < indent; step++)
str = indentString + str;
lines.remove(n);
lines.add(n, str);
if (difference > 0)
indent += difference; // indent from next line
}
}
//-------------------------------------------------------------------------
}
| 10,980 | 26.521303 | 107 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/DefToTex.java
|
package supplementary;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Converts all .def into .tex for Language Reference.
* @author cambolbro
*/
@Deprecated // Code moved to GenerateLudiiDocTex.java for proper automation
public final class DefToTex
{
// private static final String indentString = " ";
//-------------------------------------------------------------------------
/**
* Call this to automatically indent all .lud and .def files.
*/
public static void main(final String[] args)
{
String tex = "";
try
{
tex = convertAllDefToTex("../Common/res/def");
System.out.println(tex);
}
catch (final IOException e)
{
e.printStackTrace();
}
// Save to file
final String outFilePath = "../LudiiDocGen/out/tex/KnownDefines.tex";
try
(
final BufferedWriter writer =
new BufferedWriter
(
new OutputStreamWriter
(
new FileOutputStream(outFilePath),
StandardCharsets.UTF_8
)
)
)
{
writer.write(tex + "\n");
}
catch
(
final IOException e) { e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Converts all .def into .tex from the specified folder and below.
* Dumps the result to Console.
* @throws IOException
*/
public static String convertAllDefToTex(final String folderPath) throws IOException
{
final StringBuilder sb = new StringBuilder();
// Get list of directories
final List<File> dirs = new ArrayList<File>();
final File folder = new File(folderPath);
dirs.add(folder);
for (int i = 0; i < dirs.size(); ++i)
{
final File dir = dirs.get(i);
for (final File file : dir.listFiles())
if (file.isDirectory())
dirs.add(file);
}
Collections.sort(dirs);
// Visit files in each directory
for (final File dir : dirs)
{
final String path = dir.getCanonicalPath();
if (path.indexOf("/def/") != -1)
{
// Add this section header
final String name = path.substring(path.indexOf("def/"));
sb.append(texSection(name));
}
for (final File file : dir.listFiles())
if (!file.isDirectory())
convertDefToTex(file, sb);
}
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Converts the specified .def file to .tex.
* Dumps the result to Console.
*/
public static void convertDefToTex(final File file, final StringBuilder sb)
{
if (!file.getPath().contains(".def"))
{
System.out.println("Bad file: " + file.getPath());
return;
}
// Read lines in
final List<String> lines = new ArrayList<String>();
try
(
final BufferedReader reader =
new BufferedReader
(
new InputStreamReader
(
new FileInputStream(file),
StandardCharsets.UTF_8
)
)
)
{
String line = reader.readLine();
while (line != null)
{
// Process line for .tex safety
line = line.replace("&", "\\&");
line = line.replace("_", "\\_");
lines.add(new String(line));
line = reader.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Handle subsection title for this define
final String name = file.getName().substring(0, file.getName().length() - 4);
sb.append(texSubsection(name));
// Handle comments in description
final String comments = commentsFromLines(lines);
if (comments == "")
sb.append("\\phantom{}\n");
else
sb.append("\n" + comments + "\n");
// Handle examples
final List<String> examples = examplesFromLines(lines);
if (!examples.isEmpty())
sb.append(texExample(examples));
// Handle define
final String define = defineFromLines(lines);
sb.append(texDefine(define));
}
//-------------------------------------------------------------------------
final static String commentsFromLines(final List<String> lines)
{
final StringBuilder sb = new StringBuilder();
int commentLinesAdded = 0;
for (final String line : lines)
{
final int c = line.indexOf("//");
if (c < 0)
break; // not a comment
if (line.contains("@example"))
break; // don't include examples in comments
if (commentLinesAdded > 0)
sb.append(" \\\\ ");
sb.append(line.substring(c + 2).trim() + " ");
commentLinesAdded++;
}
final String comments = sb.toString().replace("#", "\\#");
return comments;
}
//-------------------------------------------------------------------------
final static List<String> examplesFromLines(final List<String> lines)
{
final List<String> examples = new ArrayList<String>();
for (final String line : lines)
{
final int c = line.indexOf("@example");
if (c < 0)
continue; // not an example
examples.add(line.substring(c + 8).trim());
}
return examples;
}
//-------------------------------------------------------------------------
final static String defineFromLines(final List<String> lines)
{
final StringBuilder sb = new StringBuilder();
boolean defineFound = false;
for (final String line : lines)
{
final int c = line.indexOf("(define ");
if (c >= 0)
defineFound = true;
if (defineFound)
sb.append(line + "\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
static String texThinLine()
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "\\vspace{-1mm}\n");
sb.append("\\noindent\\rule{\\textwidth}{0.5pt}\n");
sb.append("\\vspace{-6mm}\n");
return sb.toString();
}
static String texThickLine()
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "\\vspace{3mm}\n");
sb.append("\\noindent\\rule{\\textwidth}{2pt}\n");
sb.append("\\vspace{-7mm}\n");
return sb.toString();
}
static String texSection(final String title)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "%==========================================================\n");
sb.append(texThickLine());
sb.append("\n" + "\\section{" + title + "}\n");
//sb.append("\n" + "%---------------------------------\n");
return sb.toString();
}
static String texSubsection(final String name)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "%-----------------------------------------\n");
sb.append(texThinLine());
sb.append("\n" + "\\subsection{``" + name + "''}");
sb.append(" \\label{known:" + name + "}\n");
return sb.toString();
}
static String texExample(final List<String> examples)
{
final StringBuilder sb = new StringBuilder();
if (examples.size() < 2)
sb.append("\n% Example\n");
else
sb.append("\n% Examples\n");
sb.append("\\vspace{-1mm}\n");
sb.append("\\subsubsection*{Example}\n");
sb.append("\\vspace{-3mm}\n");
sb.append("\n" + "\\begin{formatbox}\n");
sb.append("\\begin{verbatim}\n");
for (final String example : examples)
sb.append(example + "\n");
sb.append("\\end{verbatim}\n");
sb.append("\\vspace{-1mm}\n");
sb.append("\\end{formatbox}\n");
sb.append("\\vspace{-2mm}\n");
return sb.toString();
}
static String texDefine(final String define)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n% Define\n");
sb.append("{\\tt\n");
sb.append("\\begin{verbatim}\n");
sb.append(define + "\n");
sb.append("\\end{verbatim}\n");
sb.append("}\n");
sb.append("\\vspace{-4mm}\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 8,133 | 24.339564 | 84 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/EvalUtil.java
|
package supplementary;
import java.awt.EventQueue;
import analysis.Complexity;
import app.PlayerApp;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import search.pns.ProofNumberSearch;
import search.pns.ProofNumberSearch.ProofGoals;
public class EvalUtil
{
public static void estimateGameTreeComplexity(final PlayerApp app, final boolean forceNoStateRepetitionRule)
{
if (!app.manager().ref().context().game().isDeductionPuzzle())
{
final double numSecs = 30.0;
final Thread thread = new Thread(() ->
{
final TObjectDoubleHashMap<String> results =
Complexity.estimateGameTreeComplexity
(
app.manager().savedLudName(),
app.manager().settingsManager().userSelections(),
numSecs,
forceNoStateRepetitionRule
);
final double avgNumDecisions = results.get("Avg Num Decisions");
final double avgTrialBranchingFactor = results.get("Avg Trial Branching Factor");
final double power = results.get("Estimated Complexity Power");
final int numTrials = (int) results.get("Num Trials");
EventQueue.invokeLater(() ->
{
app.addTextToAnalysisPanel("Avg. number of decisions per trial = " + avgNumDecisions + ".\n");
app.addTextToAnalysisPanel("Avg. branching factor per trial = " + avgTrialBranchingFactor + ".\n");
app.addTextToAnalysisPanel("Estimated game-tree complexity ~= 10^" + (int) Math.ceil(power) + ".\n");
app.addTextToAnalysisPanel("Statistics collected over " + numTrials + " random trials.\n");
app.setTemporaryMessage("");
});
});
app.selectAnalysisTab();
app.setTemporaryMessage("Estimate Game Tree Complexity is starting. This will take a bit over " + (int) numSecs + " seconds.\n");
thread.setDaemon(true);
thread.start();
}
else
{
app.setVolatileMessage("Estimate Game Tree Complexity is disabled for deduction puzzles.\n");
}
}
//-------------------------------------------------------------------------
/**
* Attempts to prove that the current game state is either a win or a loss
* @param proofGoal
*/
public static void proveState(final PlayerApp app, final ProofGoals proofGoal)
{
final Thread thread = new Thread(() ->
{
final ProofNumberSearch pns = new ProofNumberSearch(proofGoal);
if (!pns.supportsGame(app.manager().ref().context().game()))
{
System.err.println("PNS doesn't support this game!");
return;
}
pns.initIfNeeded(app.manager().ref().context().game(), app.manager().ref().context().state().mover());
pns.selectAction
(
app.manager().ref().context().game(),
app.manager().ref().context(),
1.0,
-1,
-1
);
});
thread.setDaemon(true);
thread.start();
}
//-------------------------------------------------------------------------
public static void estimateGameLength(final PlayerApp app)
{
if (!app.manager().ref().context().game().isDeductionPuzzle())
{
final double numSecs = 30.0;
final Thread thread = new Thread(() ->
{
final TObjectDoubleHashMap<String> results = Complexity.estimateGameLength(app.manager().ref().context().game(), numSecs);
final double avgNumDecisions = results.get("Avg Num Decisions");
final double avgNumPlayerSwitches = results.get("Avg Num Player Switches");
final int numTrials = (int) results.get("Num Trials");
EventQueue.invokeLater(() ->
{
app.addTextToAnalysisPanel("Avg. number of decisions per trial = " + avgNumDecisions + ".\n");
app.addTextToAnalysisPanel("Avg. number of player switches per trial = " + avgNumPlayerSwitches + ".\n");
app.addTextToAnalysisPanel("Statistics collected over " + numTrials + " random trials.\n");
app.setTemporaryMessage("");
});
});
app.selectAnalysisTab();
app.setTemporaryMessage("Estimate Game Length is starting. This will take a bit over " + (int) numSecs + " seconds.\n");
thread.setDaemon(true);
thread.start();
}
else
{
app.setVolatileMessage("Estimate Game Length is disabled for deduction puzzles.\n");
}
}
//-------------------------------------------------------------------------
public static void estimateBranchingFactor(final PlayerApp app)
{
if (!app.manager().ref().context().game().isDeductionPuzzle())
{
final double numSecs = 30.0;
final Thread thread = new Thread(() ->
{
final TObjectDoubleHashMap<String> results =
Complexity.estimateBranchingFactor
(
app.manager().savedLudName(),
app.manager().settingsManager().userSelections(),
numSecs
);
final double avgTrialBranchingFactor = results.get("Avg Trial Branching Factor");
final double avgStateBranchingFactor = results.get("Avg State Branching Factor");
final int numTrials = (int) results.get("Num Trials");
EventQueue.invokeLater(() ->
{
app.addTextToAnalysisPanel("Avg. branching factor per trial = " + avgTrialBranchingFactor + ".\n");
app.addTextToAnalysisPanel("Avg. branching factor per state = " + avgStateBranchingFactor + ".\n");
app.addTextToAnalysisPanel("Statistics collected over " + numTrials + " random trials.\n");
app.setTemporaryMessage("");
});
});
app.selectAnalysisTab();
app.setTemporaryMessage("Estimate Branching Factor is starting. This will take a bit over " + (int) numSecs + " seconds.\n");
thread.setDaemon(true);
thread.start();
}
else
{
app.setVolatileMessage("Estimate Branching Factor is disabled for deduction puzzles.\n");
}
}
//-------------------------------------------------------------------------
}
| 5,586 | 32.860606 | 132 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/PrintLudiiLstDefineLanguage.java
|
package supplementary;
import java.util.ArrayList;
import java.util.List;
import grammar.Grammar;
import main.StringRoutines;
import main.grammar.Symbol;
import main.grammar.Symbol.LudemeType;
/**
* Prints the \lstdefinelanguage command for the Ludii language.
*
* @author Dennis Soemers
*/
public class PrintLudiiLstDefineLanguage
{
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final List<String> classNames = new ArrayList<String>();
final List<String> constNames = new ArrayList<String>();
for (final Symbol s : Grammar.grammar().symbols())
{
if (s.isClass())
classNames.add(StringRoutines.lowerCaseInitial(s.name()));
else if (s.ludemeType() == LudemeType.Constant)
constNames.add(s.name());
}
System.out.println("\\lstdefinelanguage{ludii}{");
System.out.println(" keywords={" + StringRoutines.join(",", classNames) + "},");
System.out.println(" basewidth = {.6em,0.6em},");
System.out.println(" keywordstyle=\\color{mblue}\\bfseries,");
System.out.println(" ndkeywords={" + StringRoutines.join(",", constNames) + "},");
System.out.println(" ndkeywordstyle=\\color{dviolet}\\bfseries,");
System.out.println(" identifierstyle=\\color{black},");
System.out.println(" sensitive=true, % need case-sensitivity for different keywords");
System.out.println(" comment=[l]{//},");
System.out.println(" commentstyle=\\color{dred}\\ttfamily,");
System.out.println(" stringstyle=\\color{dgreen}\\ttfamily,");
System.out.println(" morestring=[b]',");
System.out.println(" morestring=[b]\",");
System.out.println(" escapechar=@,");
System.out.println(" showstringspaces=false,");
System.out.println(" xleftmargin=1pt,xrightmargin=1pt,");
System.out.println(" breaklines=true,basicstyle=\\ttfamily\\small,backgroundcolor=\\color{colorex},inputencoding=utf8/latin9,texcl");
System.out.println("}");
}
}
| 1,932 | 33.517857 | 136 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/EvalAIsThread.java
|
package supplementary.experiments;
import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.IntStream;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.collections.ListUtils;
import manager.Manager;
import manager.Referee;
import manager.ai.AIDetails;
import other.AI;
import other.RankUtils;
import other.context.Context;
import utils.experiments.ResultsSummary;
/**
* Thread in which multiple AI players can be evaluated when playing
* against each other.
*
* @author Dennis Soemers
*/
public class EvalAIsThread extends Thread
{
/** Our runnable */
private final EvalAIsThreadRunnable runnable;
//-------------------------------------------------------------------------
/**
* @param ref
* @param aiPlayers
* @return Constructs a thread for AIs to be evaluated in
*/
public static EvalAIsThread construct
(
final Referee ref,
final List<AI> aiPlayers,
final Manager manger
)
{
final EvalAIsThreadRunnable runnable =
new EvalAIsThreadRunnable
(
ref,
aiPlayers,
manger
);
return new EvalAIsThread(runnable);
}
/**
* Constructor
* @param runnable
*/
protected EvalAIsThread(final EvalAIsThreadRunnable runnable)
{
super(runnable);
this.runnable = runnable;
}
//-------------------------------------------------------------------------
public EvalAIsThreadRunnable getRunnable()
{
return runnable;
}
/**
* Runnable class for Eval AIs Thread
*
* @author Dennis Soemers
*/
private static class EvalAIsThreadRunnable implements Runnable
{
//---------------------------------------------------------------------
/** Referee */
protected final Referee ref;
/** AI players */
protected final List<AI> aiPlayers;
protected Manager manager;
//---------------------------------------------------------------------
/**
* Constructor
* @param ref
* @param aiPlayers
*/
public EvalAIsThreadRunnable
(
final Referee ref,
final List<AI> aiPlayers,
final Manager manager
)
{
this.ref = ref;
this.aiPlayers = aiPlayers;
this.manager = manager;
}
//---------------------------------------------------------------------
@Override
public void run()
{
final int maxNumGames = 100;
final Game game = ref.context().game();
final int numPlayers = game.players().count();
final List<String> agentStrings = new ArrayList<String>(numPlayers);
for (int i = 0; i < numPlayers; ++i)
{
final AI ai = aiPlayers.get(i + 1);
final int playerIdx = i + 1;
if (ai == null)
{
try
{
EventQueue.invokeAndWait(new Runnable()
{
@Override
public void run()
{
manager.getPlayerInterface().addTextToAnalysisPanel
(
"Cannot run evaluation; Player " + playerIdx + " is not AI.\n"
);
}
});
}
catch (final InvocationTargetException | InterruptedException e)
{
e.printStackTrace();
}
return;
}
else if (!ai.supportsGame(game))
{
try
{
EventQueue.invokeAndWait(new Runnable()
{
@Override
public void run()
{
manager.getPlayerInterface().addTextToAnalysisPanel
(
"Cannot run evaluation; " + ai.friendlyName() + " does not support this game.\n"
);
}
});
}
catch (final InvocationTargetException | InterruptedException e)
{
e.printStackTrace();
}
return;
}
agentStrings.add(manager.aiSelected()[i+1].name());
}
// final String[] originalPlayerNames = Arrays.copyOf(AIDetails.convertToNameArray(PlayerApp.aiSelected()), PlayerApp.aiSelected().length);
final Context context = ref.context();
final List<TIntArrayList> aiListPermutations =
ListUtils.generatePermutations(
TIntArrayList.wrap(
IntStream.range(1, numPlayers + 1).toArray()));
final ResultsSummary resultsSummary = new ResultsSummary(game, agentStrings);
final Timer updateGuiTimer = new Timer();
try
{
int gameCounter = 0;
for (/**/; gameCounter < maxNumGames; ++gameCounter)
{
// compute list of AIs to use for this game (we rotate every game)
final List<AI> currentAIList = new ArrayList<AI>(numPlayers);
final int currentAIsPermutation = gameCounter % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation =
aiListPermutations.get(currentAIsPermutation);
currentAIList.add( null); // 0 index not used
for (int i = 0; i < currentPlayersPermutation.size(); ++i)
{
final AI ai = aiPlayers.get(currentPlayersPermutation.getQuick(i));
currentAIList.add(ai);
}
// play a game
game.start(context);
updateGuiTimer.schedule(new TimerTask()
{
@Override
public void run()
{
manager.getPlayerInterface().repaint();
}
}, Referee.AI_VIS_UPDATE_TIME , Referee.AI_VIS_UPDATE_TIME
);
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).initAI(game, p);
}
while (!context.trial().over())
{
if (manager.settingsManager().agentsPaused())
{
final int passedAtGameCounter = gameCounter;
EventQueue.invokeLater
(
new Runnable()
{
@Override
public void run()
{
manager.getPlayerInterface().addTextToAnalysisPanel
(
"Evaluation interrupted after completing " + passedAtGameCounter + " games."
);
}
}
);
return;
}
context.model().startNewStep
(
context,
currentAIList,
AIDetails.convertToThinkTimeArray(manager.aiSelected()),
-1, -1, 0.3,
false, false, false,
null, null
);
manager.setLiveAIs(context.model().getLiveAIs());
while (!context.model().isReady())
{
Thread.sleep(100L);
}
manager.setLiveAIs(null);
}
final double[] utilities = RankUtils.agentUtilities(context);
final int numMovesPlayed = context.trial().numMoves() - context.trial().numInitialPlacementMoves();
final int[] agentPermutation = new int[currentPlayersPermutation.size() + 1];
currentPlayersPermutation.toArray(agentPermutation, 0, 1, currentPlayersPermutation.size());
for (int p = 1; p < agentPermutation.length; ++p)
{
agentPermutation[p] -= 1;
}
resultsSummary.recordResults(agentPermutation, utilities, numMovesPlayed);
manager.getPlayerInterface().addTextToAnalysisPanel(resultsSummary.generateIntermediateSummary());
manager.getPlayerInterface().addTextToAnalysisPanel("\n");
// Close AIs
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).closeAI();
}
Thread.sleep(1000); // wait for a second before starting next game
}
}
catch (final Exception e)
{
e.printStackTrace();
}
finally
{
updateGuiTimer.cancel();
updateGuiTimer.purge();
manager.setLiveAIs(null);
manager.getPlayerInterface().repaint();
}
}
}
//-------------------------------------------------------------------------
}
| 7,523 | 22.961783 | 141 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/EvalGamesSet.java
|
package supplementary.experiments;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.collections.ListUtils;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.model.Model;
import other.trial.Trial;
import utils.experiments.InterruptableExperiment;
import utils.experiments.ResultsSummary;
/**
* A set consisting of one or more games between a fixed set of agents
* (which may rotate through permutations of assignments to player numbers)
*
* @author Dennis Soemers
*/
public class EvalGamesSet
{
/** The name of the game to play */
protected String gameName = null;
/** List of extra game options to compile */
protected List<String> gameOptions = new ArrayList<String>();
/** Ruleset to compile */
protected String ruleset = null;
/** List of AIs / agents */
protected List<AI> agents = null;
/** Number of games to run (by default 100) */
protected int numGames = 100;
/** If a game lasts for more turns than this, we'll terminate it as a draw (by default -1, i.e. no limit) */
protected int gameLengthCap = -1;
/** Max seconds per move for AI (by default 1.0 second) */
protected double[] maxSeconds = new double[Constants.MAX_PLAYERS+1];
/** Max iterations per move for AI (by default -1, i.e. no limit) */
protected int maxIterations = -1;
/** Max search depth per move for AI (by default -1, i.e. no search depth limit) */
protected int maxSearchDepth = -1;
/** Whether to rotate assignments of agents to player numbers (by default true) */
protected boolean rotateAgents = true;
/** Number of seconds for which to run a warming-up */
protected int warmingUpSecs = 60;
/** If true, we'll increase number of games to play to next number that can be divided by number of permutations of agents */
protected boolean roundToNextPermutationsDivisor = false;
/** If true, we'll print intermediate results to System.out */
protected boolean printOut = true;
/** Directory in which to save output files */
protected File outDir = null;
/** Whether we want to output a summary of results */
protected boolean outputSummary = true;
/** Whether we want to output results in a format convenient for subsequently computing alpha-ranks using OpenSpiel */
protected boolean outputAlphaRankData = false;
/** Whether to create a small GUI that can be used to manually interrupt experiment */
protected boolean useGUI = false;
/** Max wall time in minutes (or -1 for no limit) */
protected int maxWallTime = -1;
/** The results of the last experiment run. */
protected ResultsSummary resultsSummary = null;
/** Suppress warnings about number of trials not being divisible by number of permutations of agents */
protected boolean suppressDivisorWarning = false;
//-------------------------------------------------------------------------
/**
* Constructor. No GUI for interrupting experiment, no wall time limit.
*/
public EvalGamesSet()
{
Arrays.fill(maxSeconds, 1.0);
}
/**
* Constructor. No wall time limit.
* @param useGUI
*/
public EvalGamesSet(final boolean useGUI)
{
this.useGUI = useGUI;
}
/**
* Constructor
* @param useGUI
* @param maxWallTime Wall time limit in minutes.
*/
public EvalGamesSet(final boolean useGUI, final int maxWallTime)
{
this.useGUI = useGUI;
this.maxWallTime = maxWallTime;
}
//-------------------------------------------------------------------------
/**
* Starts running the set of games
*/
public void startGames()
{
final Game game;
if (ruleset != null && !ruleset.equals(""))
game = GameLoader.loadGameFromName(gameName, ruleset);
else
game = GameLoader.loadGameFromName(gameName, gameOptions);
startGames(game);
}
/**
* Starts running the set of games
*/
/**
* Starts running the set of games, using the specified Game object
* @param game
*/
@SuppressWarnings("unused")
public void startGames(final Game game)
{
if (game == null)
{
System.err.println("Could not instantiate game. Aborting set of games. Game name = " + gameName + ".");
return;
}
if (agents == null)
{
System.err.println("No list of agents provided. Aborting set of games.");
return;
}
final int numPlayers = game.players().count();
if (agents.size() != numPlayers)
{
System.err.println
(
"Expected " + numPlayers +
" agents, but received list of " + agents.size() +
" agents. Aborting set of games."
);
return;
}
if (gameLengthCap >= 0)
game.setMaxTurns(Math.min(gameLengthCap, game.getMaxTurnLimit()));
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
new InterruptableExperiment(useGUI, maxWallTime)
{
@Override
public void runExperiment()
{
int numGamesToPlay = numGames;
List<TIntArrayList> aiListPermutations = new ArrayList<TIntArrayList>();
if (rotateAgents)
{
if (numPlayers <= 5)
{
// Compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
Collections.shuffle(aiListPermutations);
}
else
{
// Randomly generate some permutations of indices for the list of AIs
aiListPermutations = ListUtils.samplePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()), 120);
}
if (numGamesToPlay % aiListPermutations.size() != 0)
{
if (roundToNextPermutationsDivisor)
{
numGamesToPlay += (numGamesToPlay % aiListPermutations.size());
}
else if (!suppressDivisorWarning)
{
System.out.println
(
String.format
(
"Warning: number of games to play (%d) is "
+ "not divisible by the number of "
+ "permutations of list of AIs (%d)",
Integer.valueOf(numGamesToPlay), Integer.valueOf(aiListPermutations.size())
)
);
}
}
}
else
{
// only need a single permutation; order in which AIs were given to us
aiListPermutations.add(TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
}
// start with a warming up
if (printOut)
System.out.println("Warming up...");
long stopAt = 0L;
final long start = System.nanoTime();
final double abortAt = start + warmingUpSecs * 1000000000.0;
while (stopAt < abortAt)
{
game.start(context);
game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current());
stopAt = System.nanoTime();
}
System.gc();
if (printOut)
System.out.println("Finished warming up!");
// prepare results writing
final List<String> agentStrings = new ArrayList<String>();
for (final AI ai : agents)
{
agentStrings.add(ai.friendlyName());
}
resultsSummary = new ResultsSummary(game, agentStrings);
for (int gameCounter = 0; gameCounter < numGamesToPlay; ++gameCounter)
{
checkWallTime(0.05);
if (interrupted)
{
// Time to abort the experiment due to wall time
break;
}
// Compute list of AIs to use for this game
// (we rotate every game)
final List<AI> currentAIList = new ArrayList<AI>(numPlayers);
final int currentAIsPermutation = gameCounter % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
currentAIList.add(null); // 0 index not used
for (int i = 0; i < currentPlayersPermutation.size(); ++i)
{
currentAIList.add
(
agents.get(currentPlayersPermutation.getQuick(i) % agents.size())
);
}
// Play a game
game.start(context);
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).initAI(game, p);
}
final Model model = context.model();
while (!context.trial().over())
{
if (interrupted)
{
// Time to abort the experiment due to wall time
break;
}
model.startNewStep(context, currentAIList, maxSeconds, maxIterations, maxSearchDepth, 0.0);
}
// Record results
if (context.trial().over())
{
final double[] utilities = RankUtils.agentUtilities(context);
final int numMovesPlayed = context.trial().numMoves() - context.trial().numInitialPlacementMoves();
final int[] agentPermutation = new int[currentPlayersPermutation.size() + 1];
currentPlayersPermutation.toArray(agentPermutation, 0, 1, currentPlayersPermutation.size());
resultsSummary().recordResults(agentPermutation, utilities, numMovesPlayed);
}
// Close AIs
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).closeAI();
}
if (printOut && (gameCounter < 5 || gameCounter % 10 == 9))
{
System.out.print(resultsSummary().generateIntermediateSummary());
}
}
if (outDir != null)
{
if (outputSummary)
{
final File outFile = new File(outDir + "/results.txt");
outFile.getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile, "UTF-8"))
{
writer.write(resultsSummary().generateIntermediateSummary());
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
if (outputAlphaRankData)
{
final File outFile = new File(outDir + "/alpha_rank_data.csv");
outFile.getParentFile().mkdirs();
resultsSummary().writeAlphaRankData(outFile);
}
}
}
};
}
//-------------------------------------------------------------------------
/**
* Set the name of the game to be played
* @param gameName
* @return This, modified.
*/
public EvalGamesSet setGameName(final String gameName)
{
this.gameName = gameName;
return this;
}
/**
* Set the game options to use when compiling game
* @param gameOptions
* @return This, modified.
*/
public EvalGamesSet setGameOptions(final List<String> gameOptions)
{
this.gameOptions = gameOptions;
return this;
}
/**
* Set the ruleset to use when compiling game
* @param ruleset
* @return This, modified.
*/
public EvalGamesSet setRuleset(final String ruleset)
{
this.ruleset = ruleset;
return this;
}
/**
* Set list of AIs / agents
* @param agents
* @return This, modified.
*/
public EvalGamesSet setAgents(final List<AI> agents)
{
this.agents = agents;
return this;
}
/**
* Set number of games to play
* @param numGames
* @return This, modified.
*/
public EvalGamesSet setNumGames(final int numGames)
{
this.numGames = numGames;
return this;
}
/**
* Set cap on game length (num turns)
* @param gameLengthCap
* @return This, modified.
*/
public EvalGamesSet setGameLengthCap(final int gameLengthCap)
{
this.gameLengthCap = gameLengthCap;
return this;
}
/**
* Set max seconds per move for AI
* @param maxSeconds
* @return This, modified.
*/
public EvalGamesSet setMaxSeconds(final double maxSeconds)
{
for (int i = 0; i < this.maxSeconds.length; i++)
this.maxSeconds[i] = maxSeconds;
return this;
}
public EvalGamesSet setMaxSeconds(final double[] maxSeconds)
{
this.maxSeconds = maxSeconds;
return this;
}
/**
* Set max iterations per move for AI
* @param maxIterations
* @return This, modified.
*/
public EvalGamesSet setMaxIterations(final int maxIterations)
{
this.maxIterations = maxIterations;
return this;
}
/**
* Set max search depth per move for AI
* @param maxSearchDepth
* @return This, modified.
*/
public EvalGamesSet setMaxSearchDepth(final int maxSearchDepth)
{
this.maxSearchDepth = maxSearchDepth;
return this;
}
/**
* Set whether to rotate agents
* @param rotateAgents
* @return This, modified.
*/
public EvalGamesSet setRotateAgents(final boolean rotateAgents)
{
this.rotateAgents = rotateAgents;
return this;
}
/**
* Set number of seconds for warming up
* @param warmingUpSecs
* @return This, modified.
*/
public EvalGamesSet setWarmingUpSecs(final int warmingUpSecs)
{
this.warmingUpSecs = warmingUpSecs;
return this;
}
/**
* Set whether to round to next divisor of number of permutations
* @param roundToNextPermutationsDivisor
* @return This, modified.
*/
public EvalGamesSet setRoundToNextPermutationsDivisor(final boolean roundToNextPermutationsDivisor)
{
this.roundToNextPermutationsDivisor = roundToNextPermutationsDivisor;
return this;
}
/**
* Set output directory
* @param outDir
* @return This, modified.
*/
public EvalGamesSet setOutDir(final File outDir)
{
this.outDir = outDir;
return this;
}
/**
* Set whether to output data for alpha-rank processing.
* @param outputAlphaRankData
* @return This, modified
*/
public EvalGamesSet setOutputAlphaRankData(final boolean outputAlphaRankData)
{
this.outputAlphaRankData = outputAlphaRankData;
return this;
}
/**
* Set whether to output summary of results.
* @param outputSummary
* @return This, modified
*/
public EvalGamesSet setOutputSummary(final boolean outputSummary)
{
this.outputSummary = outputSummary;
return this;
}
/**
* Set whether we want to print intermediate results to standard output
* @param printOut
* @return This, modified.
*/
public EvalGamesSet setPrintOut(final boolean printOut)
{
this.printOut = printOut;
return this;
}
/**
* Set whether we want to suppress warnings about number of trials not being
* divisible by number of permutations of agents.
* @param suppress
* @return This, modified.
*/
public EvalGamesSet setSuppressDivisorWarning(final boolean suppress)
{
this.suppressDivisorWarning = suppress;
return this;
}
public ResultsSummary resultsSummary()
{
return resultsSummary;
}
//-------------------------------------------------------------------------
}
| 14,531 | 24.674912 | 126 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/EvalGamesThread.java
|
package supplementary.experiments;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import main.grammar.Report;
import metrics.Evaluation;
import metrics.Metric;
import supplementary.experiments.eval.EvalGames;
/**
* Thread in which various metrics of a game can be evaluated
* from AI vs. AI play.
*
* @author Dennis Soemers and Matthew.Stephenson
*/
public class EvalGamesThread extends Thread
{
/** Our runnable */
protected final EvalGamesThreadRunnable runnable;
//-------------------------------------------------------------------------
/**
* @param game
* @param gameOptions
* @param AIName
* @param numGames
* @param thinkingTime
* @param maxNumTurns
* @return Constructs a thread for games to be evaluated in
*/
public static EvalGamesThread construct
(
final Evaluation evaluation,
final Report report,
final Game game,
final List<String> gameOptions,
final String AIName,
final int numGames,
final double thinkingTime,
final int maxNumTurns,
final List<Metric> metricsToEvaluate,
final ArrayList<Double> weights,
final boolean useDatabaseGames
)
{
final EvalGamesThreadRunnable runnable =
new EvalGamesThreadRunnable
(
evaluation,
report,
game,
gameOptions,
AIName,
numGames,
thinkingTime,
maxNumTurns,
metricsToEvaluate,
weights,
useDatabaseGames
);
return new EvalGamesThread(runnable);
}
/**
* Constructor
* @param runnable
*/
protected EvalGamesThread(final EvalGamesThreadRunnable runnable)
{
super(runnable);
this.runnable = runnable;
}
//-------------------------------------------------------------------------
/**
* Runnable class for Eval AIs Thread
*
* @author Dennis Soemers
*/
private static class EvalGamesThreadRunnable implements Runnable
{
//---------------------------------------------------------------------
protected final Evaluation evaluation;
/** The game we want to evaluate */
protected final Report report;
/** The game we want to evaluate */
protected final Game game;
/** Game options */
final List<String> gameOptions;
/** Maximum number of turns before a timeout */
final int maxNumTurns;
/** AI players */
protected final String AIName;
/** Number of games to run for evaluation */
protected final int numGames;
/** Thinking time per move (in seconds) */
protected final double thinkingTime;
/** The metrics we want to evaluate */
protected final List<Metric> metricsToEvaluate;
/** the weights for all metrics (between -1 and 1) */
protected final ArrayList<Double> weights;
/** Use saved trials from the database if available. */
protected boolean useDatabaseGames;
//---------------------------------------------------------------------
/**
* Constructor
* @param game
* @param gameOptions
* @param AIName
* @param numGames
* @param thinkingTime
* @param maxNumTurns
* @param weights
* @param metricsToEvaluate
*/
public EvalGamesThreadRunnable
(
final Evaluation evaluation,
final Report report,
final Game game,
final List<String> gameOptions,
final String AIName,
final int numGames,
final double thinkingTime,
final int maxNumTurns,
final List<Metric> metricsToEvaluate,
final ArrayList<Double> weights,
final boolean useDatabaseGames
)
{
this.evaluation = evaluation;
this.report = report;
this.game = game;
this.gameOptions = gameOptions;
this.maxNumTurns = maxNumTurns;
this.AIName = AIName;
this.numGames = numGames;
this.thinkingTime = thinkingTime;
this.metricsToEvaluate = metricsToEvaluate;
this.weights = weights;
this.useDatabaseGames = useDatabaseGames;
}
//---------------------------------------------------------------------
@Override
public void run()
{
EvalGames.evaluateGame(evaluation, report, game, gameOptions, AIName, numGames, thinkingTime, maxNumTurns, metricsToEvaluate, weights, useDatabaseGames);
}
}
//-------------------------------------------------------------------------
}
| 4,145 | 22.691429 | 156 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/EvaluateAllUBFMs.java
|
package supplementary.experiments;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.trial.Trial;
import search.mcts.MCTS;
//import other.trial.Trial;
import search.minimax.AlphaBetaSearch;
import search.minimax.BiasedUBFM;
import search.minimax.HybridUBFM;
import search.minimax.LazyUBFM;
import search.minimax.NaiveActionBasedSelection;
import search.minimax.UBFM;
import utils.RandomAI;
/**
* Class to run experiments and compare an Unbounded Best-First Minimax agent
* to an Alpha-Beta agent and an UCT agent.
*
* @author cyprien
*/
public class EvaluateAllUBFMs
{
/** Activation of some displays to help debugging if true: */
public static boolean debugDisplays = false;
/** Number of trials that will be played to compare the agents: (must be even)*/
final private static int numTrialsPerComparison = 100;
/** Time for the AI to think in the simulations (seconds): */
final private static double thinkingTime = 1;
private boolean compareHeuristics = true;
final String repository = "/home/cyprien/Documents/M1/Internship/data/";
//-------------------------------------------------------------------------
private static EvaluateAllUBFMs evaluator = null;
/** Game played (first arg of main): */
public String gameName;
/** The different configurations to test: */
private List<String[]> configurations;
//-------------------------------------------------------------------------
// Thread executor (maximum number of threads possible)
final static int numThreads = 10;
final ExecutorService executor = Executors.newFixedThreadPool(numThreads); // note: was static on the previous file
//-------------------------------------------------------------------------
/** Main function, running the experiment */
public void runExperiment()
{
System.out.println("Launching all the matches in the game "+gameName+"...");
final Game game = GameLoader.loadGameFromName(gameName+".lud");
configurations = new ArrayList<String[]>(80);
if (compareHeuristics)
{
configurations.add(new String[] {"TrainedUBFM", Float.toString(0.2f), Integer.toString(1)});
for (int i=1; i<=15; i++)
configurations.add(new String[] {"TrainedUBFM", Float.toString(0.2f), Integer.toString(i*5)});
}
else
{
if ((game.metadata().ai().features() != null) || (game.metadata().ai().trainedFeatureTrees() != null))
{
configurations.add(new String[] {"Naive Action Based Selection"});
System.out.println("features found");
}
for (String epsilon : new String[] {"0", "0.1", "0.2", "0.3", "0.5"})
{
configurations.add(new String[] {"UBFM",epsilon});
configurations.add(new String[] {"DescentUBFM",epsilon});
if ((game.metadata().ai().features() != null) || (game.metadata().ai().trainedFeatureTrees() != null))
{
for (String weight : new String[] {"0.1","0.3","0.5","1","2"})
configurations.add(new String[] {"LazyUBFM",epsilon,weight});
for (String n : new String[] {"2","4","6","10"})
configurations.add(new String[] {"BiasedUBFM",epsilon,n});
}
for (String weight : new String[] {"0.2","0.5","0.9"})
configurations.add(new String[] {"HybridUBFM",epsilon,weight});
}
configurations.add(new String[] {"Bob"});
}
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
try
{
// Run trials concurrently
final CountDownLatch latch = new CountDownLatch(configurations.size()*2); //*2 because there are two opponents
final List<Future<double[]>> futures = new ArrayList<Future<double[]>>(numTrialsPerComparison);
for (String[] config: configurations)
{
for (String opp: new String[] {"AlphaBeta","UCT"})
{
final String[] configuration = config;
final String opponent = opp;
futures.add(
executor.submit
(
() ->
{
final double[] agentScores = new double[]{0.,0.,0.,0.};
try
{
LocalDateTime beginTime = LocalDateTime.now();
UBFM UBFM_AI = null;
AI not_UBFM_AI = null;
switch (configuration[0])
{
case "UBFM":
UBFM_AI = new UBFM();
break;
case "TrainedUBFM":
String fileName = repository+"learning/learned_heuristics/"+gameName+configuration[2]+".sav";
File f = new File(fileName);
if (f.exists())
UBFM_AI = new UBFM();
break;
case "DescentUBFM":
UBFM_AI = new UBFM();
UBFM_AI.setIfFullPlayouts(true);
break;
case "LazyUBFM":
final LazyUBFM LazyAI = new LazyUBFM();
UBFM_AI = LazyAI;
LazyUBFM.setActionEvaluationWeight(Float.parseFloat(configuration[2]));
break;
case "HybridUBFM":
final HybridUBFM HybridAI = new HybridUBFM();
UBFM_AI = HybridAI;
HybridAI.setHeuristicScoreWeight(Float.parseFloat(configuration[2]));
break;
case "BiasedUBFM":
final BiasedUBFM BiasedAI = new BiasedUBFM();
UBFM_AI = BiasedAI;
BiasedAI.setNbStateEvaluationsPerNode(Integer.parseInt(configuration[2]));
break;
case "Naive Action Based Selection":
not_UBFM_AI = new NaiveActionBasedSelection();
break;
default:
System.out.println(configuration[0]);
throw new RuntimeException("Configuration not understood");
}
AI Tested_AI = null;
if (UBFM_AI != null)
{
UBFM_AI.setSelectionEpsilon(Float.parseFloat(configuration[1]));
UBFM_AI.setSelectionPolicy(UBFM.SelectionPolicy.SAFEST);
Tested_AI = UBFM_AI;
UBFM_AI.savingSearchTreeDescription = false;
//if (gameName == "Chess")
UBFM_AI.setTTReset(true); // FIXME: could be changed
UBFM_AI.debugDisplay = false;
UBFM_AI.savingSearchTreeDescription = false;
}
else if (not_UBFM_AI != null)
Tested_AI = not_UBFM_AI;
if (Tested_AI != null)
{
final AI opponentAI;
switch (opponent)
{
case "AlphaBeta":
opponentAI = new AlphaBetaSearch();
break;
case "UCT":
opponentAI = MCTS.createUCT();
break;
case "RandomAI":
opponentAI = new RandomAI();
break;
default:
throw new RuntimeException("Unknown opponent");
}
compareAgents(game, Tested_AI, opponentAI, agentScores, numTrialsPerComparison, configuration);
try
{
File directory = new File(String.valueOf(repository+gameName+"/"+opponent+"/"));
directory.mkdirs();
@SuppressWarnings("resource")
FileWriter myWriter = new FileWriter(repository+gameName+"/"+opponent+"/"+configurationToString(configuration)+".sav");
myWriter.write("Results of the duel between "+configurationToString(configuration)+" against "+opponent+":\n");
myWriter.write("Game: "+gameName+"\n");
myWriter.write("(thinking time: "+Double.toString(thinkingTime)+", numberOfPlayouts: "+Integer.toString(numTrialsPerComparison)+")\n");
myWriter.write("(begin time "+dtf.format(beginTime)+", end time "+dtf.format(LocalDateTime.now())+")\n\n");
myWriter.write("UBFM WR as 1st player:"+Double.toString(agentScores[0])+"\n");
myWriter.write("Opponent WR as 1st player:"+Double.toString(agentScores[1])+"\n");
myWriter.write("UBFM WR as 2nd player:"+Double.toString(agentScores[2])+"\n");
myWriter.write("Opponent WR as 2nd player:"+Double.toString(agentScores[3])+"\n");
myWriter.write("\n");
myWriter.write("UBFM WR average:"+Double.toString((agentScores[2]+agentScores[0])/2.)+"\n");
myWriter.write("Opponent WR average:"+Double.toString((agentScores[1]+agentScores[3])/2.)+"\n");
myWriter.write("UBFM score:"+Double.toString(50f+(agentScores[0]+agentScores[2])/4.-(agentScores[1]+agentScores[3])/4.)+"\n");
myWriter.close();
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
return agentScores;
}
catch (final Exception e)
{
e.printStackTrace();
return agentScores;
}
finally
{
latch.countDown();
}
}
)
);
}
}
latch.await(); // wait for all trials to finish
System.out.println("Games done.");
executor.shutdown();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
/**
* Compares two agents on a given game. Writes the results in the array resultsArray.
* The format of the result is the following:
* {AI1 win rate as 1st player, AI2 win rate as 1st player, AI1 win rate as 2nd player, AI2 win rate as 2nd player}
* @param game
* @param AI1
* @parama AI2
* @param resultsArray : array of size 4
* @param nbTrials
* @param configuration
*/
private static void compareAgents
(
final Game game,
final AI AI1,
final AI AI2,
final double[] resultsArray,
final int nbTrials,
final String[] configuration
)
{
for (int i=0; i<nbTrials; i++)
{
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
final List<AI> agents = new ArrayList<>();
agents.add(null);
if (i%2 == 0) {
agents.add(AI1);
agents.add(AI2);
}
else {
agents.add(AI2);
agents.add(AI1);
}
game.start(context);
AI1.initAI(game, i%2+1);
AI2.initAI(game, (i+1)%2+1);
if (debugDisplays)
System.out.println("launching a playout");
game.playout(context, agents, thinkingTime, null, -1, 200, ThreadLocalRandom.current());
if (debugDisplays)
System.out.println("a game is over");
if (RankUtils.agentUtilities(context)[1+i%2]==1)
resultsArray[0+(i%2)*2] += 2 * 100 / nbTrials;
if (RankUtils.agentUtilities(context)[2-i%2]==1)
resultsArray[1+(i%2)*2] += 2 * 100 / nbTrials;
}
return;
}
public static String configurationToString(String[] configuration)
{
StringBuffer res = new StringBuffer();
for (int i=0; i<configuration.length; i++)
res.append(configuration[i].replace(".", "p")+"_");
res.deleteCharAt(res.length()-1);
return res.toString();
}
public static void main(String[] args)
{
evaluator = new EvaluateAllUBFMs();
if (args.length>0)
evaluator.gameName = args[0];
else
evaluator.gameName = "Breakthrough"; // by default
if (args.length>1)
if (args[1] == "eval heuristics")
evaluator.compareHeuristics = true;
evaluator.runExperiment();
}
}
| 11,425 | 30.476584 | 146 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/EvaluateUBFM.java
|
package supplementary.experiments;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import main.math.statistics.Stats;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.trial.Trial;
import search.mcts.MCTS;
import search.minimax.UBFMKilothonContender;
/**
* Class to run experiments and compare an Unbounded Best-First Minimax agent
* to an Iterative Deepening Alpha-Beta agent.
*
* @author cyprien
*
*/
public class EvaluateUBFM
{
/** Activation of some displays to help debugging if true: */
public static boolean debugDisplays = false;
private static EvaluateUBFM evaluateUBFM = null;
/** Number of trials that will be played to compare the agents: */
private static int numTrialsPerComparison = 1;
/** Time for the AI to think in the simulations (seconds): */
private static double thinkingTime = 1;
/** Game played: */
private static final String gameName = "20 Squares";
/** Name of the file in which the results will be written: */
private String outputFile = "comparison_output.sav";
/** Text output: */
private StringBuffer textOutput = new StringBuffer();
//-------------------------------------------------------------------------
// Thread executor (maximum number of threads possible)
final static int numThreads = Runtime.getRuntime().availableProcessors();
final ExecutorService executor = Executors.newFixedThreadPool(numThreads); // note: was static on the previous file
/** Main function, running the experiment */
public void runExperiment()
{
System.out.println("Launching experiment comparing UBFM to Iterative deepening...");
output("Game: "+gameName);
final Game game = GameLoader.loadGameFromName(gameName+".lud");
final Stats resultsAgent1asFirst = new Stats("Results of agent 1 (as first player)");
final Stats resultsAgent1asSecond = new Stats("Results of agent 1 (as second player)");
int nbDraws = 0;
output("\n");
try
{
// Run trials concurrently
final CountDownLatch latch = new CountDownLatch(numTrialsPerComparison);
final List<Future<Double>> futures = new ArrayList<Future<Double>>(numTrialsPerComparison);
for (int n = 0; n < numTrialsPerComparison; ++n)
{
final int m = n;
futures.add(
executor.submit
(
() ->
{
try
{
//final Heuristics heuristics = new Heuristics(new MobilityAdvanced(null, null));
final AI UBFM_AI = new UBFMKilothonContender();
// UBFM_AI.setSelectionEpsilon(0f);
final AI alphaBetaAI = MCTS.createUCT();
// UBFM_AI.debugDisplay = false;
// UBFM_AI.savingSearchTreeDescription = false;
// UBFM_AI.setNbStateEvaluationsPerNode(20);
final float[] agentScores = new float[] {0.f, 0.f };
if (m % 2 == 0)
compareAgents(game, UBFM_AI, alphaBetaAI, agentScores);
else
compareAgents(game, alphaBetaAI, UBFM_AI, agentScores);
latch.countDown();
output(".");
// agent utilities are converted to a score between 0 and 1
return Double.valueOf(agentScores[m%2]*0.5 + 0.5);
}
catch (final Exception e)
{
e.printStackTrace();
return Double.valueOf(0.0);
}
}
)
);
}
latch.await(); // wait for all trials to finish
System.out.println("Games done.");
double result;
for (int n=0; n<numTrialsPerComparison; ++n)
{
result = futures.get(n).get().doubleValue();
if (n % 2 == 0)
resultsAgent1asFirst.addSample(result);
else
resultsAgent1asSecond.addSample(result);
if (result == 0.5)
nbDraws += 1;
if (debugDisplays)
System.out.println("Score of agent 1 in game "+n+" is "+futures.get(n).get());
}
resultsAgent1asFirst.measure();
resultsAgent1asSecond.measure();
output("\nWin rate of agent 1 (UBFM) as 1st player");
output(resultsAgent1asFirst.toString());
output("\nWin rate of agent 1 (UBFM) as 2nd player");
output(resultsAgent1asSecond.toString());
output("\nNumber of draws: ");
output(Double.toString(nbDraws));
output("\nOverall mean: ");
output(Double.toString((resultsAgent1asFirst.mean()+resultsAgent1asSecond.mean())/2));
executor.shutdown();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
/**
* Compares a two of agents on a given game. Writes the results in the array resultsArray.
*/
private static void compareAgents(final Game game, final AI AI1, final AI AI2, final float[] resultsArray)
{
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
final List<AI> agents = new ArrayList<>();
agents.add(null);
agents.add(AI1);
agents.add(AI2);
game.start(context);
AI1.initAI(game, 1);
AI2.initAI(game, 2);
if (debugDisplays)
System.out.println("launching a playout");
game.playout(context, agents, thinkingTime, null, -1, 200, ThreadLocalRandom.current());
if (debugDisplays)
System.out.println("a game is over");
resultsArray[0] += (float) RankUtils.agentUtilities(context)[1];
resultsArray[1] += (float) RankUtils.agentUtilities(context)[2];
return;
}
private void output(String text)
{
System.out.print(text);
textOutput.append(text);
try
{
@SuppressWarnings("resource")
FileWriter myWriter = new FileWriter("/home/cyprien/Documents/M1/Internship/"+outputFile);
myWriter.write(textOutput.toString());
myWriter.close();
}
catch (final IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
return;
}
public static void main(String[] args)
{
evaluateUBFM = new EvaluateUBFM();
evaluateUBFM.runExperiment();
}
}
| 6,198 | 25.491453 | 116 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/HeuristicsTraining.java
|
package supplementary.experiments;
//import java.io.File;
//import java.io.FileWriter;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.concurrent.CountDownLatch;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.concurrent.Future;
//import java.util.concurrent.ThreadLocalRandom;
//
//import game.Game;
//import gnu.trove.list.array.TFloatArrayList;
//import main.collections.FVector;
//import main.collections.FastArrayList;
//import main.collections.Pair;
//import metadata.ai.heuristics.Heuristics;
//import metadata.ai.heuristics.terms.CentreProximity;
//import metadata.ai.heuristics.terms.ComponentValues;
//import metadata.ai.heuristics.terms.CornerProximity;
//import metadata.ai.heuristics.terms.CurrentMoverHeuristic;
//import metadata.ai.heuristics.terms.HeuristicTerm;
//import metadata.ai.heuristics.terms.Influence;
//import metadata.ai.heuristics.terms.InfluenceAdvanced;
//import metadata.ai.heuristics.terms.Intercept;
//import metadata.ai.heuristics.terms.LineCompletionHeuristic;
//import metadata.ai.heuristics.terms.Material;
//import metadata.ai.heuristics.terms.MobilityAdvanced;
//import metadata.ai.heuristics.terms.MobilitySimple;
//import metadata.ai.heuristics.terms.OwnRegionsCount;
//import metadata.ai.heuristics.terms.PlayerRegionsProximity;
//import metadata.ai.heuristics.terms.PlayerSiteMapCount;
//import metadata.ai.heuristics.terms.RegionProximity;
//import metadata.ai.heuristics.terms.Score;
//import metadata.ai.heuristics.terms.SidesProximity;
//import metadata.ai.heuristics.terms.ThreatenedMaterial;
//import metadata.ai.heuristics.terms.ThreatenedMaterialMultipleCount;
//import metadata.ai.heuristics.terms.UnthreatenedMaterial;
//import other.AI;
//import other.GameLoader;
//import other.RankUtils;
//import other.context.Context;
//import other.move.Move;
//import other.state.State;
//import other.trial.Trial;
//import search.minimax.BiasedUBFM;
//import search.minimax.UBFM;
//import utils.data_structures.transposition_table.TranspositionTableUBFM;
//import utils.data_structures.transposition_table.TranspositionTableUBFM.UBFMTTData;
////import weka.classifiers.Classifier;
//import weka.core.Instances;
//import weka.core.Utils;
//import weka.core.converters.ArffLoader;
//import weka.classifiers.Evaluation;
//import weka.classifiers.functions.LinearRegression;
/**
* Script to learn a set of heuristic terms and weight for a game, for it to be
* used by minimax based algorithm like Alpha-Beta search or UBFM.
*
* @author cyprien
*/
public class HeuristicsTraining
{
//
// private final boolean debugDisplays = true;
//
// /** Duration of the whole training in seconds: */
// private final double trainingDuration = 14400.;
//
// /** Thinking time of the AI in seconds: */
// private final float thinkingTime = 0.3f;
//
// /** Path of the directory with the files: */
// private static final String repository = "/data/learning/";
//
// private final String trainDataFile = "training.arff";
// private final String testDataFile = "testing.arff";
//
// private final StringBuffer trainDataARFF = new StringBuffer();
// private final StringBuffer testDataARFF = new StringBuffer();
//
// /** Probability that an entry gets assigned to the testing data set: */
// private final double proportionOfTestingEntries = 0.15;
//
// /** Score associated to a win: */
// private final float scoreWin = 20f;
//
// /** Number of playouts before the weights are updated */
// private final int numPlayoutsPerIteration = 40;
//
// /** Number of turns after which the games are stopped */
// private int maxNbTurns = 40;
//
// /** Probability of discarding an entry: */
// private final double probabilityDiscard = 0.9;
//
// /** Threshold of the heuristics weights (under it thy are not saved) */
// private final float heuristicWeightsThreshold = 0.001f;
//
// //-------------------------------------------------------------------------
//
// /** The different heuristic terms (with a weight of 1) */
// final List<HeuristicTerm> heuristicTermsList;
//
// final int nbParameters;
//
// private Game game;
//
// int numPlayers;
//
// /** Total number of calls of the recursive function to fill training data */
// int fillTrainingCallNumber;
//
// // Thread executor (maximum number of threads possible)
// final static int numThreads = Runtime.getRuntime().availableProcessors();
// final ExecutorService executor = Executors.newFixedThreadPool(numThreads); // note: was static on the previous file
//
// //-------------------------------------------------------------------------
//
// public HeuristicsTraining(String gameName)
// {
// game = GameLoader.loadGameFromName(gameName+".lud");
// numPlayers = game.players().count();
//
// heuristicTermsList = createHeuristicTerms(game);
//
// int nbParams = 0;
// for (HeuristicTerm heuristicTerm : heuristicTermsList)
// {
// heuristicTerm.init(game);
// final FVector params = heuristicTerm.paramsVector();
// if (params != null)
// nbParams += params.dim();
// else
// nbParams += 1;
// }
// this.nbParameters = nbParams;
// if (debugDisplays)
// System.out.println("Number of parameters : "+Integer.toString(nbParameters));
// }
//
// //-------------------------------------------------------------------------
//
//
// public static void main (String[] args)
// {
// String gameName;
// if (args.length > 0)
// gameName = args[0];
// else
// gameName = "Breakthrough";
//
// HeuristicsTraining heuristicTraining = new HeuristicsTraining(gameName);
//
// try {
// heuristicTraining.runHeuristicLearning();
// } catch (final Exception e) {
// e.printStackTrace();
// }
// }
//
// protected void runHeuristicLearning () throws Exception
// {
// final long startTime = System.currentTimeMillis();
// final long stopTime = startTime + (long) (trainingDuration * 1000);
//
// final int nbHeuristics = heuristicTermsList.size();
//
// final Heuristics heuristics = new Heuristics(heuristicTermsList.toArray(new HeuristicTerm[0]));
//
// final List<Double> correlationCoeficients = new ArrayList<Double>();
//
// final FVector heuristicWeights = heuristics.paramsVector();
//
// int numIteration = 0;
//
// while (System.currentTimeMillis() < stopTime)
// {
//
// //-----------------------------------------------------------------
//
// // Initialising the training data files:
// String[] dataFileNames = new String[] {trainDataFile,testDataFile};
// StringBuffer[] dataFileContents = new StringBuffer[] {trainDataARFF, testDataARFF};
// for (int k : new int[] {0,1})
// {
// dataFileContents[k].setLength(0);
// dataFileContents[k].append("@relation Heuristics_score_differences_and_value\n\n");
//
// // Filling the heuristic function's weight:
// dataFileContents[k].append("@attribute value NUMERIC\n");
//
// for (int i=0; i<nbHeuristics; i++)
// {
// FVector params = heuristicTermsList.get(i).paramsVector();
// if (params != null)
// for (int j=0; j<params.dim(); j++)
// dataFileContents[k].append("@attribute "+heuristicTermsList.get(i).getClass().getSimpleName()+Integer.toString(i)+"_"+Integer.toString(j)+" NUMERIC\n");
// else
// dataFileContents[k].append("@attribute "+heuristicTermsList.get(i).getClass().getSimpleName()+" NUMERIC\n");
// }
// dataFileContents[k].append("\n@data\n");
// }
//
// heuristics.updateParams(game, heuristicWeights, 0);
//
// System.out.println("Heuristics:");
// System.out.println(heuristics.toString());
// System.out.println(heuristics.paramsVector().toString());
//
// fillTrainingCallNumber = 0;
//
// // Run trials concurrently
// final CountDownLatch latch = new CountDownLatch(numPlayoutsPerIteration);
//
// final List<Future<Pair<String,String>>> futures = new ArrayList<Future<Pair<String,String>>>(numPlayoutsPerIteration);
//
// for (int k=0; k<numPlayoutsPerIteration; k++)
// {
// final int index = k;
// final int iterationNumber = numIteration;
//
// futures.add
// (
// executor.submit
// (
// () ->
// {
// try
// {
// // Generating training set for the linear regression:
// System.out.printf("\nBeginning the playout number %d of iteration %d:\n",index,iterationNumber);
//
// final Pair<String,String> res = generateATrainingSet(heuristics, 1+(index%2));
//
// latch.countDown();
//
// return res;
// }
// catch (final Exception e)
// {
// e.printStackTrace();
// return new Pair<String,String>("","");
// }
// }
// )
// );
// }
//
// latch.await(); // wait for all trials to finish
//
// Pair<String,String> outputs;
// for (int n=0; n<numPlayoutsPerIteration; ++n)
// {
// outputs = futures.get(n).get();
//
// trainDataARFF.append(outputs.key());
// testDataARFF.append(outputs.value());
// }
//
// // Saving data in a file
// for (int i : new int[] {0,1})
// {
// try {
// File directory = new File(String.valueOf(repository+"training/"));
// directory.mkdirs();
// FileWriter myWriter = new FileWriter(repository+"training/"+dataFileNames[i]);
// myWriter.write(dataFileContents[i].toString());
// myWriter.close();
// } catch (IOException e) {
// System.out.println("An error occurred.");
// e.printStackTrace();
// }
// }
//
// //-----------------------------------------------------------------
// // Updating the heuristicWeights with Machine Learning:
// System.out.println("\nUpdating the heuristicWeights with Machine Learning:");
//
//
// Instances trainDataSet = loadDataSet(trainDataFile);
// Instances testDataSet = loadDataSet(testDataFile);
//
// LinearRegression classifier = new LinearRegression();
//
// //classifier.setOptions(Utils.splitOptions("-S 1"));
//
// // Training:
// classifier.buildClassifier(trainDataSet);
//
// for (int i=0; i<nbParameters; i++)
// heuristicWeights.set(i, (float) classifier.coefficients()[i+1]);
//
// // Evaluating the classifier:
// Evaluation eval = new Evaluation(trainDataSet);
// eval.evaluateModel(classifier, testDataSet);
//
// correlationCoeficients.add(eval.correlationCoefficient());
//
// System.out.println("** Linear Regression Evaluation with Datasets **");
// System.out.println(eval.toSummaryString());
// System.out.print(" the expression for the input data as per algorithm is ");
// System.out.println(classifier);
//
// //---------------------------------------------------------------------
// // Saving weights in a file:
// try {
// File directory = new File(String.valueOf(repository+"/learned_heuristics/"));
// directory.mkdirs();
// FileWriter myWriter = new FileWriter(repository+"/learned_heuristics/"+game.name()+Integer.toString(numIteration)+".sav");
// myWriter.write(heuristics.toStringThresholded(heuristicWeightsThreshold));
// myWriter.close();
// } catch (IOException e) {
// System.out.println("An error occurred.");
// e.printStackTrace();
// }
// try {
// File directory = new File(String.valueOf(repository+"/parameters/"));
// directory.mkdirs();
// FileWriter myWriter = new FileWriter(repository+"/parameters/"+game.name()+Integer.toString(numIteration)+".sav");
// myWriter.write(heuristics.paramsVector().toString());
// myWriter.close();
// } catch (IOException e) {
// System.out.println("An error occurred.");
// e.printStackTrace();
// }
// try {
// FileWriter myWriter = new FileWriter(repository+"correlation_coeficients_"+game.name()+".sav");
// myWriter.write(toString(correlationCoeficients));
// myWriter.close();
// } catch (IOException e) {
// System.out.println("An error occurred.");
// e.printStackTrace();
// }
//
// numIteration += 1;
//
//// We consider that we have generated enough heuristic parameters after 75 iterations
// if (numIteration > 75)
// break;
// };
// System.out.println("Heuristic training done.");
//
// }
//
// public static Instances loadDataSet(String fileName) throws IOException
// {
// ArffLoader loader = new ArffLoader();
//
// loader.setSource(new File(repository + "training/"+fileName));
//
// Instances dataSet = loader.getDataSet();
//
// dataSet.setClassIndex(0); //argument is the index of score in the training entries
//
// return dataSet;
// }
//
// /**
// * Uses a transposition table to calculate the value associated to states and fill the training data.
// * Takes the value directly from the TT, and ignores leaves which are are not terminal states.
// *
// * @param TT
// * @return
// */
// protected Pair<String, String> generateATrainingSet (final Heuristics heuristics, final int maximisingPlayer)
// {
// // Setting up a playout:
// final Trial trial = new Trial(game);
// final Context context = new Context(game, trial);
//
// final UBFM AI = new UBFM(heuristics);
//
// AI.setIfFullPlayouts(true); // switches to the "Descent" algorithm
//// AI.setNbStateEvaluationsPerNode(6);
// AI.setSelectionEpsilon(0.3f);
// AI.savingSearchTreeDescription = false;
// AI.debugDisplay = false;
// AI.forceAMaximisingPlayer(maximisingPlayer);
// AI.setTTReset(false);
//
// final List<AI> agents = new ArrayList<>();
// agents.add(null);
// agents.add(AI);
// agents.add(AI);
//
// game.start(context);
//
// AI.initAI(game, maximisingPlayer);
//
// final Context initialContext = AI.copyContext(context); // used later
//
// game.playout(context, agents, thinkingTime, null, -1, maxNbTurns, ThreadLocalRandom.current()); // TODO: change max nb playout actions
//
// System.out.println("done");
//
//
// System.out.println("Result of maximising player: "+Double.toString(RankUtils.agentUtilities(context)[maximisingPlayer]));
//
// if (debugDisplays)
// {
// System.out.println("\nGenerating training set for the linear regression:\n");
// }
//
// System.out.println("Number of entries in the TT: "+Integer.toString(AI.getTranspositionTable().nbEntries()));
//
// final long zobrist = initialContext.state().fullHash(initialContext);
// final UBFMTTData tableData = AI.getTranspositionTable().retrieve(zobrist);
//
// // Marking the value in the TT so that it is not visited again in the same recursive call
// AI.getTranspositionTable().store(tableData.fullHash, tableData.value, tableData.depth, TranspositionTableUBFM.MARKED, tableData.sortedScoredMoves);
//
// final StringBuffer trainDataEntries = new StringBuffer();
// final StringBuffer testDataEntries = new StringBuffer();
//
// float rootValue = fillTrainingData(AI, initialContext, trainDataEntries, testDataEntries, maximisingPlayer);
//
// if (debugDisplays)
// {
// System.out.println();
// System.out.printf("Recursive calls of the function to fill the training data: %d \n", fillTrainingCallNumber);
// }
//
// // Validating the value in the TT so that it is not visited again
// AI.getTranspositionTable().store(tableData.fullHash, rootValue, tableData.depth, TranspositionTableUBFM.VALIDATED, tableData.sortedScoredMoves);
//
// return new Pair<String,String>(trainDataEntries.toString(), testDataEntries.toString());
// }
//
// /**
// * Recursive function to fill the training data.
// * The value of a state is its value in the search tree ("tree learning").
// * The leaves of the search tree which are not terminal game states are ignored.
// *
// * @param TT
// * @param context
// */
// protected float fillTrainingData
// (
// final UBFM AI,
// final Context context,
// final StringBuffer trainingEntries,
// final StringBuffer testingEntries,
// final int maximisingPlayer
// )
// {
//
// // Recursive call:
// fillTrainingCallNumber += 1;
//
// if (debugDisplays && (fillTrainingCallNumber % 10000 == 0))
// {
// System.out.print(Integer.toString(fillTrainingCallNumber)+"...");
// //System.out.println("Number of validate entries:"+Integer.toString(AI.transpositionTable.nbMarkedEntries()));
// //System.out.println();
// }
//
// boolean registeringValue = false;
// float value = Float.NaN;
//
// if (context.trial().over() || !context.active(maximisingPlayer))
// {
// // terminal node (at least for maximising player)
// value = (float) RankUtils.agentUtilities(context)[maximisingPlayer];
// registeringValue = true;
// //System.out.println("terminal node");
// }
// else
// {
// final State state = context.state();
// final long zobrist = state.fullHash(context);
// final UBFMTTData tableData = AI.getTranspositionTable().retrieve(zobrist);
//
// if (tableData.sortedScoredMoves != null)
// {
// registeringValue = true;
//
// value = tableData.value;
//
// final FastArrayList<Move> legalMoves = game.moves(context).moves();
// final int nbMoves = legalMoves.size();
//// final int mover = state.playerToAgent(state.mover());
//
// final TFloatArrayList childrenValues = new TFloatArrayList();
//
// for (int i=0; i<nbMoves; i++)
// {
// final Context contextCopy = AI.copyContext(context);
// final Move move = legalMoves.get(i);
//
// game.apply(contextCopy, move);
//
// final State newState = contextCopy.state();
// final long newZobrist = newState.fullHash(contextCopy);
// final UBFMTTData newTableData = AI.getTranspositionTable().retrieve(newZobrist);
//
// if (newTableData != null)
// {
// if (newTableData.valueType != TranspositionTableUBFM.MARKED)
// {
// if (newTableData.valueType != TranspositionTableUBFM.VALIDATED)
// {
//
// // Marking the value in the TT so that it is not visited again in the same recursive call
// AI.getTranspositionTable().store( newTableData.fullHash, newTableData.value,
// newTableData.depth, TranspositionTableUBFM.MARKED,
// newTableData.sortedScoredMoves);
//
// final float childValue = fillTrainingData(AI, contextCopy, trainingEntries, testingEntries, maximisingPlayer);
//
// // Un-marking the value in the TT so that it is not considered as a draw if encountered elsewhere in the tree
// AI.getTranspositionTable().store( newTableData.fullHash, childValue,
// newTableData.depth, TranspositionTableUBFM.VALIDATED,
// newTableData.sortedScoredMoves);
// }
// childrenValues.add(tableData.value);
// }
// else
// {
// // we consider that one can always chose to go back to a previously visited state,
// // so it is a draw as far as this path is concerned
// childrenValues.add(0f);
// }
// }
// }
// }
//
// if (value > scoreWin)
// value = scoreWin;
// else if (value < -scoreWin)
// value = -scoreWin;
//
// //-----------------------------------------------------------------
// // Adding entry with heuristic value differences:
//
// if ((registeringValue) && (Math.random()>probabilityDiscard))
// {
//
// StringBuffer dataFileContent;
// if (Math.random()>proportionOfTestingEntries)
// dataFileContent = trainingEntries;
// else
// dataFileContent = testingEntries;
//
// final String valueEntry = String.format("%.2g", value);
// dataFileContent.append(valueEntry+" ".repeat(14-valueEntry.length())+",");
//
// final FVector trainingEntry = AI.heuristicValueFunction().computeStateFeatureVector(context, maximisingPlayer);
//
// for (int k=0; k<nbParameters; k++)
// {
// final String entry = String.format("%.8g", trainingEntry.get(k));
// dataFileContent.append(entry+" ".repeat(14-entry.length())+",");
// }
//
// dataFileContent.deleteCharAt(dataFileContent.length()-1); //deleting the last comma
// dataFileContent.append("\n");
// }
// }
//
// return value;
// }
//
// //-------------------------------------------------------------------------
//
//
// protected List<HeuristicTerm> createHeuristicTerms (final Game game)
// {
// /** The initial weight of the heuristics is important for the initialisation */
//
// List<HeuristicTerm> heuristicTerms = new ArrayList<HeuristicTerm>();
//
// if (CurrentMoverHeuristic.isApplicableToGame(game))
// heuristicTerms.add(new CurrentMoverHeuristic(null, 0f));
//
// if (Material.isApplicableToGame(game))
// heuristicTerms.add(new Material(null, 1f, null, null));
//
// if (MobilityAdvanced.isApplicableToGame(game))
// heuristicTerms.add(new MobilityAdvanced(null, 0f));
//
//// if (InfluenceAdvanced.isApplicableToGame(game))
//// heuristicTerms.add(new InfluenceAdvanced(null, 0f));
//
//// if (LineCompletionHeuristic.isApplicableToGame(game))
//// heuristicTerms.add(new LineCompletionHeuristic(null, 0f, null));
//
//
//// if (OwnRegionsCount.isApplicableToGame(game))
//// heuristicTerms.add(new OwnRegionsCount(null, 0f));
//
//// if (PlayerSiteMapCount.isApplicableToGame(game))
//// heuristicTerms.add(new PlayerSiteMapCount(null, 0f));
////
//// if (Score.isApplicableToGame(game))
//// heuristicTerms.add(new Score(null, 0f));
//
//// if (CentreProximity.isApplicableToGame(game))
//// heuristicTerms.add(new CentreProximity(null, 0f, null));
//
//// if (ComponentValues.isApplicableToGame(game))
//// {
//// heuristicTerms.add(new ComponentValues(null, Float.valueOf(defaultWeight), null, null));
//// for (final Pair[] componentPairs : allComponentPairsCombinations)
//// heuristicTerms.add(new ComponentValues(null, Float.valueOf(defaultWeight), componentPairs, null));
//// }
//
//// if (CornerProximity.isApplicableToGame(game))
//// heuristicTerms.add(new CornerProximity(null, 0f, null));
//
// if (SidesProximity.isApplicableToGame(game))
// heuristicTerms.add(new SidesProximity(null, 0f, null));
//
//// if (PlayerRegionsProximity.isApplicableToGame(game))
//// {
//// for (int p = 1; p <= game.players().count(); ++p)
//// {
//// heuristicTerms.add(new PlayerRegionsProximity(null, 0f, p, null));
//// }
//// }
//
// /*
// if (RegionProximity.isApplicableToGame(game))
// {
// for (int i = 0; i < game.equipment().regions().length; ++i)
// {
// heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), null));
// for (final Pair[] componentPairs : allComponentPairsCombinations)
// heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), componentPairs));
// }
// }
// */
//
// return heuristicTerms;
// }
//
// //-------------------------------------------------------------------------
//
// protected String toString(final float[] weights)
// {
// final StringBuffer stringBuilder = new StringBuffer();
//
// for (int i=0; i<weights.length; i++)
// stringBuilder.append(String.format("%.8g\n", weights[i]));
//
// return stringBuilder.toString();
// }
//
// protected String toString(final List<Double> values)
// {
// final StringBuffer stringBuilder = new StringBuffer();
//
// stringBuilder.append("[");
// for (int i=0; i<values.size(); i++)
// stringBuilder.append(String.format("%.8g,", values.get(i)));
//
// stringBuilder.deleteCharAt(stringBuilder.length()-1);
// stringBuilder.append("]");
// return stringBuilder.toString();
// }
}
| 23,652 | 34.515015 | 161 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/analysis/CustomPlayoutsResultsCSV.java
|
package supplementary.experiments.analysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import game.rules.phase.Phase;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
import other.playout.Playout;
import other.playout.PlayoutAddToEmpty;
import other.playout.PlayoutFilter;
import other.playout.PlayoutNoRepetition;
/**
* Generates a CSV with results from timing custom playouts vs. non-custom playouts
*
* @author Dennis Soemers
*/
public class CustomPlayoutsResultsCSV
{
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private CustomPlayoutsResultsCSV()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* @param game
* @param type
* @return True if the given game uses the given type of custom playout
*/
private static boolean gameUsesPlayoutType(final Game game, final Class<? extends Playout> type)
{
if (game.mode().playout() != null && game.mode().playout().getClass().isAssignableFrom(type))
return true;
for (final Phase phase : game.rules().phases())
if (phase.playout() != null && phase.playout().getClass().isAssignableFrom(type))
return true;
return false;
}
/**
* Generates our CSV file
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSV(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String customResultsDir = argParse.getValueString("--custom-results-dir");
customResultsDir = customResultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!customResultsDir.endsWith("/"))
customResultsDir += "/";
String noCustomResultsDir = argParse.getValueString("--no-custom-results-dir");
noCustomResultsDir = noCustomResultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!noCustomResultsDir.endsWith("/"))
noCustomResultsDir += "/";
final String outFile = argParse.getValueString("--out-file");
final List<String> rows = new ArrayList<String>(); // Rows to write in new CSV
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
int totNumGames = 0;
int totNumRulesets = 0;
int numGamesWithCustom = 0;
int numRulesetsWithCustom = 0;
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
++totNumGames;
boolean foundRulesetWithCustom = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
++totNumRulesets;
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
if (game.isStacking())
continue;
if (game.hiddenInformation())
continue;
if (!game.hasCustomPlayouts())
continue;
if (!foundRulesetWithCustom)
{
foundRulesetWithCustom = true;
++numGamesWithCustom;
}
++numRulesetsWithCustom;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File customResultFile = new File(customResultsDir + filepathsGameName + filepathsRulesetName + ".csv");
final File noCustomResultFile = new File(noCustomResultsDir + filepathsGameName + filepathsRulesetName + ".csv");
if (customResultFile.exists() && noCustomResultFile.exists())
{
final String customContents = FileHandling.loadTextContentsFromFile(customResultFile.getAbsolutePath());
final String noCustomContents = FileHandling.loadTextContentsFromFile(noCustomResultFile.getAbsolutePath());
final String[] customLines = customContents.split(Pattern.quote("\n"));
final String[] noCustomLines = noCustomContents.split(Pattern.quote("\n"));
// Second line has results, first line is just column headers
final String[] customRowSplit = customLines[1].split(Pattern.quote(","));
final String[] noCustomRowSplit = noCustomLines[1].split(Pattern.quote(","));
// Second result of row is playouts per second, we'll take that
final double customResult = Double.parseDouble(customRowSplit[1]);
final double noCustomResult = Double.parseDouble(noCustomRowSplit[1]);
final double ratio = customResult / noCustomResult;
// Third result of row is moves per second
final double customMovesPerSec = Double.parseDouble(customRowSplit[2]);
final double noCustomMovesPerSec = Double.parseDouble(noCustomRowSplit[2]);
final double movesPerPlayoutRatio = (customMovesPerSec / customResult) / (noCustomMovesPerSec / noCustomResult);
final double deltaMovesPerEpisode = (customMovesPerSec / customResult) - (noCustomMovesPerSec / noCustomResult);
if (gameUsesPlayoutType(game, PlayoutAddToEmpty.class))
{
rows.add
(
StringRoutines.join
(
",",
"Add-To-Empty",
String.valueOf(ratio),
String.valueOf(noCustomResult),
String.valueOf(customResult),
String.valueOf(movesPerPlayoutRatio),
String.valueOf(deltaMovesPerEpisode),
filepathsGameName + filepathsRulesetName
)
);
}
if (gameUsesPlayoutType(game, PlayoutFilter.class))
{
rows.add
(
StringRoutines.join
(
",",
"Filter",
String.valueOf(ratio),
String.valueOf(noCustomResult),
String.valueOf(customResult),
String.valueOf(movesPerPlayoutRatio),
String.valueOf(deltaMovesPerEpisode),
filepathsGameName + filepathsRulesetName
)
);
}
if (gameUsesPlayoutType(game, PlayoutNoRepetition.class))
{
rows.add
(
StringRoutines.join
(
",",
"No-Repetition",
String.valueOf(ratio),
String.valueOf(noCustomResult),
String.valueOf(customResult),
String.valueOf(movesPerPlayoutRatio),
String.valueOf(deltaMovesPerEpisode),
filepathsGameName + filepathsRulesetName
)
);
}
}
else if (customResultFile.exists() || noCustomResultFile.exists())
{
System.err.println("One exists but the other doesn't!");
}
}
}
System.out.println("Num games = " + totNumGames);
System.out.println("Num rulesets = " + totNumRulesets);
System.out.println("Num games with custom playout = " + numGamesWithCustom);
System.out.println("Num rulesets with custom playout = " + numRulesetsWithCustom);
try (final PrintWriter writer = new UnixPrintWriter(new File(outFile), "UTF-8"))
{
// Write header
writer.println
(
StringRoutines.join
(
",",
"Playout",
"Speedup",
"BaselinePlayoutsPerSec",
"CustomPlayoutsPerSec",
"MovesPerEpisodeRatio",
"DeltaMovesPerEpisode",
"GameRuleset"
)
);
// Write rows
for (final String row : rows)
{
writer.println(row);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates single CSV with results."
);
argParse.addOption(new ArgOption()
.withNames("--custom-results-dir")
.help("Directory with results for custom playouts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--no-custom-results-dir")
.help("Directory with results for no-custom playouts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath for CSV file to write")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSV(argParse);
}
//-------------------------------------------------------------------------
}
| 10,659 | 30.078717 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/analysis/EvaluateBaseAgents.java
|
package supplementary.experiments.analysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
import utils.DBGameInfo;
/**
* Generates a CSV file with the best base agent per ruleset
*
* @author Dennis Soemers
*/
public class EvaluateBaseAgents
{
/**
* Constructor (don't need this)
*/
private EvaluateBaseAgents()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our CSV
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSV(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String resultsDir = argParse.getValueString("--results-dir");
resultsDir = resultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!resultsDir.endsWith("/"))
resultsDir += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<List<String>> rowStringLists = new ArrayList<List<String>>();
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File rulesetResultsDir = new File(resultsDir + filepathsGameName + filepathsRulesetName);
if (rulesetResultsDir.exists())
{
final List<String> rowStringList = new ArrayList<String>();
// First column: just game name
rowStringList.add(gameName);
// Second column: just ruleset name
rowStringList.add(fullRulesetName);
// Third column: game + ruleset name
rowStringList.add(DBGameInfo.getUniqueName(game));
// Map from agent names to sum of scores for this ruleset
final TObjectDoubleMap<String> agentScoreSums = new TObjectDoubleHashMap<String>();
// Map from agent names to how often we observed this agent in this ruleset
final TObjectIntMap<String> agentCounts = new TObjectIntHashMap<String>();
final File[] matchupDirs = rulesetResultsDir.listFiles();
for (final File matchupDir : matchupDirs)
{
if (matchupDir.isDirectory())
{
final String[] resultLines =
FileHandling.loadTextContentsFromFile
(
matchupDir.getAbsolutePath() + "/alpha_rank_data.csv"
).split(Pattern.quote("\n"));
// Skip index 0, that's just the headings
for (int i = 1; i < resultLines.length; ++i)
{
final String line = resultLines[i];
final int idxQuote1 = 0;
final int idxQuote2 = line.indexOf("\"", idxQuote1 + 1);
final int idxQuote3 = line.indexOf("\"", idxQuote2 + 1);
final int idxQuote4 = line.indexOf("\"", idxQuote3 + 1);
final String agentsTuple =
line
.substring(idxQuote1 + 2, idxQuote2 - 1)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("'"), "");
final String scoresTuple =
line
.substring(idxQuote3 + 2, idxQuote4 - 1)
.replaceAll(Pattern.quote(" "), "");
final String[] agentNames = agentsTuple.split(Pattern.quote(","));
final String[] scores = scoresTuple.split(Pattern.quote(","));
for (int j = 0; j < agentNames.length; ++j)
{
// Convert score to "win percentage"
final double score = ((Double.parseDouble(scores[j]) + 1.0) / 2.0) * 100.0;
agentScoreSums.adjustOrPutValue(agentNames[j], score, score);
agentCounts.adjustOrPutValue(agentNames[j], 1, 1);
}
}
}
}
// Figure out which agent has best score
double bestScore = -1.0;
String bestAgent = "";
for (final String agent : agentScoreSums.keySet())
{
final double score = agentScoreSums.get(agent) / agentCounts.get(agent);
if (score > bestScore)
{
bestScore = score;
bestAgent = agent;
}
}
// Fourth column: top agent
rowStringList.add(bestAgent);
// Fifth column: top score
rowStringList.add("" + bestScore);
// All strings for this row are complete
rowStringLists.add(rowStringList);
}
else
{
System.out.println(rulesetResultsDir + " does not exist");
}
}
}
String outDir = argParse.getValueString("--out-dir");
if (!outDir.endsWith("/"))
outDir += "/";
final String outFilename = "BestBaseAgents.csv";
try (final PrintWriter writer = new PrintWriter(new File(outDir + outFilename), "UTF-8"))
{
// First write the headings
final List<String> headings = new ArrayList<String>();
headings.add("Game");
headings.add("Ruleset");
headings.add("GameRuleset");
headings.add("Top Agent");
headings.add("Top Score");
writer.println(StringRoutines.join(",", headings));
// Now write all the rows
for (int i = 0; i < rowStringLists.size(); ++i)
{
writer.println(StringRoutines.join(",", rowStringLists.get(i)));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates a CSV file containing top base agent per ruleset."
);
argParse.addOption(new ArgOption()
.withNames("--results-dir")
.help("Filepath for directory with per-game subdirectories of matchup directories.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-dir")
.help("Output directory to save output files to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSV(argParse);
}
//-------------------------------------------------------------------------
}
| 8,976 | 30.609155 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/analysis/EvaluateStartingHeuristics.java
|
package supplementary.experiments.analysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
import utils.DBGameInfo;
/**
* Generates a CSV file with the best base/starting heuristic per ruleset
*
* @author Dennis Soemers
*/
public class EvaluateStartingHeuristics
{
/**
* Constructor (don't need this)
*/
private EvaluateStartingHeuristics()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our CSV
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSV(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String resultsDir = argParse.getValueString("--results-dir");
resultsDir = resultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!resultsDir.endsWith("/"))
resultsDir += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<List<String>> rowStringLists = new ArrayList<List<String>>();
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File rulesetResultsDir = new File(resultsDir + filepathsGameName + filepathsRulesetName);
if (rulesetResultsDir.exists() && rulesetResultsDir.list().length > 0)
{
final List<String> rowStringList = new ArrayList<String>();
// First column: just game name
rowStringList.add(gameName);
// Second column: just ruleset name
rowStringList.add(fullRulesetName);
// Third column: game + ruleset name
rowStringList.add(DBGameInfo.getUniqueName(game));
// Map from heuristic names to sum of scores for this ruleset
final TObjectDoubleMap<String> heuristicScoreSums = new TObjectDoubleHashMap<String>();
// Map from heuristic names to how often we observed this heuristic in this ruleset
final TObjectIntMap<String> heuristicCounts = new TObjectIntHashMap<String>();
final File[] matchupDirs = rulesetResultsDir.listFiles();
for (final File matchupDir : matchupDirs)
{
if (matchupDir.isDirectory())
{
final String[] resultLines =
FileHandling.loadTextContentsFromFile(
matchupDir.getAbsolutePath() + "/alpha_rank_data.csv"
).split(Pattern.quote("\n"));
// Skip index 0, that's just the headings
for (int i = 1; i < resultLines.length; ++i)
{
final String line = resultLines[i];
final int idxQuote1 = 0;
final int idxQuote2 = line.indexOf("\"", idxQuote1 + 1);
final int idxQuote3 = line.indexOf("\"", idxQuote2 + 1);
final int idxQuote4 = line.indexOf("\"", idxQuote3 + 1);
final String heuristicsTuple =
line
.substring(idxQuote1 + 2, idxQuote2 - 1)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("'"), "");
final String scoresTuple =
line
.substring(idxQuote3 + 2, idxQuote4 - 1)
.replaceAll(Pattern.quote(" "), "");
final String[] heuristicNames = heuristicsTuple.split(Pattern.quote(","));
final String[] scores = scoresTuple.split(Pattern.quote(","));
for (int j = 0; j < heuristicNames.length; ++j)
{
// Convert score to "win percentage"
final double score = ((Double.parseDouble(scores[j]) + 1.0) / 2.0) * 100.0;
heuristicScoreSums.adjustOrPutValue(heuristicNames[j], score, score);
heuristicCounts.adjustOrPutValue(heuristicNames[j], 1, 1);
}
}
}
}
// Figure out which heuristic has best score
double bestScore = -1.0;
String bestHeuristic = "";
for (final String heuristic : heuristicScoreSums.keySet())
{
final double score = heuristicScoreSums.get(heuristic) / heuristicCounts.get(heuristic);
if (score > bestScore)
{
bestScore = score;
bestHeuristic = heuristic;
}
}
// Fourth column: top heuristic
rowStringList.add(bestHeuristic);
// Fifth column: top score
rowStringList.add("" + bestScore);
// All strings for this row are complete
rowStringLists.add(rowStringList);
}
else
{
System.out.println(rulesetResultsDir + " does not exist");
}
}
}
String outDir = argParse.getValueString("--out-dir");
if (!outDir.endsWith("/"))
outDir += "/";
final String outFilename = "BestStartingHeuristics.csv";
try (final PrintWriter writer = new PrintWriter(new File(outDir + outFilename), "UTF-8"))
{
// First write the headings
final List<String> headings = new ArrayList<String>();
headings.add("Game");
headings.add("Ruleset");
headings.add("GameRuleset");
headings.add("Top Heuristic");
headings.add("Top Score");
writer.println(StringRoutines.join(",", headings));
// Now write all the rows
for (int i = 0; i < rowStringLists.size(); ++i)
{
writer.println(StringRoutines.join(",", rowStringLists.get(i)));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates a CSV file containing top heuristic per ruleset."
);
argParse.addOption(new ArgOption()
.withNames("--results-dir")
.help("Filepath for directory with per-game subdirectories of matchup directories.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-dir")
.help("Output directory to save output files to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSV(argParse);
}
//-------------------------------------------------------------------------
}
| 9,146 | 31.321555 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/analysis/GenerateBaseHeuristicScoresCSV.java
|
package supplementary.experiments.analysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
import utils.DBGameInfo;
/**
* Generates a CSV file containing the scores for all base heuristics
* for all games.
*
* @author Dennis Soemers
*/
public class GenerateBaseHeuristicScoresCSV
{
/**
* Constructor (don't need this)
*/
private GenerateBaseHeuristicScoresCSV()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our CSV
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSV(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String resultsDir = argParse.getValueString("--results-dir");
resultsDir = resultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!resultsDir.endsWith("/"))
resultsDir += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<List<String>> rowStringLists = new ArrayList<List<String>>();
final List<TObjectDoubleMap<String>> heuristicScoreSumsList = new ArrayList<TObjectDoubleMap<String>>();
final List<TObjectIntMap<String>> heuristicCountsList = new ArrayList<TObjectIntMap<String>>();
final Set<String> allHeuristicNames = new HashSet<String>();
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File rulesetResultsDir = new File(resultsDir + filepathsGameName + filepathsRulesetName);
if (rulesetResultsDir.exists())
{
final List<String> rowStringList = new ArrayList<String>();
// First column: game name
rowStringList.add(gameName);
// Second column: ruleset name
rowStringList.add(fullRulesetName);
// Third column: game + ruleset name
rowStringList.add(DBGameInfo.getUniqueName(game));
// Map from heuristic names to sum of scores for this ruleset
final TObjectDoubleMap<String> heuristicScoreSums = new TObjectDoubleHashMap<String>();
// Map from heuristic names to how often we observed this heuristic in this ruleset
final TObjectIntMap<String> heuristicCounts = new TObjectIntHashMap<String>();
final File[] matchupDirs = rulesetResultsDir.listFiles();
for (final File matchupDir : matchupDirs)
{
if (matchupDir.isDirectory())
{
final String[] resultLines =
FileHandling.loadTextContentsFromFile(
matchupDir.getAbsolutePath() + "/alpha_rank_data.csv"
).split(Pattern.quote("\n"));
// Skip index 0, that's just the headings
for (int i = 1; i < resultLines.length; ++i)
{
final String line = resultLines[i];
final int idxQuote1 = 0;
final int idxQuote2 = line.indexOf("\"", idxQuote1 + 1);
final int idxQuote3 = line.indexOf("\"", idxQuote2 + 1);
final int idxQuote4 = line.indexOf("\"", idxQuote3 + 1);
final String heuristicsTuple =
line
.substring(idxQuote1 + 2, idxQuote2 - 1)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("'"), "");
final String scoresTuple =
line
.substring(idxQuote3 + 2, idxQuote4 - 1)
.replaceAll(Pattern.quote(" "), "");
final String[] heuristicNames = heuristicsTuple.split(Pattern.quote(","));
final String[] scores = scoresTuple.split(Pattern.quote(","));
for (int j = 0; j < heuristicNames.length; ++j)
{
// Convert score to "win percentage"
final double score = ((Double.parseDouble(scores[j]) + 1.0) / 2.0) * 100.0;
heuristicScoreSums.adjustOrPutValue(heuristicNames[j], score, score);
heuristicCounts.adjustOrPutValue(heuristicNames[j], 1, 1);
allHeuristicNames.add(heuristicNames[j]);
}
}
}
}
// All strings for this row are complete...ish for now
rowStringLists.add(rowStringList);
heuristicScoreSumsList.add(heuristicScoreSums);
heuristicCountsList.add(heuristicCounts);
}
}
}
final List<String> sortedHeuristicNames = new ArrayList<String>(allHeuristicNames);
Collections.sort(sortedHeuristicNames);
String outDir = argParse.getValueString("--out-dir");
if (!outDir.endsWith("/"))
outDir += "/";
final String outFilename = argParse.getValueBool("--merge-region-heuristics") ? "BaseHeuristicScoresMerged.csv" : "BaseHeuristicScores.csv";
try (final PrintWriter writer = new PrintWriter(new File(outDir + outFilename), "UTF-8"))
{
// First write the headings
final List<String> headings = new ArrayList<String>();
headings.add("Game");
headings.add("Ruleset");
headings.add("GameRuleset");
headings.addAll(sortedHeuristicNames);
if (argParse.getValueBool("--merge-region-heuristics"))
{
String lastMerged = "";
for (int i = 3; i < headings.size(); /**/)
{
final String origHeading = headings.get(i);
if (StringRoutines.isDigit(origHeading.charAt(origHeading.length() - 1)))
{
final String truncatedHeading = origHeading.substring(0, origHeading.lastIndexOf("_"));
if (!lastMerged.equals(truncatedHeading))
{
lastMerged = truncatedHeading;
headings.set(i, truncatedHeading);
}
else
{
headings.remove(i);
}
}
else
{
++i;
}
}
}
writer.println(StringRoutines.join(",", headings));
// Now write all the rows
for (int i = 0; i < rowStringLists.size(); ++i)
{
final List<String> rowStringList = rowStringLists.get(i);
final TObjectDoubleMap<String> scoreSumsMap = heuristicScoreSumsList.get(i);
final TObjectIntMap<String> heuristicCountsMap = heuristicCountsList.get(i);
String lastMerged = "";
for (final String heuristicName : sortedHeuristicNames)
{
if (scoreSumsMap.containsKey(heuristicName))
{
if (argParse.getValueBool("--merge-region-heuristics") && StringRoutines.isDigit(heuristicName.charAt(heuristicName.length() - 1)))
{
final String truncatedName = heuristicName.substring(0, heuristicName.lastIndexOf("_"));
if (!lastMerged.equals(truncatedName))
{
lastMerged = truncatedName;
rowStringList.add("" + scoreSumsMap.get(heuristicName) / heuristicCountsMap.get(heuristicName));
}
else
{
final double prevScore;
if (rowStringList.get(rowStringList.size() - 1).length() > 0)
prevScore = Double.parseDouble(rowStringList.get(rowStringList.size() - 1));
else
prevScore = Double.NEGATIVE_INFINITY;
final double newScore = scoreSumsMap.get(heuristicName) / heuristicCountsMap.get(heuristicName);
if (newScore > prevScore)
rowStringList.set(rowStringList.size() - 1, "" + newScore);
}
}
else
{
rowStringList.add("" + scoreSumsMap.get(heuristicName) / heuristicCountsMap.get(heuristicName));
}
}
else
{
if (argParse.getValueBool("--merge-region-heuristics") && StringRoutines.isDigit(heuristicName.charAt(heuristicName.length() - 1)))
{
final String truncatedName = heuristicName.substring(0, heuristicName.lastIndexOf("_"));
if (!lastMerged.equals(truncatedName))
{
lastMerged = truncatedName;
rowStringList.add("");
}
}
else
{
rowStringList.add("");
}
}
}
writer.println(StringRoutines.join(",", rowStringList));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates a CSV file containing the scores for all base heuristics for all games."
);
argParse.addOption(new ArgOption()
.withNames("--results-dir")
.help("Filepath for directory with per-game subdirectories of matchup directories.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-dir")
.help("Output directory to save output files to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--merge-region-heuristics")
.help("If true, we'll merge all region proximity heuristics with different region indices.")
.withType(OptionTypes.Boolean));
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSV(argParse);
}
//-------------------------------------------------------------------------
}
| 11,888 | 32.490141 | 142 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/analysis/RulesetConceptsUCT.java
|
package supplementary.experiments.analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import gnu.trove.list.array.TDoubleArrayList;
import main.collections.ArrayUtils;
/**
* Helper class to load and use the data stored in our RulesetConceptsUCT.csv file.
* Note that this file is in a private repo, so users with only the public repo
* will be unable to load this.
*
* @author Dennis Soemers
*/
public class RulesetConceptsUCT
{
//-------------------------------------------------------------------------
/**
* Filepath for our CSV file. Since this only works with access to private repo
* anyway, the filepath has been hardcoded for use from Eclipse.
*
* This would usually be private and final, but making it public and non-final
* is very useful for editing the filepath when running on cluster (where LudiiPrivate
* is not available).
*/
public static String FILEPATH = "../../LudiiPrivate/DataMiningScripts/Sklearn/res/Input/rulesetConceptsUCT.csv";
/** Names of our columns */
private static String[] columnNames = null;
/** Map to store all our data, from ruleset names to vectors of values */
private static Map<String, TDoubleArrayList> map = null;
//-------------------------------------------------------------------------
/**
* No constructor
*/
private RulesetConceptsUCT()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* @param rulesetName
* @param columnName
* @return Value for given ruleset name and column name
*/
public static double getValue(final String rulesetName, final String columnName)
{
if (map == null)
loadData();
return getValue(rulesetName, ArrayUtils.indexOf(columnName, columnNames));
}
/**
* @param rulesetName
* @param columnIdx
* @return Value for given ruleset name and column index
*/
public static double getValue(final String rulesetName, final int columnIdx)
{
if (map == null)
loadData();
final TDoubleArrayList vector = map.get(rulesetName);
if (vector == null)
{
System.out.println("no data for " + rulesetName);
return Double.NaN;
}
return vector.getQuick(columnIdx);
}
//-------------------------------------------------------------------------
/**
* Load our data from the CSV file
*/
private static void loadData()
{
try (final BufferedReader reader = new BufferedReader(new FileReader(new File(FILEPATH))))
{
columnNames = reader.readLine().split(Pattern.quote(","));
map = new HashMap<String, TDoubleArrayList>();
for (String line; (line = reader.readLine()) != null; /**/)
{
final String[] lineSplit = line.split(Pattern.quote(","));
final String rulesetName = lineSplit[0];
final TDoubleArrayList vector = new TDoubleArrayList();
for (int i = 1; i < lineSplit.length; ++i)
{
if (lineSplit[i].isEmpty())
vector.add(Double.NaN);
else if (lineSplit[i].equals("null"))
vector.add(Double.NaN);
else
vector.add(Double.parseDouble(lineSplit[i]));
}
map.put(rulesetName, vector);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
}
| 3,403 | 26.015873 | 113 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/analysis/WriteGameRulesetCategories.java
|
package supplementary.experiments.analysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
/**
* For every game-ruleset subdirectory in some directory, write a little
* file telling us what category that game is listed under.
*
* @author Dennis Soemers
*/
public class WriteGameRulesetCategories
{
//-------------------------------------------------------------------------
private static void writeGameRulesetCategories(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final Map<String, String> gameCategories = new HashMap<String, String>();
final String gameCategoriesFileContents = FileHandling.loadTextContentsFromFile("../Mining/res/categories/GameCategories.csv");
final String[] gameCategoryLines = gameCategoriesFileContents.split(Pattern.quote("\n"));
for (final String line : gameCategoryLines)
{
final String[] splitLine = line.replaceAll(Pattern.quote("\""), "").split(Pattern.quote(","));
String gameName = StringRoutines.cleanGameName(splitLine[0]);
final String category = splitLine[1];
if (gameCategories.containsKey(gameName))
gameCategories.put(gameName, gameCategories.get(gameName) + "/" + category);
else
gameCategories.put(gameName, category);
}
for (final String gameName : allGameNames)
{
final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String shortGameName = gameNameSplit[gameNameSplit.length - 1];
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName);
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName, fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.hasSubgames())
continue;
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.isStacking())
continue;
if (game.isBoardless())
continue;
if (game.hiddenInformation())
continue;
String baseDir = argParse.getValueString("--base-dir");
if (baseDir.endsWith("/"))
baseDir = baseDir.substring(0, baseDir.length() - 1);
final File gameRulesetDir =
new File
(
baseDir
+
StringRoutines.cleanGameName(("/" + shortGameName).replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
StringRoutines.cleanRulesetName(fullRulesetName).replaceAll(Pattern.quote("/"), "_")
+
"/"
);
if (!gameRulesetDir.exists() || !gameRulesetDir.isDirectory())
continue;
final String categoryFilepath = gameRulesetDir.getAbsolutePath() + "/Category.txt";
System.out.println("Writing: " + categoryFilepath + "...");
try (final PrintWriter writer = new PrintWriter(categoryFilepath, "UTF-8"))
{
writer.println(gameCategories.get(StringRoutines.cleanGameName((shortGameName).replaceAll(Pattern.quote(".lud"), ""))));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"In every game-ruleset subdirectory of a larger directory, writes a file with the game's category."
);
argParse.addOption(new ArgOption()
.withNames("--base-dir")
.help("The base directory (with game-ruleset subdirectories).")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
writeGameRulesetCategories(argParse);
}
//-------------------------------------------------------------------------
}
| 5,926 | 30.526596 | 129 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/debugging/FindCrashingTrial.java
|
package supplementary.experiments.debugging;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.collections.ListUtils;
import other.AI;
import other.GameLoader;
import other.context.Context;
import other.model.Model;
import other.trial.Trial;
import utils.AIFactory;
import utils.experiments.InterruptableExperiment;
/**
* Implementation of an experiment that runs trials until one crashes,
* and then saves the trial right before the crash.
*
* @author Dennis Soemers
*/
public class FindCrashingTrial
{
/* Game setup */
/** Name of the game to play. Should end with .lud */
private String gameName;
/** List of game options to use when compiling game */
private List<String> gameOptions;
/* Basic experiment setup */
/** Number of evaluation games to run */
protected int numGames;
/** Maximum game duration (in moves) */
protected int gameLengthCap;
/** Max allowed thinking time per move (in seconds) */
protected double thinkingTime;
/** Max allowed number of MCTS iterations per move */
protected int iterationLimit;
/** Max search depth (for e.g. alpha-beta) */
protected int depthLimit;
/** Whether to rotate through agent-to-player assignments */
protected boolean rotateAgents;
//------------------------------------------------------------------------------
/* Agents setup */
/** Strings describing agents to use */
private List<String> agentStrings;
//------------------------------------------------------------------------------
/** File saving stuff and other outputs */
/** Output directory */
private File outTrialFile;
/** Whether we allow printing some messages to System.out */
protected boolean printOut = true;
//------------------------------------------------------------------------------
/* Auxiliary experiment setup */
/**
* Whether to create a small GUI that can be used to manually interrupt training run.
* False by default.
*/
protected boolean useGUI;
/** Max wall time in minutes (or -1 for no limit) */
protected int maxWallTime;
//-------------------------------------------------------------------------
/**
* Constructor. No GUI for interrupting experiment, no wall time limit.
*/
public FindCrashingTrial()
{
// all defaults already set above
}
/**
* Constructor. No wall time limit.
* @param useGUI
*/
public FindCrashingTrial(final boolean useGUI)
{
this.useGUI = useGUI;
}
/**
* Constructor
* @param useGUI
* @param maxWallTime Wall time limit in minutes.
*/
public FindCrashingTrial(final boolean useGUI, final int maxWallTime)
{
this.useGUI = useGUI;
this.maxWallTime = maxWallTime;
}
//-------------------------------------------------------------------------
/**
* Starts the experiment
*/
@SuppressWarnings("unused")
public void startExperiment()
{
final List<AI> ais = new ArrayList<AI>(agentStrings.size());
for (final String agent : agentStrings)
{
ais.add(AIFactory.createAI(agent));
}
final Game game = GameLoader.loadGameFromName(gameName, gameOptions);
if (game == null)
{
System.err.println("Could not instantiate game. Aborting match. Game name = " + gameName + ".");
return;
}
final int numPlayers = game.players().count();
if (ais.size() != numPlayers)
{
System.err.println
(
"Expected " + numPlayers +
" agents, but received list of " + ais.size() +
" agents. Aborting match."
);
return;
}
if (gameLengthCap >= 0)
game.setMaxTurns(Math.min(gameLengthCap, game.getMaxTurnLimit()));
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
final byte[] gameStartRngState = new byte[((RandomProviderDefaultState) context.rng().saveState()).getState().length];
try
{
new InterruptableExperiment(useGUI, maxWallTime)
{
@Override
public void runExperiment()
{
final int numGamesToPlay = numGames;
List<TIntArrayList> aiListPermutations = new ArrayList<TIntArrayList>();
if (rotateAgents)
{
// compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray())
);
}
else
{
// only need a single permutation; order in which AIs were given to us
aiListPermutations.add(TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
}
for (int gameCounter = 0; gameCounter < numGamesToPlay; ++gameCounter)
{
if (printOut)
System.out.println("starting game " + gameCounter);
checkWallTime(0.05);
if (interrupted)
{
// time to abort the experiment due to wall time
break;
}
// compute list of AIs to use for this game
// (we rotate every game)
final List<AI> currentAIList = new ArrayList<AI>(numPlayers);
final int currentAIsPermutation = gameCounter % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
currentAIList.add(null); // 0 index not used
for (int i = 0; i < currentPlayersPermutation.size(); ++i)
{
currentAIList.add
(
ais.get(currentPlayersPermutation.getQuick(i) % ais.size())
);
}
// play a game
final byte[] newRNGState = ((RandomProviderDefaultState) context.rng().saveState()).getState();
for (int i = 0; i < gameStartRngState.length; ++i)
{
gameStartRngState[i] = newRNGState[i];
}
game.start(context);
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).initAI(game, p);
}
final Model model = context.model();
while (!context.trial().over())
{
if (interrupted)
{
// time to abort the experiment due to wall time
break;
}
model.startNewStep(context, currentAIList, thinkingTime, iterationLimit, depthLimit, 0.0);
}
// Close AIs
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).closeAI();
}
}
}
};
}
catch (final Exception | Error e)
{
e.printStackTrace();
try
{
System.out.println("Saving to file: " + outTrialFile.getAbsolutePath());
trial.saveTrialToTextFile(outTrialFile, gameName, gameOptions, new RandomProviderDefaultState(gameStartRngState));
}
catch (final IOException ioException)
{
ioException.printStackTrace();
}
return;
}
if (printOut)
System.out.println("No game crashed!");
}
//-------------------------------------------------------------------------
/**
* Can be used for quick testing without command-line args, or proper
* testing with elaborate setup through command-line args
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Run games until one crashes, and save the trial that causes a crash. "
+ "Only intended for debugging purposes."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to play. Should end with \".lud\".")
.setRequired()
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--game-options")
.help("Game Options to load.")
.withDefault(new ArrayList<String>(0))
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--agents")
.help("Agents which should be evaluated")
.withDefault(Arrays.asList("Random", "Random"))
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("-n", "--num-games", "--num-eval-games")
.help("Number of training games to run.")
.withDefault(Integer.valueOf(200))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--game-length-cap", "--max-num-actions")
.help("Maximum number of actions that may be taken before a game is terminated as a draw (-1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--thinking-time", "--time", "--seconds")
.help("Max allowed thinking time per move (in seconds).")
.withDefault(Double.valueOf(1.0))
.withNumVals(1)
.withType(OptionTypes.Double));
argParse.addOption(new ArgOption()
.withNames("--iteration-limit", "--iterations")
.help("Max allowed number of MCTS iterations per move.")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--depth-limit")
.help("Max allowed search depth per move (for e.g. alpha-beta).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--no-rotate-agents")
.help("Don't rotate through possible assignments of agents to Player IDs.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--out-trial-file")
.help("Filepath for output trial")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--no-print-out")
.help("Suppress print messages to System.out")
.withNumVals(0)
.withType(OptionTypes.Boolean));
argParse.addOption(new ArgOption()
.withNames("--useGUI")
.help("Whether to create a small GUI that can be used to "
+ "manually interrupt training run. False by default."));
argParse.addOption(new ArgOption()
.withNames("--max-wall-time")
.help("Max wall time in minutes (or -1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final FindCrashingTrial eval =
new FindCrashingTrial
(
argParse.getValueBool("--useGUI"),
argParse.getValueInt("--max-wall-time")
);
eval.gameName = argParse.getValueString("--game");
eval.gameOptions = (List<String>) argParse.getValue("--game-options");
eval.agentStrings = (List<String>) argParse.getValue("--agents");
eval.numGames = argParse.getValueInt("-n");
eval.gameLengthCap = argParse.getValueInt("--game-length-cap");
eval.thinkingTime = argParse.getValueDouble("--thinking-time");
eval.iterationLimit = argParse.getValueInt("--iteration-limit");
eval.depthLimit = argParse.getValueInt("--depth-limit");
eval.rotateAgents = !argParse.getValueBool("--no-rotate-agents");
eval.printOut = !argParse.getValueBool("--no-print-out");
final String outTrialFilepath = argParse.getValueString("--out-trial-file");
if (outTrialFilepath != null)
eval.outTrialFile = new File(outTrialFilepath);
else
eval.outTrialFile = null;
eval.startExperiment();
}
}
| 11,650 | 27.626536 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/debugging/FindSuperLongTrial.java
|
package supplementary.experiments.debugging;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.collections.ListUtils;
import other.AI;
import other.GameLoader;
import other.context.Context;
import other.model.Model;
import other.trial.Trial;
import utils.AIFactory;
import utils.experiments.InterruptableExperiment;
/**
* Implementation of an experiment that runs trials, and saves one if
* even just a single move takes an excessively long time to complete.
*
* @author Dennis Soemers
*/
public class FindSuperLongTrial
{
/* Game setup */
/** Name of the game to play. Should end with .lud */
protected String gameName;
/** List of game options to use when compiling game */
protected List<String> gameOptions;
//-------------------------------------------------------------------------
/* Basic experiment setup */
/** Number of evaluation games to run */
protected int numGames;
/** Maximum game duration (in moves) */
private int gameLengthCap;
/** Max allowed thinking time per move (in seconds) */
protected double thinkingTime;
/** Max allowed number of MCTS iterations per move */
protected int iterationLimit;
/** Max search depth (for e.g. alpha-beta) */
protected int depthLimit;
/** Whether to rotate through agent-to-player assignments */
protected boolean rotateAgents;
/** If a single step takes more than this number of milliseconds, we save the trial */
protected volatile long maxMillisPerStep;
/** If a single trial takes more than this number of milliseconds, we save the trial */
protected volatile long maxMillisPerTrial;
//-------------------------------------------------------------------------
/* Agents setup */
/** Strings describing agents to use */
private List<String> agentStrings;
//-------------------------------------------------------------------------
/** File saving stuff and other outputs */
/** Output directory */
protected volatile File outTrialFile;
/** Whether we allow printing some messages to System.out */
protected boolean printOut = true;
//-------------------------------------------------------------------------
/* Auxiliary experiment setup */
/**
* Whether to create a small GUI that can be used to manually interrupt training run.
* False by default.
*/
protected boolean useGUI;
/** Max wall time in minutes (or -1 for no limit) */
protected int maxWallTime;
//-------------------------------------------------------------------------
/**
* Constructor. No GUI for interrupting experiment, no wall time limit.
*/
public FindSuperLongTrial()
{
// all defaults already set above
}
/**
* Constructor. No wall time limit.
* @param useGUI
*/
public FindSuperLongTrial(final boolean useGUI)
{
this.useGUI = useGUI;
}
/**
* Constructor
* @param useGUI
* @param maxWallTime Wall time limit in minutes.
*/
public FindSuperLongTrial(final boolean useGUI, final int maxWallTime)
{
this.useGUI = useGUI;
this.maxWallTime = maxWallTime;
}
//-------------------------------------------------------------------------
/**
* Starts the experiment
*/
@SuppressWarnings("unused")
public void startExperiment()
{
final List<AI> ais = new ArrayList<AI>(agentStrings.size());
for (final String agent : agentStrings)
{
ais.add(AIFactory.createAI(agent));
}
final Game game = GameLoader.loadGameFromName(gameName, gameOptions);
if (game == null)
{
System.err.println("Could not instantiate game. Aborting match. Game name = " + gameName + ".");
return;
}
final int numPlayers = game.players().count();
if (ais.size() != numPlayers)
{
System.err.println
(
"Expected " + numPlayers +
" agents, but received list of " + ais.size() +
" agents. Aborting match."
);
return;
}
if (gameLengthCap >= 0)
game.setMaxTurns(Math.min(gameLengthCap, game.getMaxTurnLimit()));
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
final byte[] gameStartRngState = new byte[((RandomProviderDefaultState) context.rng().saveState()).getState().length];
try
{
new InterruptableExperiment(useGUI, maxWallTime)
{
@Override
public void runExperiment()
{
final int numGamesToPlay = numGames;
List<TIntArrayList> aiListPermutations = new ArrayList<TIntArrayList>();
if (rotateAgents)
{
// compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray())
);
}
else
{
// only need a single permutation; order in which AIs were given to us
aiListPermutations.add(TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
}
final TrialSavingRunnable runnable = new TrialSavingRunnable();
final Thread checkTimeThread = new Thread(runnable);
checkTimeThread.setDaemon(true);
checkTimeThread.start();
for (int gameCounter = 0; gameCounter < numGamesToPlay; ++gameCounter)
{
if (printOut)
System.out.println("starting game " + gameCounter);
checkWallTime(0.05);
if (interrupted)
{
// time to abort the experiment due to wall time
break;
}
// compute list of AIs to use for this game
// (we rotate every game)
final List<AI> currentAIList = new ArrayList<AI>(numPlayers);
final int currentAIsPermutation = gameCounter % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
currentAIList.add(null); // 0 index not used
for (int i = 0; i < currentPlayersPermutation.size(); ++i)
{
currentAIList.add
(
ais.get(currentPlayersPermutation.getQuick(i) % ais.size())
);
}
// play a game
final byte[] newRNGState = ((RandomProviderDefaultState) context.rng().saveState()).getState();
for (int i = 0; i < gameStartRngState.length; ++i)
{
gameStartRngState[i] = newRNGState[i];
}
runnable.gameStartRngState = Arrays.copyOf(gameStartRngState, gameStartRngState.length);
game.start(context);
runnable.trial = trial;
runnable.currentTrialStartTime = System.currentTimeMillis();
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).initAI(game, p);
}
final Model model = context.model();
while (!context.trial().over())
{
if (interrupted)
{
// time to abort the experiment due to wall time
break;
}
runnable.currentStepStartTime = System.currentTimeMillis();
model.startNewStep(context, currentAIList, thinkingTime, iterationLimit, depthLimit, 0.0);
runnable.currentStepStartTime = -1L;
}
// Close AIs
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).closeAI();
}
runnable.currentTrialStartTime = -1L;
}
}
};
}
catch (final Exception | Error e)
{
e.printStackTrace();
try
{
trial.saveTrialToTextFile(outTrialFile, gameName, gameOptions, new RandomProviderDefaultState(gameStartRngState));
}
catch (final IOException ioException)
{
ioException.printStackTrace();
}
return;
}
if (printOut)
System.out.println("No game crashed or exceeded length!");
}
//-------------------------------------------------------------------------
/**
* Runnable to keep track of time and save trials when they take too long
*
* @author Dennis Soemers
*/
private class TrialSavingRunnable implements Runnable
{
/** The trial object we're currently running */
public volatile Trial trial = null;
/** Start time of our current step in the main thread */
public volatile long currentStepStartTime = -1L;
/** Start time of our current trial in the main thread */
public volatile long currentTrialStartTime = -1L;
/** Internal state of RNG when we started current trial */
public volatile byte[] gameStartRngState = null;
public TrialSavingRunnable()
{
// ...
}
@Override
public void run()
{
while (true)
{
final long startTime = currentStepStartTime;
final long startTrialTime = currentTrialStartTime;
if (startTime < 0L)
continue;
final long currentTime = System.currentTimeMillis();
if (currentTime - startTime > maxMillisPerStep)
{
try
{
trial.saveTrialToTextFile(outTrialFile, gameName, gameOptions, new RandomProviderDefaultState(gameStartRngState));
System.err.println("Saved to file (single-step time-out): " + outTrialFile.getCanonicalPath());
}
catch (final IOException ioException)
{
ioException.printStackTrace();
}
System.exit(0);
}
else if (currentTime - startTrialTime > maxMillisPerTrial)
{
try
{
trial.saveTrialToTextFile(outTrialFile, gameName, gameOptions, new RandomProviderDefaultState(gameStartRngState));
System.err.println("Saved to file (full-trial time-out): " + outTrialFile.getCanonicalPath());
}
catch (final IOException ioException)
{
ioException.printStackTrace();
}
System.exit(0);
}
}
}
}
//-------------------------------------------------------------------------
/**
* Can be used for quick testing without command-line args, or proper
* testing with elaborate setup through command-line args
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Run games until one crashes, and save the trial that causes a crash. "
+ "Only intended for debugging purposes."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to play. Should end with \".lud\".")
.withDefault("Amazons.lud")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--game-options")
.help("Game Options to load.")
.withDefault(new ArrayList<String>(0))
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--agents")
.help("Agents which should be evaluated")
.withDefault(Arrays.asList("Random", "Random"))
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("-n", "--num-games", "--num-eval-games")
.help("Number of training games to run.")
.withDefault(Integer.valueOf(200))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--game-length-cap", "--max-num-actions")
.help("Maximum number of actions that may be taken before a game is terminated as a draw (-1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--thinking-time", "--time", "--seconds")
.help("Max allowed thinking time per move (in seconds).")
.withDefault(Double.valueOf(1.0))
.withNumVals(1)
.withType(OptionTypes.Double));
argParse.addOption(new ArgOption()
.withNames("--iteration-limit", "--iterations")
.help("Max allowed number of MCTS iterations per move.")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--depth-limit")
.help("Max allowed search depth per move (for e.g. alpha-beta).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--no-rotate-agents")
.help("Don't rotate through possible assignments of agents to Player IDs.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--max-millis-per-step")
.help("If a single step takes more than this number of milliseconds, we save the trial")
.withDefault(Integer.valueOf(5000))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--max-millis-per-trial")
.help("If a single trial takes more than this number of milliseconds, we save the trial")
.withDefault(Integer.valueOf(120000))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--out-trial-file")
.help("Filepath for output trial")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--no-print-out")
.help("Suppress print messages to System.out")
.withNumVals(0)
.withType(OptionTypes.Boolean));
argParse.addOption(new ArgOption()
.withNames("--useGUI")
.help("Whether to create a small GUI that can be used to "
+ "manually interrupt training run. False by default."));
argParse.addOption(new ArgOption()
.withNames("--max-wall-time")
.help("Max wall time in minutes (or -1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final FindSuperLongTrial eval =
new FindSuperLongTrial
(
argParse.getValueBool("--useGUI"),
argParse.getValueInt("--max-wall-time")
);
eval.gameName = argParse.getValueString("--game");
eval.gameOptions = (List<String>) argParse.getValue("--game-options");
eval.agentStrings = (List<String>) argParse.getValue("--agents");
eval.numGames = argParse.getValueInt("-n");
eval.gameLengthCap = argParse.getValueInt("--game-length-cap");
eval.thinkingTime = argParse.getValueDouble("--thinking-time");
eval.iterationLimit = argParse.getValueInt("--iteration-limit");
eval.depthLimit = argParse.getValueInt("--depth-limit");
eval.rotateAgents = !argParse.getValueBool("--no-rotate-agents");
eval.maxMillisPerStep = argParse.getValueInt("--max-millis-per-step");
eval.maxMillisPerTrial = argParse.getValueInt("--max-millis-per-trial");
eval.printOut = !argParse.getValueBool("--no-print-out");
final String outTrialFilepath = argParse.getValueString("--out-trial-file");
if (outTrialFilepath != null)
eval.outTrialFile = new File(outTrialFilepath);
else
eval.outTrialFile = null;
eval.startExperiment();
}
}
| 15,102 | 28.671906 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/eval/EvalAgents.java
|
package supplementary.experiments.eval;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import features.feature_sets.network.JITSPatterNetFeatureSet;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import other.AI;
import supplementary.experiments.EvalGamesSet;
import utils.AIFactory;
/**
* Implementation of an experiment that evaluates the performance
* of different Agents.
*
* @author Dennis Soemers
*/
public class EvalAgents
{
/* Game setup */
/** Name of the game to play. Should end with .lud */
protected String gameName;
/** List of game options to use when compiling game */
protected List<String> gameOptions = new ArrayList<String>(0);
/** Name of ruleset to compile. Any options will be ignored if ruleset is provided. */
protected String ruleset;
//-------------------------------------------------------------------------
/* Basic experiment setup */
/** Number of evaluation games to run */
protected int numGames;
/** Maximum game duration (in moves) */
protected int gameLengthCap;
/** Max allowed thinking time per move (in seconds) */
protected double thinkingTime;
/** Max allowed number of MCTS iterations per move */
protected int iterationLimit;
/** Max search depth (for e.g. alpha-beta) */
protected int depthLimit;
/** Whether to rotate through agent-to-player assignments */
protected boolean rotateAgents;
/** Number of seconds for warming-up of JVM */
protected int warmingUpSecs;
/** If true, increase number of games to play to next number that can be divided by number of permutations of agents */
protected boolean roundToNextPermutationsDivisor;
//-------------------------------------------------------------------------
/* Agents setup */
/** Strings describing agents to use */
protected List<String> agentStrings;
//-------------------------------------------------------------------------
/** File saving stuff and other outputs */
/** Output directory */
protected File outDir;
/** Whether we want to output a human-readable(ish) summary of results */
protected boolean outputSummary;
/** Whether we want to output data for alpha-rank */
protected boolean outputAlphaRankData;
/** Whether we want to print general messages to System.out */
protected boolean printOut;
/** Suppress warnings about number of trials not being divisible by number of permutations of agents */
protected boolean suppressDivisorWarning = false;
//-------------------------------------------------------------------------
/* Auxiliary experiment setup */
/**
* Whether to create a small GUI that can be used to manually interrupt training run.
* False by default.
*/
protected boolean useGUI;
/** Max wall time in minutes (or -1 for no limit) */
protected int maxWallTime;
//-------------------------------------------------------------------------
/**
* Constructor. No GUI for interrupting experiment, no wall time limit.
*/
public EvalAgents()
{
// all defaults already set above
}
/**
* Constructor. No wall time limit.
* @param useGUI
*/
public EvalAgents(final boolean useGUI)
{
this.useGUI = useGUI;
}
/**
* Constructor
* @param useGUI
* @param maxWallTime Wall time limit in minutes.
*/
public EvalAgents(final boolean useGUI, final int maxWallTime)
{
this.useGUI = useGUI;
this.maxWallTime = maxWallTime;
}
//-------------------------------------------------------------------------
/**
* Starts the experiment
*/
public void startExperiment()
{
final List<AI> ais = new ArrayList<AI>(agentStrings.size());
for (final String agent : agentStrings)
{
ais.add(AIFactory.createAI(agent));
}
final EvalGamesSet gamesSet =
new EvalGamesSet(useGUI, maxWallTime)
.setGameName(gameName)
.setGameOptions(gameOptions)
.setRuleset(ruleset)
.setAgents(ais)
.setNumGames(numGames)
.setGameLengthCap(gameLengthCap)
.setMaxSeconds(thinkingTime)
.setMaxIterations(iterationLimit)
.setMaxSearchDepth(depthLimit)
.setRotateAgents(rotateAgents)
.setWarmingUpSecs(warmingUpSecs)
.setRoundToNextPermutationsDivisor(roundToNextPermutationsDivisor)
.setOutDir(outDir)
.setOutputAlphaRankData(outputAlphaRankData)
.setOutputSummary(outputSummary)
.setPrintOut(printOut)
.setSuppressDivisorWarning(suppressDivisorWarning);
gamesSet.startGames();
}
//-------------------------------------------------------------------------
/**
* Can be used for quick testing without command-line args, or proper
* testing with elaborate setup through command-line args
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// Feature Set caching is safe in this main method
JITSPatterNetFeatureSet.ALLOW_FEATURE_SET_CACHE = true;
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Evaluate playing strength of different agents against each other."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to play. Should end with \".lud\".")
.withDefault("Amazons.lud")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--game-options")
.help("Game Options to load.")
.withDefault(new ArrayList<String>(0))
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--ruleset")
.help("Ruleset to compile.")
.withDefault("")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--agents")
.help("Agents which should be evaluated")
.withDefault(Arrays.asList("UCT", "Biased MCTS"))
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("-n", "--num-games", "--num-eval-games")
.help("Number of training games to run.")
.withDefault(Integer.valueOf(200))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--game-length-cap", "--max-num-actions")
.help("Maximum number of actions that may be taken before a game is terminated as a draw (-1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--thinking-time", "--time", "--seconds")
.help("Max allowed thinking time per move (in seconds).")
.withDefault(Double.valueOf(1.0))
.withNumVals(1)
.withType(OptionTypes.Double));
argParse.addOption(new ArgOption()
.withNames("--iteration-limit", "--iterations")
.help("Max allowed number of MCTS iterations per move.")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--depth-limit")
.help("Max allowed search depth per move (for e.g. alpha-beta).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--no-rotate-agents")
.help("Don't rotate through possible assignments of agents to Player IDs.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--warming-up-secs")
.help("Number of seconds for which to warm up JVM.")
.withType(OptionTypes.Int)
.withNumVals(1)
.withDefault(Integer.valueOf(60)));
argParse.addOption(new ArgOption()
.withNames("--round-to-next-permutations-divisor")
.help("Increase number of games to play to next number that can be divided by number of permutations of agents.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--out-dir", "--output-directory")
.help("Filepath for output directory")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--output-summary")
.help("Output summary of results.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--output-alpha-rank-data")
.help("Output data for alpha-rank.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--no-print-out")
.help("Suppress general prints to System.out.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--suppress-divisor-warning")
.help("Suppress warning about number of trials not being divisible by number of permutations of agents.")
.withType(OptionTypes.Boolean)
.withNumVals(0));
argParse.addOption(new ArgOption()
.withNames("--useGUI")
.help("Whether to create a small GUI that can be used to "
+ "manually interrupt training run. False by default."));
argParse.addOption(new ArgOption()
.withNames("--max-wall-time")
.help("Max wall time in minutes (or -1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final EvalAgents eval =
new EvalAgents
(
argParse.getValueBool("--useGUI"),
argParse.getValueInt("--max-wall-time")
);
eval.gameName = argParse.getValueString("--game");
eval.gameOptions = (List<String>) argParse.getValue("--game-options");
eval.ruleset = argParse.getValueString("--ruleset");
eval.agentStrings = (List<String>) argParse.getValue("--agents");
eval.numGames = argParse.getValueInt("-n");
eval.gameLengthCap = argParse.getValueInt("--game-length-cap");
eval.thinkingTime = argParse.getValueDouble("--thinking-time");
eval.iterationLimit = argParse.getValueInt("--iteration-limit");
eval.depthLimit = argParse.getValueInt("--depth-limit");
eval.rotateAgents = !argParse.getValueBool("--no-rotate-agents");
eval.warmingUpSecs = argParse.getValueInt("--warming-up-secs");
eval.roundToNextPermutationsDivisor = argParse.getValueBool("--round-to-next-permutations-divisor");
final String outDirFilepath = argParse.getValueString("--out-dir");
if (outDirFilepath != null)
eval.outDir = new File(outDirFilepath);
else
eval.outDir = null;
eval.outputSummary = argParse.getValueBool("--output-summary");
eval.outputAlphaRankData = argParse.getValueBool("--output-alpha-rank-data");
eval.printOut = !argParse.getValueBool("--no-print-out");
eval.suppressDivisorWarning = argParse.getValueBool("--suppress-divisor-warning");
eval.startExperiment();
}
}
| 10,868 | 31.061947 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/eval/EvalGames.java
|
package supplementary.experiments.eval;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.rng.RandomProviderState;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import org.json.JSONObject;
import compiler.Compiler;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.Constants;
import main.FileHandling;
import main.grammar.Report;
import main.options.Ruleset;
import main.options.UserSelections;
import manager.network.DatabaseFunctionsPublic;
import manager.utils.game_logs.MatchRecord;
import metrics.Evaluation;
import metrics.Metric;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
import utils.AIFactory;
import utils.DBGameInfo;
/**
* Functions used when evaluating games.
*
* @author Matthew.Stephenson
*/
public class EvalGames
{
final static String outputFilePath = "EvalResults.csv"; //"../Mining/res/evaluation/Results.csv";
//-------------------------------------------------------------------------
/**
* Evaluates all games/rulesets.
*/
private static void evaluateAllGames
(
final Report report, final int numberTrials, final int maxTurns, final double thinkTime,
final String AIName, final boolean useDBGames
)
{
final Evaluation evaluation = new Evaluation();
final List<Metric> metrics = evaluation.conceptMetrics();
final ArrayList<Double> weights = new ArrayList<>();
for (int i = 0; i < metrics.size(); i++)
weights.add(Double.valueOf(1));
String outputString = "GameName,";
for (int m = 0; m < metrics.size(); m++)
{
outputString += metrics.get(m).name() + ",";
}
outputString = outputString.substring(0, outputString.length()-1) + "\n";
final String[] choices = FileHandling.listGames();
for (final String s : choices)
{
if (!FileHandling.shouldIgnoreLudEvaluation(s))
{
System.out.println("\n" + s);
final String gameName = s.split("\\/")[s.split("\\/").length-1];
final Game tempGame = GameLoader.loadGameFromName(gameName);
final List<Ruleset> rulesets = tempGame.description().rulesets();
if (tempGame.hasSubgames()) // TODO, we don't currently support matches
continue;
if (rulesets != null && !rulesets.isEmpty())
{
// Record ludemeplexes for each ruleset
for (int rs = 0; rs < rulesets.size(); rs++)
if (!rulesets.get(rs).optionSettings().isEmpty())
outputString += evaluateGame(evaluation, report, tempGame, rulesets.get(rs).optionSettings(), AIName, numberTrials, thinkTime, maxTurns, metrics, weights, useDBGames);
}
else
{
outputString += evaluateGame(evaluation, report, tempGame, tempGame.description().gameOptions().allOptionStrings(tempGame.getOptions()), AIName, numberTrials, thinkTime, maxTurns, metrics, weights, useDBGames);
}
}
}
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath, false)))
{
writer.write(outputString);
writer.close();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Evaluates a given game.
*/
public static String evaluateGame
(
final Evaluation evaluation,
final Report report,
final Game originalGame,
final List<String> gameOptions,
final String AIName,
final int numGames,
final double thinkingTimeEach,
final int maxNumTurns,
final List<Metric> metricsToEvaluate,
final ArrayList<Double> weights,
final boolean useDatabaseGames
)
{
final Game game = (Game)Compiler.compile(originalGame.description(), new UserSelections(gameOptions), report, false);
game.setMaxTurns(maxNumTurns);
final List<AI> aiPlayers = new ArrayList<>();
for (int i = 0; i < Constants.MAX_PLAYERS+1; i++)
{
final JSONObject json = new JSONObject().put("AI",new JSONObject().put("algorithm", AIName));
aiPlayers.add(AIFactory.fromJson(json));
}
final double[] thinkingTime = new double[aiPlayers.size()];
for (int p = 1; p < aiPlayers.size(); ++p)
thinkingTime[p] = thinkingTimeEach;
final DatabaseFunctionsPublic databaseFunctionsPublic = DatabaseFunctionsPublic.construct();
String analysisPanelString = "";
// Initialise the AI agents needed.
final int numPlayers = game.players().count();
for (int i = 0; i < numPlayers; ++i)
{
final AI ai = aiPlayers.get(i + 1);
final int playerIdx = i + 1;
if (ai == null)
{
final String message = "Cannot run evaluation; Player " + playerIdx + " is not AI.\n";
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel(message);
}
catch(final Exception e)
{
// probably running from command line.
System.out.println(message);
}
return "\n";
}
else if (!ai.supportsGame(game))
{
final String message = "Cannot run evaluation; " + ai.friendlyName() + " does not support this game.\n";
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel(message);
}
catch(final Exception e)
{
// probably running from command line.
System.out.println(message);
}
return "\n";
}
}
final String message = "Please don't touch anything until complete! \nGenerating trials: \n";
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel(message);
}
catch(final Exception e)
{
// probably running from command line.
System.out.println(message);
}
// If using Ludii AI, need to get the algorithm used.
for (int p = 1; p <= game.players().count(); ++p)
aiPlayers.get(p).initAI(game, p);
String aiAlgorihtm = aiPlayers.get(1).name();
if (aiAlgorihtm.length() > 7 && aiAlgorihtm.substring(0, 5).equals("Ludii"))
aiAlgorihtm = aiAlgorihtm.substring(7, aiAlgorihtm.length()-1);
// Get any valid trials that were in database.
ArrayList<String> databaseTrials = new ArrayList<>();
if (useDatabaseGames)
{
databaseTrials = databaseFunctionsPublic.getTrialsFromDatabase
(
game.name(), game.description().gameOptions().allOptionStrings(game.getOptions()),
aiAlgorihtm, thinkingTime[1], game.getMaxTurnLimit(),
game.description().raw().hashCode()
);
// Load files from a specific directory instead.
// final String dirName = "/home/matthew/Downloads/Banqi";
// final File dir = new File(dirName);
// final File[] allFiles = dir.listFiles();
// for(final File file : allFiles)
// {
// String totalContents = "";
// BufferedReader br;
// try
// {
// br = new BufferedReader(new FileReader(file));
// String line = null;
// while ((line = br.readLine()) != null)
// {
// totalContents += line + "\n";
// }
// }
// catch (final IOException e)
// {
// e.printStackTrace();
// }
// databaseTrials.add(totalContents);
// }
}
// Generate trials and print generic results.
final List<Trial> allStoredTrials = new ArrayList<>();
final List<RandomProviderState> allStoredRNG = new ArrayList<>();
final double[] sumScores = new double[game.players().count() + 1];
int numDraws = 0;
int numTimeouts = 0;
long sumNumMoves = 0L;
final Context context = new Context(game, new Trial(game));
try
{
for (int gameCounter = 0; gameCounter < numGames; ++gameCounter)
{
RandomProviderDefaultState rngState = (RandomProviderDefaultState) context.rng().saveState();
boolean usingSavedTrial = false;
List<Move> savedTrialMoves = new ArrayList<>();
if (databaseTrials.size() > gameCounter)
{
usingSavedTrial = true;
final Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, databaseTrials.get(gameCounter).getBytes(StandardCharsets.UTF_8));
final File file = new File(tempFile.toString());
final MatchRecord savedMatchRecord = MatchRecord.loadMatchRecordFromTextFile(file, game);
savedTrialMoves = savedMatchRecord.trial().generateCompleteMovesList();
rngState = savedMatchRecord.rngState();
context.rng().restoreState(rngState);
}
allStoredRNG.add(rngState);
// Play a game
game.start(context);
for (int p = 1; p <= game.players().count(); ++p)
aiPlayers.get(p).initAI(game, p);
if (usingSavedTrial)
for (int i = context.trial().numMoves(); i < savedTrialMoves.size(); i++)
context.game().apply(context, savedTrialMoves.get(i));
while (!context.trial().over())
{
context.model().startNewStep
(
context,
aiPlayers,
thinkingTime,
-1, -1, 0.0,
true, // block call until it returns
false, false,
null, null
);
while (!context.model().isReady())
Thread.sleep(100L);
}
final double[] utils = RankUtils.agentUtilities(context);
for (int p = 1; p <= game.players().count(); ++p)
sumScores[p] += (utils[p] + 1.0) / 2.0; // convert [-1, 1] to [0, 1]
if (context.trial().status().winner() == 0)
++numDraws;
if
(
(
context.state().numTurn()
>=
game.getMaxTurnLimit() * game.players().count()
)
||
(
context.trial().numMoves() - context.trial().numInitialPlacementMoves()
>=
game.getMaxMoveLimit()
)
)
{
++numTimeouts;
}
sumNumMoves += context.trial().numMoves() - context.trial().numInitialPlacementMoves();
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel(".");
}
catch(final Exception e)
{
// probably running from command line.
System.out.print(".");
}
allStoredTrials.add(new Trial(context.trial()));
if (!usingSavedTrial)
databaseFunctionsPublic.storeTrialInDatabase
(
game.name(),
game.description().gameOptions().allOptionStrings(game.getOptions()),
aiAlgorihtm, thinkingTime[1], game.getMaxTurnLimit(),
game.description().raw().hashCode(), new Trial(context.trial()), rngState
);
// Close AIs
for (int p = 1; p < aiPlayers.size(); ++p)
aiPlayers.get(p).closeAI();
}
}
catch (final Exception e)
{
e.printStackTrace();
}
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel("\nCalculating metrics: \n");
}
catch(final Exception e)
{
// probably running from command line.
System.out.print("\nTrials completed.\n");
}
final DecimalFormat df = new DecimalFormat("#.#####");
final String drawPercentage = df.format(numDraws*100.0/numGames) + "%";
final String timeoutPercentage = df.format(numTimeouts*100.0/numGames) + "%";
analysisPanelString += "\n\nAgent type: " + aiPlayers.get(0).friendlyName();
analysisPanelString += "\nDraw likelihood: " + drawPercentage;
analysisPanelString += "\nTimeout likelihood: " + timeoutPercentage;
analysisPanelString += "\nAverage number of moves per game: " + df.format(sumNumMoves/(double)numGames);
for (int i = 1; i < sumScores.length; i++)
analysisPanelString += "\nPlayer " + (i) + " win rate: " + df.format(sumScores[i]*100.0/numGames) + "%";
analysisPanelString += "\n\n";
double finalScore = 0.0;
String csvOutputString = DBGameInfo.getUniqueName(game) + ",";
final Trial[] trials = allStoredTrials.toArray(new Trial[allStoredTrials.size()]);
final RandomProviderState[] randomProviderStates = allStoredRNG.toArray(new RandomProviderState[allStoredRNG.size()]);
// Specific Metric results
for (int m = 0; m < metricsToEvaluate.size(); m++)
{
if (weights.get(m).doubleValue() == 0)
continue;
final Metric metric = metricsToEvaluate.get(m);
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel(metric.name() + "\n");
}
catch(final Exception e)
{
// probably running from command line.
System.out.print(metric.name() + "\n");
}
final Double score = metric.apply(game, evaluation, trials, randomProviderStates);
if (score == null)
{
csvOutputString += "NULL,";
}
else
{
final double weight = weights.get(m).doubleValue();
analysisPanelString += metric.name() + ": " + df.format(score) + " (weight: " + weight + ")\n";
finalScore += score.doubleValue() * weight;
csvOutputString += score + ",";
}
}
analysisPanelString += "Final Score: " + df.format(finalScore) + "\n\n";
try
{
report.getReportMessageFunctions().printMessageInAnalysisPanel(analysisPanelString);
}
catch (final Exception e)
{
// Probably running from command line
System.out.println(analysisPanelString);
}
return csvOutputString.substring(0, csvOutputString.length()-1) + "\n";
}
//-------------------------------------------------------------------------
/**
* @param args
*/
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Evaluate all games in ludii using gameplay metrics."
);
argParse.addOption(new ArgOption()
.withNames("--numTrials")
.help("Number of trials to run for each game.")
.withDefault(Integer.valueOf(10))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--maxTurns")
.help("Turn limit.")
.withDefault(Integer.valueOf(50))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--thinkTime")
.help("Thinking time per move.")
.withDefault(Double.valueOf(0.1))
.withNumVals(1)
.withType(OptionTypes.Double));
argParse.addOption(new ArgOption()
.withNames("--AIName")
.help("Name of the Agent to use.")
.withDefault("Ludii AI")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--useDatabaseGames")
.help("Use database games when available.")
.withDefault(Boolean.valueOf(true))
.withNumVals(1)
.withType(OptionTypes.Boolean));
if (!argParse.parseArguments(args))
return;
final int numberTrials = argParse.getValueInt("--numTrials");
final int maxTurns = argParse.getValueInt("--maxTurns");
final double thinkTime = argParse.getValueDouble("--thinkTime");
final String AIName = argParse.getValueString("--AIName");
final boolean useDatabaseGames = argParse.getValueBool("--useDatabaseGames");
evaluateAllGames(null, numberTrials, maxTurns, thinkTime, AIName, useDatabaseGames);
}
}
| 14,953 | 29.332657 | 215 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/eval/EvalGate.java
|
package supplementary.experiments.eval;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import features.feature_sets.network.JITSPatterNetFeatureSet;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.collections.ListUtils;
import main.grammar.Report;
import metadata.ai.agents.BestAgent;
import metadata.ai.features.Features;
import metadata.ai.heuristics.Heuristics;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.model.Model;
import other.trial.Trial;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import search.minimax.AlphaBetaSearch;
import utils.AIFactory;
import utils.AIUtils;
import utils.experiments.InterruptableExperiment;
import utils.experiments.ResultsSummary;
/**
* A "gating" evaluation where we check whether a newly-trained agent
* performs better than the currently-best agent.
*
* @author Dennis Soemers
*/
public class EvalGate
{
/** Name of the game to play. Should end with .lud */
protected String gameName;
/** List of game options to use when compiling game */
protected List<String> gameOptions;
/** Name of ruleset to compile. Any options will be ignored if ruleset is provided. */
protected String ruleset;
/** Number of evaluation games to run */
protected int numGames;
/** Maximum game duration (in moves) */
protected int gameLengthCap;
/** Max allowed thinking time per move (in seconds) */
protected double thinkingTime;
/** Number of seconds for warming-up of JVM */
protected int warmingUpSecs;
/** Strings describing the agent to evaluate */
protected String evalAgent;
/** Filepaths for feature weights to evaluate (if we're evaluating some form of Biased MCTS, one per player) */
protected List<String> evalFeatureWeightsFilepaths;
/** Filepath for heuristics to evaluate (if we're evaluating some form of Alpha-Beta) */
protected String evalHeuristicsFilepath;
/** Directory containing best agents data */
protected File bestAgentsDataDir;
/** Type of gate agent against which we wish to evaluate ("BestAgent", "Alpha-Beta", or "BiasedMCTS") */
protected String gateAgentType;
/**
* Whether to create a small GUI that can be used to manually interrupt training run.
* False by default.
*/
protected boolean useGUI;
/** Max wall time in minutes (or -1 for no limit) */
protected int maxWallTime;
//-------------------------------------------------------------------------
/**
* Constructor
* @param useGUI
* @param maxWallTime Wall time limit in minutes.
*/
private EvalGate(final boolean useGUI, final int maxWallTime)
{
this.useGUI = useGUI;
this.maxWallTime = maxWallTime;
}
//-------------------------------------------------------------------------
/**
* Helper method to instantiate an AI to evaluate
* @return
*/
private AI createEvalAI()
{
if (evalAgent.equals("Alpha-Beta"))
{
return AIFactory.createAI("algorithm=Alpha-Beta;heuristics=" + evalHeuristicsFilepath);
}
else if (evalAgent.equals("BiasedMCTS"))
{
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= evalFeatureWeightsFilepaths.size(); ++p)
{
playoutSb.append(",policyweights" + p + "=" + evalFeatureWeightsFilepaths.get(p - 1));
}
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
"learned_selection_policy=playout",
"friendly_name=BiasedMCTS"
);
return AIFactory.createAI(agentStr);
}
else if (evalAgent.equals("BiasedMCTSUniformPlayouts"))
{
final StringBuilder policySb = new StringBuilder();
policySb.append("learned_selection_policy=softmax");
for (int p = 1; p <= evalFeatureWeightsFilepaths.size(); ++p)
{
policySb.append(",policyweights" + p + "=" + evalFeatureWeightsFilepaths.get(p - 1));
}
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
"playout=random",
"final_move=robustchild",
"tree_reuse=true",
policySb.toString(),
"friendly_name=BiasedMCTSUniformPlayouts"
);
return AIFactory.createAI(agentStr);
}
else
{
System.err.println("Can't build eval AI: " + evalAgent);
return null;
}
}
/**
* Helper method to instantiate a "gate AI" (a currently-best AI to beat)
* @return
*/
private AI createGateAI()
{
final String bestAgentDataDirFilepath = bestAgentsDataDir.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/");
final Report report = new Report();
try
{
if (gateAgentType.equals("BestAgent"))
{
final BestAgent bestAgent = (BestAgent)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestAgentDataDirFilepath + "/BestAgent.txt"),
"metadata.ai.agents.BestAgent",
report
);
if (bestAgent.agent().equals("AlphaBeta") || bestAgent.agent().equals("Alpha-Beta"))
{
return new AlphaBetaSearch(bestAgentDataDirFilepath + "/BestHeuristics.txt");
}
else if (bestAgent.agent().equals("AlphaBetaMetadata"))
{
return new AlphaBetaSearch();
}
else if (bestAgent.agent().equals("UCT"))
{
return AIFactory.createAI("UCT");
}
else if (bestAgent.agent().equals("MC-GRAVE"))
{
return AIFactory.createAI("MC-GRAVE");
}
else if (bestAgent.agent().equals("MAST"))
{
return AIFactory.createAI("MAST");
}
else if (bestAgent.agent().equals("ProgressiveHistory") || bestAgent.agent().equals("Progressive History"))
{
return AIFactory.createAI("Progressive History");
}
else if (bestAgent.agent().equals("Biased MCTS"))
{
final Features features = (Features)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestAgentDataDirFilepath + "/BestFeatures.txt"),
"metadata.ai.features.Features",
report
);
return MCTS.createBiasedMCTS(features, 1.0);
}
else if (bestAgent.agent().equals("Biased MCTS (Uniform Playouts)"))
{
final Features features = (Features)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestAgentDataDirFilepath + "/BestFeatures.txt"),
"metadata.ai.features.Features",
report
);
return MCTS.createBiasedMCTS(features, 0.0);
}
else
{
System.err.println("Unrecognised best agent: " + bestAgent.agent());
}
}
else if (gateAgentType.equals("Alpha-Beta"))
{
return new AlphaBetaSearch(bestAgentDataDirFilepath + "/BestHeuristics.txt");
}
else if (gateAgentType.equals("BiasedMCTS"))
{
final Features features = (Features)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestAgentDataDirFilepath + "/BestFeatures.txt"),
"metadata.ai.features.Features",
report
);
// We'll take biased playouts or uniform playouts to be equal to the agent we're evaluating
if (evalAgent.equals("BiasedMCTS"))
return MCTS.createBiasedMCTS(features, 1.0);
else if (evalAgent.equals("BiasedMCTSUniformPlayouts"))
return MCTS.createBiasedMCTS(features, 0.0);
else
System.err.println("Trying to use Biased MCTS gate when evaluating something other than Biased MCTS!");
}
}
catch (final IOException e)
{
e.printStackTrace();
}
System.err.println("Failed to build gate AI: " + gateAgentType);
return null;
}
/**
* Starts the experiment
*/
@SuppressWarnings("unused")
public void startExperiment()
{
final Game game;
if (ruleset != null && !ruleset.equals(""))
game = GameLoader.loadGameFromName(gameName, ruleset);
else
game = GameLoader.loadGameFromName(gameName, gameOptions);
final int numPlayers = game.players().count();
if (gameLengthCap >= 0)
game.setMaxTurns(Math.min(gameLengthCap, game.getMaxTurnLimit()));
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
// We want an even number of AIs, with equally many instances of:
// 1) our AI to evaluate
// 2) our current best AI
final List<AI> ais = new ArrayList<AI>((numPlayers % 2 == 0) ? numPlayers : numPlayers + 1);
for (int i = 0; i < numPlayers; i += 2)
{
final AI evalAI = createEvalAI();
evalAI.setFriendlyName("EvalAI");
final AI gateAI = createGateAI();
gateAI.setFriendlyName("GateAI");
ais.add(evalAI);
ais.add(gateAI);
}
new InterruptableExperiment(useGUI, maxWallTime)
{
@Override
public void runExperiment()
{
int numGamesToPlay = numGames;
List<TIntArrayList> aiListPermutations = new ArrayList<TIntArrayList>();
// compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray())
);
if (numGamesToPlay % aiListPermutations.size() != 0)
{
// Increase number of games to play such that we can divide by number of AI permutations
numGamesToPlay += (numGamesToPlay % aiListPermutations.size());
}
// start with a warming up
long stopAt = 0L;
final long start = System.nanoTime();
final double abortAt = start + warmingUpSecs * 1000000000.0;
while (stopAt < abortAt)
{
game.start(context);
game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current());
stopAt = System.nanoTime();
}
System.gc();
// prepare results writing
final List<String> agentStrings = new ArrayList<String>();
for (final AI ai : ais)
{
agentStrings.add(ai.friendlyName());
}
final ResultsSummary resultsSummary = new ResultsSummary(game, agentStrings);
for (int gameCounter = 0; gameCounter < numGamesToPlay; ++gameCounter)
{
checkWallTime(0.05);
if (interrupted)
{
// time to abort the experiment due to wall time
break;
}
// compute list of AIs to use for this game
// (we rotate every game)
final List<AI> currentAIList = new ArrayList<AI>(numPlayers);
final int currentAIsPermutation = gameCounter % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
currentAIList.add(null); // 0 index not used
for (int i = 0; i < currentPlayersPermutation.size(); ++i)
{
currentAIList.add
(
ais.get(currentPlayersPermutation.getQuick(i) % ais.size())
);
}
// Play a game
game.start(context);
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).initAI(game, p);
}
final Model model = context.model();
while (!context.trial().over())
{
if (interrupted)
{
// Time to abort the experiment due to wall time
break;
}
model.startNewStep(context, currentAIList, thinkingTime, -1, -1, 0.0);
}
// Record results
if (context.trial().over())
{
final double[] utilities = RankUtils.agentUtilities(context);
final int numMovesPlayed = context.trial().numMoves() - context.trial().numInitialPlacementMoves();
final int[] agentPermutation = new int[currentPlayersPermutation.size() + 1];
currentPlayersPermutation.toArray(agentPermutation, 0, 1, currentPlayersPermutation.size());
resultsSummary.recordResults(agentPermutation, utilities, numMovesPlayed);
}
// Close AIs
for (int p = 1; p < currentAIList.size(); ++p)
{
currentAIList.get(p).closeAI();
}
}
// If we outperform the gate, we'll have to write some new files
final double avgEvalScore = resultsSummary.avgScoreForAgentName("EvalAI");
final double avgGateScore = resultsSummary.avgScoreForAgentName("GateAI");
System.out.println("----------------------------------");
System.out.println("Eval Agent = " + evalAgent);
System.out.println("Gate Agent = " + gateAgentType);
System.out.println();
System.out.println("Eval Agent Score = " + avgEvalScore);
System.out.println("Gate Agent Score = " + avgGateScore);
System.out.println("----------------------------------");
if (avgEvalScore > avgGateScore)
{
// We passed the gate
boolean writeBestAgent = false;
boolean writeFeatures = false;
boolean writeHeuristics = false;
if (gateAgentType.equals("BestAgent"))
{
writeBestAgent = true;
if (evalAgent.equals("Alpha-Beta"))
writeHeuristics = true;
else if (evalAgent.contains("BiasedMCTS"))
writeFeatures = true;
else
System.err.println("Eval agent is neither Alpha-Beta nor a variant of BiasedMCTS");
}
else if (gateAgentType.equals("Alpha-Beta"))
{
if (evalAgent.equals("Alpha-Beta"))
writeHeuristics = true;
else
System.err.println("evalAgent = " + evalAgent + " against gateAgentType = " + gateAgentType);
}
else if (gateAgentType.equals("BiasedMCTS"))
{
if (evalAgent.contains("BiasedMCTS"))
writeFeatures = true;
else
System.err.println("evalAgent = " + evalAgent + " against gateAgentType = " + gateAgentType);
}
else
{
System.err.println("Unrecognised gate agent type: " + gateAgentType);
}
final String bestAgentsDataDirPath = bestAgentsDataDir.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/");
if (writeBestAgent)
{
final File bestAgentFile = new File(bestAgentsDataDirPath + "/BestAgent.txt");
try (final PrintWriter writer = new PrintWriter(bestAgentFile))
{
final BestAgent bestAgent;
if (evalAgent.equals("Alpha-Beta"))
bestAgent = new BestAgent("AlphaBeta");
else if (evalAgent.equals("BiasedMCTS"))
bestAgent = new BestAgent("Biased MCTS");
else if (evalAgent.equals("BiasedMCTSUniformPlayouts"))
bestAgent = new BestAgent("Biased MCTS (Uniform Playouts)");
else
bestAgent = null;
System.out.println("Writing new best agent: " + evalAgent);
writer.println(bestAgent.toString());
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
}
if (writeHeuristics)
{
final File bestHeuristicsFile = new File(bestAgentsDataDirPath + "/BestHeuristics.txt");
try (final PrintWriter writer = new PrintWriter(bestHeuristicsFile))
{
final String heuristicsStr = FileHandling.loadTextContentsFromFile(evalHeuristicsFilepath);
final Heuristics heuristics = (Heuristics)compiler.Compiler.compileObject
(
heuristicsStr,
"metadata.ai.heuristics.Heuristics",
new Report()
);
System.out.println("writing new best heuristics");
writer.println(heuristics.toString());
}
catch (final IOException e)
{
e.printStackTrace();
}
}
if (writeFeatures)
{
final File bestFeaturesFile = new File(bestAgentsDataDirPath + "/BestFeatures.txt");
// We'll first just use the command line args we got to build a Biased MCTS
// Then we'll extract the features from that one
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= evalFeatureWeightsFilepaths.size(); ++p)
{
playoutSb.append(",policyweights" + p + "=" + evalFeatureWeightsFilepaths.get(p - 1));
}
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
"learned_selection_policy=playout",
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
// Generate our features metadata and write it
final Features features =
AIUtils.generateFeaturesMetadata
(
(SoftmaxPolicyLinear) mcts.learnedSelectionPolicy(),
(SoftmaxPolicyLinear) mcts.playoutStrategy()
);
try (final PrintWriter writer = new PrintWriter(bestFeaturesFile))
{
System.out.println("writing new best features");
writer.println(features.toString());
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
};
}
//-------------------------------------------------------------------------
/**
* Can be used for quick testing without command-line args, or proper
* testing with elaborate setup through command-line args
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// Feature Set caching is safe in this main method
JITSPatterNetFeatureSet.ALLOW_FEATURE_SET_CACHE = true;
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Gating experiment to test if a newly-trained agent outperforms current best."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to play. Should end with \".lud\".")
.withDefault("Amazons.lud")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--game-options")
.help("Game Options to load.")
.withDefault(new ArrayList<String>(0))
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--ruleset")
.help("Ruleset to compile.")
.withDefault("")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--eval-agent")
.help("Agent to be evaluated.")
.withNumVals(1)
.withType(OptionTypes.String)
.withLegalVals("Alpha-Beta", "BiasedMCTS", "BiasedMCTSUniformPlayouts")
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--eval-feature-weights-filepaths")
.help("Filepaths for feature weights to be evaluated.")
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--eval-heuristics-filepath")
.help("Filepath for heuristics to be evaluated.")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("-n", "--num-games", "--num-eval-games")
.help("Number of training games to run.")
.withDefault(Integer.valueOf(200))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--game-length-cap", "--max-num-actions")
.help("Maximum number of actions that may be taken before a game is terminated as a draw (-1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--thinking-time", "--time", "--seconds")
.help("Max allowed thinking time per move (in seconds).")
.withDefault(Double.valueOf(1.0))
.withNumVals(1)
.withType(OptionTypes.Double));
argParse.addOption(new ArgOption()
.withNames("--warming-up-secs")
.help("Number of seconds for which to warm up JVM.")
.withType(OptionTypes.Int)
.withNumVals(1)
.withDefault(Integer.valueOf(60)));
argParse.addOption(new ArgOption()
.withNames("--best-agents-data-dir")
.help("Filepath for directory containing data on best agents")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--gate-agent-type")
.help("Type of gate agent against which we wish to evaluate.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired()
.withLegalVals("BestAgent", "Alpha-Beta", "BiasedMCTS"));
argParse.addOption(new ArgOption()
.withNames("--useGUI")
.help("Whether to create a small GUI that can be used to "
+ "manually interrupt training run. False by default."));
argParse.addOption(new ArgOption()
.withNames("--max-wall-time")
.help("Max wall time in minutes (or -1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final EvalGate eval =
new EvalGate
(
argParse.getValueBool("--useGUI"),
argParse.getValueInt("--max-wall-time")
);
eval.gameName = argParse.getValueString("--game");
eval.gameOptions = (List<String>) argParse.getValue("--game-options");
eval.ruleset = argParse.getValueString("--ruleset");
eval.evalAgent = argParse.getValueString("--eval-agent");
eval.evalFeatureWeightsFilepaths = (List<String>) argParse.getValue("--eval-feature-weights-filepaths");
eval.evalHeuristicsFilepath = argParse.getValueString("--eval-heuristics-filepath");
eval.numGames = argParse.getValueInt("-n");
eval.gameLengthCap = argParse.getValueInt("--game-length-cap");
eval.thinkingTime = argParse.getValueDouble("--thinking-time");
eval.warmingUpSecs = argParse.getValueInt("--warming-up-secs");
eval.bestAgentsDataDir = new File(argParse.getValueString("--best-agents-data-dir"));
eval.gateAgentType = argParse.getValueString("--gate-agent-type");
eval.startExperiment();
}
//-------------------------------------------------------------------------
}
| 22,282 | 30.428773 | 115 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/eval/EvalPlayoutImplementations.java
|
package supplementary.experiments.eval;
import java.io.File;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
/**
* Implementation of an experiment that evaluates the performance
* of specialised playout implementations.
*
* Note that this is not about MCTS-specific playout enhancements,
* but about different implementations for the "standard" uniform-random
* playouts (AddToEmpty, ByPiece, ...)
*
* @author Dennis Soemers
*/
public class EvalPlayoutImplementations
{
/* Game setup */
/** Name of the game to play. Should end with .lud */
protected String gameName;
//-------------------------------------------------------------------------
/* Basic experiment setup */
/** Number of evaluation games to run */
protected int numGames;
/** Max allowed thinking time per move (in seconds) */
protected double thinkingTime;
/** Max allowed number of MCTS iterations per move */
protected int iterationLimit;
//-------------------------------------------------------------------------
/** File saving stuff */
/** Output directory */
protected File outDir;
//-------------------------------------------------------------------------
/* Auxiliary experiment setup */
/**
* Whether to create a small GUI that can be used to manually interrupt training run.
* False by default.
*/
protected boolean useGUI;
/** Max wall time in minutes (or -1 for no limit) */
protected int maxWallTime;
//-------------------------------------------------------------------------
/**
* Constructor. No GUI for interrupting experiment, no wall time limit.
*/
public EvalPlayoutImplementations()
{
// all defaults already set above
}
/**
* Constructor. No wall time limit.
* @param useGUI
*/
public EvalPlayoutImplementations(final boolean useGUI)
{
this.useGUI = useGUI;
}
/**
* Constructor
* @param useGUI
* @param maxWallTime Wall time limit in minutes.
*/
public EvalPlayoutImplementations(final boolean useGUI, final int maxWallTime)
{
this.useGUI = useGUI;
this.maxWallTime = maxWallTime;
}
//-------------------------------------------------------------------------
/**
* Starts the experiment
*/
public void startExperiment()
{
// TODO
}
//-------------------------------------------------------------------------
/**
* Can be used for quick testing without command-line args, or proper
* testing with elaborate setup through command-line args
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Evaluate playing strength of MCTS agents with different playout implementations against each other."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to play. Should end with \".lud\".")
.withDefault("Amazons.lud")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("-n", "--num-games", "--num-eval-games")
.help("Number of training games to run.")
.withDefault(Integer.valueOf(200))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--thinking-time", "--time", "--seconds")
.help("Max allowed thinking time per move (in seconds).")
.withDefault(Double.valueOf(1.0))
.withNumVals(1)
.withType(OptionTypes.Double));
argParse.addOption(new ArgOption()
.withNames("--iteration-limit", "--iterations")
.help("Max allowed number of MCTS iterations per move.")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
argParse.addOption(new ArgOption()
.withNames("--out-dir", "--output-directory")
.help("Filepath for output directory")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--useGUI")
.help("Whether to create a small GUI that can be used to "
+ "manually interrupt training run. False by default."));
argParse.addOption(new ArgOption()
.withNames("--max-wall-time")
.help("Max wall time in minutes (or -1 for no limit).")
.withDefault(Integer.valueOf(-1))
.withNumVals(1)
.withType(OptionTypes.Int));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final EvalPlayoutImplementations eval =
new EvalPlayoutImplementations
(
argParse.getValueBool("--useGUI"),
argParse.getValueInt("--max-wall-time")
);
eval.gameName = argParse.getValueString("--game");
eval.numGames = argParse.getValueInt("-n");
eval.thinkingTime = argParse.getValueDouble("--thinking-time");
eval.iterationLimit = argParse.getValueInt("--iteration-limit");
final String outDirFilepath = argParse.getValueString("--out-dir");
if (outDirFilepath != null)
eval.outDir = new File(outDirFilepath);
else
eval.outDir = null;
eval.startExperiment();
}
}
| 5,105 | 26.901639 | 106 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_importance/AnalyseFeatureImportances.java
|
package supplementary.experiments.feature_importance;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import features.Feature;
import features.FeatureVector;
import features.WeightVector;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import gnu.trove.list.array.TFloatArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.collections.ArrayUtils;
import main.collections.FVector;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import training.expert_iteration.ExItExperience;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
public class AnalyseFeatureImportances
{
//-------------------------------------------------------------------------
/**
* Do the analysis
* @param argParse
*/
private static void analyseFeatureImportances(final CommandLineArgParse argParse)
{
final String gameName = argParse.getValueString("--game-name");
String gameTrainingDirPath = argParse.getValueString("--game-training-dir");
if (!gameTrainingDirPath.endsWith("/"))
gameTrainingDirPath += "/";
final Game game = GameLoader.loadGameFromName(gameName);
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
gameTrainingDirPath + "PolicyWeights" +
"TSPG_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
playoutSb.append(",boosted=true"); // True for TSPG, false for CE
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
// NOTE: just doing Player 1 for now
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
gameTrainingDirPath +
"ExperienceBuffer_P" + 1,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
return;
}
}
}
// From here onwards very similar code to the decision tree building code
final BaseFeatureSet featureSet = featureSets[1];
final LinearFunction linFunc = linearFunctions[1];
final WeightVector oracleWeightVector = linFunc.effectiveParams();
final ExItExperience[] samples = buffer.allExperience();
final List<FeatureVector> allFeatureVectors = new ArrayList<FeatureVector>();
final TFloatArrayList allTargetLabels = new TFloatArrayList();
final List<List<FeatureVector>> featureVectorsPerState = new ArrayList<List<FeatureVector>>();
final List<TFloatArrayList> targetsPerState = new ArrayList<TFloatArrayList>();
for (final ExItExperience sample : samples)
{
if (sample != null && sample.moves().size() > 1)
{
final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet);
final float[] logits = new float[featureVectors.length];
for (int i = 0; i < featureVectors.length; ++i)
{
final FeatureVector featureVector = featureVectors[i];
logits[i] = oracleWeightVector.dot(featureVector);
}
final float maxLogit = ArrayUtils.max(logits);
final float minLogit = ArrayUtils.min(logits);
if (maxLogit == minLogit)
continue; // Nothing to learn from this, just skip it
for (int i = 0; i < featureVectors.length; ++i)
{
final FeatureVector featureVector = featureVectors[i];
allFeatureVectors.add(featureVector);
}
// Maximise logits for winning moves and minimise for losing moves
for (int i = sample.winningMoves().nextSetBit(0); i >= 0; i = sample.winningMoves().nextSetBit(i + 1))
{
logits[i] = maxLogit;
}
for (int i = sample.losingMoves().nextSetBit(0); i >= 0; i = sample.losingMoves().nextSetBit(i + 1))
{
logits[i] = minLogit;
}
final FVector policy = new FVector(logits);
policy.softmax();
final float maxProb = policy.max();
final float[] targets = new float[logits.length];
for (int i = 0; i < targets.length; ++i)
{
targets[i] = policy.get(i) / maxProb;
}
for (final float target : targets)
{
allTargetLabels.add(target);
}
featureVectorsPerState.add(Arrays.asList(featureVectors));
targetsPerState.add(TFloatArrayList.wrap(targets));
}
}
// For every aspatial and every spatial feature, if not already picked, compute mean prob for true and false branches
final int numAspatialFeatures = featureSet.getNumAspatialFeatures();
final int numSpatialFeatures = featureSet.getNumSpatialFeatures();
final double[] sumProbsIfFalseAspatial = new double[numAspatialFeatures];
final int[] numFalseAspatial = new int[numAspatialFeatures];
final double[] sumProbsIfTrueAspatial = new double[numAspatialFeatures];
final int[] numTrueAspatial = new int[numAspatialFeatures];
for (int i = 0; i < numAspatialFeatures; ++i)
{
for (int j = 0; j < allFeatureVectors.size(); ++j)
{
final FeatureVector featureVector = allFeatureVectors.get(j);
final float targetProb = allTargetLabels.getQuick(j);
if (featureVector.aspatialFeatureValues().get(i) != 0.f)
{
sumProbsIfTrueAspatial[i] += targetProb;
++numTrueAspatial[i];
}
else
{
sumProbsIfFalseAspatial[i] += targetProb;
++numFalseAspatial[i];
}
}
}
final double[] sumProbsIfFalseSpatial = new double[numSpatialFeatures];
final int[] numFalseSpatial = new int[numSpatialFeatures];
final double[] sumProbsIfTrueSpatial = new double[numSpatialFeatures];
final int[] numTrueSpatial = new int[numSpatialFeatures];
for (int i = 0; i < allFeatureVectors.size(); ++i)
{
final FeatureVector featureVector = allFeatureVectors.get(i);
final float targetProb = allTargetLabels.getQuick(i);
final boolean[] active = new boolean[numSpatialFeatures];
final TIntArrayList sparseSpatials = featureVector.activeSpatialFeatureIndices();
for (int j = 0; j < sparseSpatials.size(); ++j)
{
active[sparseSpatials.getQuick(j)] = true;
}
for (int j = 0; j < active.length; ++j)
{
if (active[j])
{
sumProbsIfTrueSpatial[j] += targetProb;
++numTrueSpatial[j];
}
else
{
sumProbsIfFalseSpatial[j] += targetProb;
++numFalseSpatial[j];
}
}
}
final double[] meanProbsIfFalseAspatial = new double[numAspatialFeatures];
final double[] meanProbsIfTrueAspatial = new double[numAspatialFeatures];
final double[] meanProbsIfFalseSpatial = new double[numSpatialFeatures];
final double[] meanProbsIfTrueSpatial = new double[numSpatialFeatures];
for (int i = 0; i < numAspatialFeatures; ++i)
{
if (numFalseAspatial[i] > 0)
meanProbsIfFalseAspatial[i] = sumProbsIfFalseAspatial[i] / numFalseAspatial[i];
if (numTrueAspatial[i] > 0)
meanProbsIfTrueAspatial[i] = sumProbsIfTrueAspatial[i] / numTrueAspatial[i];
}
for (int i = 0; i < numSpatialFeatures; ++i)
{
if (numFalseSpatial[i] > 0)
meanProbsIfFalseSpatial[i] = sumProbsIfFalseSpatial[i] / numFalseSpatial[i];
if (numTrueSpatial[i] > 0)
meanProbsIfTrueSpatial[i] = sumProbsIfTrueSpatial[i] / numTrueSpatial[i];
}
// Allocate our rows
final List<Row> rows = new ArrayList<Row>();
for (int i = 0; i < numAspatialFeatures; ++i)
{
rows.add(new Row(featureSet.aspatialFeatures()[i]));
}
for (int i = 0; i < numSpatialFeatures; ++i)
{
rows.add(new Row(featureSet.spatialFeatures()[i]));
}
// Compute baseline SSE
double baselineSSE = 0.0;
final double baselinePrediction = allTargetLabels.sum() / allTargetLabels.size();
for (int i = 0; i < allTargetLabels.size(); ++i)
{
final double error = allTargetLabels.getQuick(i) - baselinePrediction;
baselineSSE += (error * error);
}
// Compute sums of squared errors
for (int i = 0; i < numAspatialFeatures; ++i)
{
final int rowIdx = i;
final Row row = rows.get(rowIdx);
double sumSquaredErrors = 0.0;
double sumSquaredErrorsFalse = 0.0;
double sumSquaredErrorsTrue = 0.0;
for (int j = 0; j < allFeatureVectors.size(); ++j)
{
final FeatureVector featureVector = allFeatureVectors.get(j);
final float targetProb = allTargetLabels.getQuick(j);
final double error;
if (featureVector.aspatialFeatureValues().get(i) != 0.f)
{
error = targetProb - meanProbsIfTrueAspatial[i];
sumSquaredErrorsTrue += (error * error);
}
else
{
error = targetProb - meanProbsIfFalseAspatial[i];
sumSquaredErrorsFalse += (error * error);
}
sumSquaredErrors += (error * error);
}
row.sse = sumSquaredErrors;
row.reductionSSE = baselineSSE - sumSquaredErrors;
row.sseFalse = sumSquaredErrorsFalse;
row.sseTrue = sumSquaredErrorsTrue;
row.sampleSizeFalse = numFalseAspatial[i];
row.sampleSizeTrue = numTrueAspatial[i];
row.meanTargetFalse = meanProbsIfFalseAspatial[i];
row.meanTargetTrue = meanProbsIfTrueAspatial[i];
}
for (int i = 0; i < numSpatialFeatures; ++i)
{
final int rowIdx = i + numAspatialFeatures;
final Row row = rows.get(rowIdx);
double sumSquaredErrors = 0.0;
double sumSquaredErrorsFalse = 0.0;
double sumSquaredErrorsTrue = 0.0;
for (int j = 0; j < allFeatureVectors.size(); ++j)
{
final FeatureVector featureVector = allFeatureVectors.get(j);
final float targetProb = allTargetLabels.getQuick(j);
final double error;
if (featureVector.activeSpatialFeatureIndices().contains(i))
{
error = targetProb - meanProbsIfTrueSpatial[i];
sumSquaredErrorsTrue += (error * error);
}
else
{
error = targetProb - meanProbsIfFalseSpatial[i];
sumSquaredErrorsFalse += (error * error);
}
sumSquaredErrors += (error * error);
}
row.sse = sumSquaredErrors;
row.reductionSSE = baselineSSE - sumSquaredErrors;
row.sseFalse = sumSquaredErrorsFalse;
row.sseTrue = sumSquaredErrorsTrue;
row.sampleSizeFalse = numFalseSpatial[i];
row.sampleSizeTrue = numTrueSpatial[i];
row.meanTargetFalse = meanProbsIfFalseSpatial[i];
row.meanTargetTrue = meanProbsIfTrueSpatial[i];
}
final double negativeRange = baselinePrediction;
final double positiveRange = 1.0 - baselinePrediction;
// For every feature, compute urgency
for (int i = 0; i < numAspatialFeatures; ++i)
{
final int rowIdx = i;
final Row row = rows.get(rowIdx);
final double falseUrgency = Math.max(meanProbsIfFalseAspatial[i] / baselinePrediction, baselinePrediction / meanProbsIfFalseAspatial[i]);
final double trueUrgency = Math.max(meanProbsIfTrueAspatial[i] / baselinePrediction, baselinePrediction / meanProbsIfTrueAspatial[i]);
final double urgency = Math.max(falseUrgency, trueUrgency);
row.urgency = urgency;
final double weightedFalseUrgency = Math.log10(numFalseAspatial[i]) * Math.max(meanProbsIfFalseAspatial[i] / baselinePrediction, baselinePrediction / meanProbsIfFalseAspatial[i]);
final double weightedTrueUrgency = Math.log10(numTrueAspatial[i]) * Math.max(meanProbsIfTrueAspatial[i] / baselinePrediction, baselinePrediction / meanProbsIfTrueAspatial[i]);
final double weightedUrgency = Math.max(weightedFalseUrgency, weightedTrueUrgency);
row.weightedUrgency = weightedUrgency;
row.urgencyRatio = Math.max(falseUrgency / trueUrgency, trueUrgency / falseUrgency);
final double scaledUrgencyFalse;
if (meanProbsIfFalseAspatial[i] > baselinePrediction)
scaledUrgencyFalse = (meanProbsIfFalseAspatial[i] - baselinePrediction) / positiveRange;
else
scaledUrgencyFalse = (baselinePrediction - meanProbsIfFalseAspatial[i]) / negativeRange;
final double scaledUrgencyTrue;
if (meanProbsIfTrueAspatial[i] > baselinePrediction)
scaledUrgencyTrue = (meanProbsIfTrueAspatial[i] - baselinePrediction) / positiveRange;
else
scaledUrgencyTrue = (baselinePrediction - meanProbsIfTrueAspatial[i]) / negativeRange;
row.scaledUrgency = Math.max(scaledUrgencyFalse, scaledUrgencyTrue);
}
for (int i = 0; i < numSpatialFeatures; ++i)
{
final int rowIdx = i + numAspatialFeatures;
final Row row = rows.get(rowIdx);
final double falseUrgency = Math.max(meanProbsIfFalseSpatial[i] / baselinePrediction, baselinePrediction / meanProbsIfFalseSpatial[i]);
final double trueUrgency = Math.max(meanProbsIfTrueSpatial[i] / baselinePrediction, baselinePrediction / meanProbsIfTrueSpatial[i]);
final double urgency = Math.max(falseUrgency, trueUrgency);
row.urgency = urgency;
final double weightedFalseUrgency = Math.log10(numFalseSpatial[i]) * Math.max(meanProbsIfFalseSpatial[i] / baselinePrediction, baselinePrediction / meanProbsIfFalseSpatial[i]);
final double weightedTrueUrgency = Math.log10(numTrueSpatial[i]) * Math.max(meanProbsIfTrueSpatial[i] / baselinePrediction, baselinePrediction / meanProbsIfTrueSpatial[i]);
final double weightedUrgency = Math.max(weightedFalseUrgency, weightedTrueUrgency);
row.weightedUrgency = weightedUrgency;
row.urgencyRatio = Math.max(falseUrgency / trueUrgency, trueUrgency / falseUrgency);
final double scaledUrgencyFalse;
if (meanProbsIfFalseSpatial[i] > baselinePrediction)
scaledUrgencyFalse = (meanProbsIfFalseSpatial[i] - baselinePrediction) / positiveRange;
else
scaledUrgencyFalse = (baselinePrediction - meanProbsIfFalseSpatial[i]) / negativeRange;
final double scaledUrgencyTrue;
if (meanProbsIfTrueSpatial[i] > baselinePrediction)
scaledUrgencyTrue = (meanProbsIfTrueSpatial[i] - baselinePrediction) / positiveRange;
else
scaledUrgencyTrue = (baselinePrediction - meanProbsIfTrueSpatial[i]) / negativeRange;
row.scaledUrgency = Math.max(scaledUrgencyFalse, scaledUrgencyTrue);
}
// for (int s = 0; s < featureVectorsPerState.size(); ++s)
// {
// final List<FeatureVector> featureVectors = featureVectorsPerState.get(s);
// final TFloatArrayList targets = targetsPerState.get(s);
// final int numActions = targets.size();
//
// for (int i = 0; i < numAspatialFeatures; ++i)
// {
// final int rowIdx = i;
// final Row row = rows.get(rowIdx);
//
// // Compute policy for this state if we were to use only this feature
// final FVector policy = new FVector(numActions);
//
// for (int a = 0; a < numActions; ++a)
// {
// final FeatureVector featureVector = featureVectors.get(a);
//
// if (featureVector.aspatialFeatureValues().get(i) != 0.f)
// policy.set(a, (float) meanProbsIfTrueAspatial[i]);
// else
// policy.set(a, (float) meanProbsIfFalseAspatial[i]);
// }
//
// policy.normalise();
//
// for (int a = 0; a < numActions; ++a)
// {
// row.sumExpectedRegrets += (policy.get(a) * (1.0 - targets.getQuick(a)));
// row.sumExpectedSquaredRegrets += (policy.get(a) * (1.0 - targets.getQuick(a)) * (1.0 - targets.getQuick(a)));
// }
// }
//
// for (int i = 0; i < numSpatialFeatures; ++i)
// {
// final int rowIdx = i + numAspatialFeatures;
// final Row row = rows.get(rowIdx);
//
// // Compute policy for this state if we were to use only this feature
// final FVector policy = new FVector(numActions);
//
// for (int a = 0; a < numActions; ++a)
// {
// final FeatureVector featureVector = featureVectors.get(a);
//
// if (featureVector.activeSpatialFeatureIndices().contains(i))
// policy.set(a, (float) meanProbsIfTrueSpatial[i]);
// else
// policy.set(a, (float) meanProbsIfFalseSpatial[i]);
// }
//
// policy.normalise();
//
// for (int a = 0; a < numActions; ++a)
// {
// row.sumExpectedRegrets += (policy.get(a) * (1.0 - targets.getQuick(a)));
// row.sumExpectedSquaredRegrets += (policy.get(a) * (1.0 - targets.getQuick(a)) * (1.0 - targets.getQuick(a)));
// }
// }
// }
Collections.sort
(
rows, new Comparator<Row>()
{
@Override
public int compare(final Row o1, final Row o2)
{
if (o1.reductionSSE > o2.reductionSSE)
return - 1;
if (o1.reductionSSE < o2.reductionSSE)
return 1;
return 0;
}
});
try (final PrintWriter writer = new PrintWriter(argParse.getValueString("--out-file"), "UTF-8"))
{
// Write the header
writer.println
(
"Feature,SSE,ReductionSSE,SseFalse,SseTrue,SampleSizeFalse,SampleSizeTrue,MeanTargetFalse,"
+
"MeanTargetTrue,"
//+ "SumExpectedRegrets,SumExpectedSquaredRegrets,"
+ "Urgency,WeightedUrgency,UrgencyRatio,ScaledUrgency"
);
for (final Row row : rows)
{
if (row.sampleSizeFalse > 0 && row.sampleSizeTrue > 0)
writer.println(row);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* A row in the dataset we're creating
*
* @author Dennis Soemers
*/
private static class Row
{
public final Feature feature;
public double sse;
public double reductionSSE;
public double sseFalse;
public double sseTrue;
public int sampleSizeFalse;
public int sampleSizeTrue;
public double meanTargetFalse;
public double meanTargetTrue;
//public double sumExpectedRegrets;
//public double sumExpectedSquaredRegrets;
public double urgency;
public double weightedUrgency;
public double urgencyRatio;
public double scaledUrgency;
/**
* Constructor
*
* @param feature
*/
public Row(final Feature feature)
{
this.feature = feature;
}
@Override
public String toString()
{
return StringRoutines.join
(
",",
StringRoutines.quote(feature.toString()),
Double.valueOf(sse),
Double.valueOf(reductionSSE),
Double.valueOf(sseFalse),
Double.valueOf(sseTrue),
Double.valueOf(sampleSizeFalse),
Double.valueOf(sampleSizeTrue),
Double.valueOf(meanTargetFalse),
Double.valueOf(meanTargetTrue),
//Double.valueOf(sumExpectedRegrets),
//Double.valueOf(sumExpectedSquaredRegrets),
Double.valueOf(urgency),
Double.valueOf(weightedUrgency),
Double.valueOf(urgencyRatio),
Double.valueOf(scaledUrgency)
);
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Analyses feature importances for a game."
);
argParse.addOption(new ArgOption()
.withNames("--game-training-dir")
.help("The directory with training outcomes for the game to analyse.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--game-name")
.help("Name of the game.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write data to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
analyseFeatureImportances(argParse);
}
//-------------------------------------------------------------------------
}
| 20,982 | 30.648567 | 182 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_importance/IdentifyTopFeatures.java
|
package supplementary.experiments.feature_importance;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import decision_trees.classifiers.DecisionConditionNode;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceUrgencyTreeLearner;
import features.Feature;
import features.FeatureVector;
import features.WeightVector;
import features.aspatial.AspatialFeature;
import features.feature_sets.BaseFeatureSet;
import features.feature_sets.network.JITSPatterNetFeatureSet;
import features.spatial.SpatialFeature;
import features.spatial.SpatialFeature.RotRefInvariantFeature;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import gnu.trove.list.array.TFloatArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.collections.ArrayUtils;
import main.collections.FVector;
import main.collections.ListUtils;
import main.collections.ScoredInt;
import main.math.statistics.IncrementalStats;
import metadata.ai.misc.Pair;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.trial.Trial;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import training.expert_iteration.ExItExperience;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Script to identify small collection of top features
*
* @author Dennis Soemers
*/
public class IdentifyTopFeatures
{
//-------------------------------------------------------------------------
/**
* Every feature is, per generation, guaranteed to get this many trials
* (likely each against a different opponent feature) for eval.
*/
private static final int NUM_TRIALS_PER_FEATURE_EVAL = 50;
/** Number of features we want to end up with at the end (per player). */
private static final int GOAL_NUM_FEATURES = 15;
/** Number of trials to run per evaluation for deciding whether or not to grow feature set */
private static final int NUM_EVAL_TRIALS_FEATURESET_GROWING = 150;
//-------------------------------------------------------------------------
/**
* Runs the process
* @param parsedArgs
*/
private static void identifyTopFeatures(final CommandLineArgParse parsedArgs)
{
final String gameName = parsedArgs.getValueString("--game");
final String ruleset = parsedArgs.getValueString("--ruleset");
final Game game;
if (ruleset != null && !ruleset.equals(""))
game = GameLoader.loadGameFromName(gameName, ruleset);
else
game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName + " (ruleset = " + ruleset + ")");
try
{
final int numPlayers = game.players().count();
String trainingOutDirPath = parsedArgs.getValueString("--training-out-dir");
if (!trainingOutDirPath.endsWith("/"))
trainingOutDirPath += "/";
// Load feature sets and policies
final BaseFeatureSet[] featureSets = new BaseFeatureSet[numPlayers + 1];
final LinearFunction[] linearFunctionsPlayout = new LinearFunction[numPlayers + 1];
final LinearFunction[] linearFunctionsTSPG = new LinearFunction[numPlayers + 1];
if (!loadFeaturesAndWeights(game, trainingOutDirPath, featureSets, linearFunctionsPlayout, linearFunctionsTSPG))
{
System.out.println("Did not manage to load any files for " + gameName + " (ruleset = " + ruleset + ")");
return;
}
// for (int p = 1; p < featureSets.length; ++p)
// {
// // Add simplified versions of existing spatial features
// final BaseFeatureSet featureSet = featureSets[p];
// final SpatialFeature[] origSpatialFeatures = featureSet.spatialFeatures();
// final List<SpatialFeature> featuresToAdd = new ArrayList<SpatialFeature>();
//
// for (final SpatialFeature feature : origSpatialFeatures)
// {
// featuresToAdd.addAll(feature.generateGeneralisers(game));
// }
//
// featureSets[p] = featureSet.createExpandedFeatureSet(game, featuresToAdd);
// featureSets[p].init(game, new int[] {p}, null);
// }
// Load experience buffers
final ExperienceBuffer[] experienceBuffers = new ExperienceBuffer[numPlayers + 1];
loadExperienceBuffers(game, trainingOutDirPath, experienceBuffers);
// Build trees for all players
final DecisionTreeNode[] playoutTreesPerPlayer = new DecisionTreeNode[numPlayers + 1];
final DecisionTreeNode[] tspgTreesPerPlayer = new DecisionTreeNode[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
playoutTreesPerPlayer[p] =
ExperienceUrgencyTreeLearner.buildTree(featureSets[p], linearFunctionsPlayout[p], experienceBuffers[p], 4, 10);
tspgTreesPerPlayer[p] =
ExperienceUrgencyTreeLearner.buildTree(featureSets[p], linearFunctionsTSPG[p], experienceBuffers[p], 4, 10);
}
// For every player, extract candidate features from the decision trees for that player
final List<List<AspatialFeature>> candidateAspatialFeaturesPerPlayer = new ArrayList<List<AspatialFeature>>();
final List<List<SpatialFeature>> candidateSpatialFeaturesPerPlayer = new ArrayList<List<SpatialFeature>>();
candidateAspatialFeaturesPerPlayer.add(null);
candidateSpatialFeaturesPerPlayer.add(null);
for (int p = 1; p <= numPlayers; ++p)
{
// Collect all the features in our trees
final List<AspatialFeature> aspatialFeaturesList = new ArrayList<AspatialFeature>();
List<SpatialFeature> spatialFeaturesList = new ArrayList<SpatialFeature>();
final List<Feature> featuresList = new ArrayList<Feature>();
collectFeatures(playoutTreesPerPlayer[p], featuresList);
collectFeatures(tspgTreesPerPlayer[p], featuresList);
// Get rid of any sorts of duplicates/redundancies
for (final Feature feature : featuresList)
{
if (feature instanceof AspatialFeature)
{
if (!aspatialFeaturesList.contains(feature))
aspatialFeaturesList.add((AspatialFeature) feature);
}
else
{
spatialFeaturesList.add((SpatialFeature) feature);
}
}
spatialFeaturesList = SpatialFeature.deduplicate(spatialFeaturesList);
spatialFeaturesList = SpatialFeature.simplifySpatialFeaturesList(game, spatialFeaturesList);
// Add generalisers of our candidate spatial features
final Set<RotRefInvariantFeature> generalisers = new HashSet<RotRefInvariantFeature>();
for (final SpatialFeature f : spatialFeaturesList)
{
f.generateGeneralisers(game, generalisers, 1);
}
for (final RotRefInvariantFeature f : generalisers)
{
spatialFeaturesList.add(f.feature());
}
// Do another round of cleaning up duplicates
spatialFeaturesList = SpatialFeature.deduplicate(spatialFeaturesList);
spatialFeaturesList = SpatialFeature.simplifySpatialFeaturesList(game, spatialFeaturesList);
candidateAspatialFeaturesPerPlayer.add(new ArrayList<AspatialFeature>());
//candidateAspatialFeaturesPerPlayer.add(aspatialFeaturesList); TODO leaving aspatial features out, annoying to get weight vectors correct
candidateSpatialFeaturesPerPlayer.add(spatialFeaturesList);
}
// Create new feature sets with all the candidate features
final BaseFeatureSet[] candidateFeatureSets = new BaseFeatureSet[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
candidateFeatureSets[p] = JITSPatterNetFeatureSet.construct(candidateAspatialFeaturesPerPlayer.get(p), candidateSpatialFeaturesPerPlayer.get(p));
candidateFeatureSets[p].init(game, new int [] {p}, null);
}
// For every candidate feature, determine a single weight as the one we
// would have used for it if the feature were used in the root of a logit tree
final FVector[] candidateFeatureWeightsPerPlayer = new FVector[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
candidateFeatureWeightsPerPlayer[p] =
computeCandidateFeatureWeights
(
candidateFeatureSets[p],
featureSets[p],
linearFunctionsPlayout[p],
experienceBuffers[p]
);
}
// Clear some memory
Arrays.fill(experienceBuffers, null);
Arrays.fill(candidateFeatureSets, null);
Arrays.fill(featureSets, null);
// Run trials to evaluate all our candidate features and rank them
final List<List<Feature>> candidateFeaturesPerPlayer = new ArrayList<List<Feature>>(numPlayers + 1);
candidateFeaturesPerPlayer.add(null);
for (int p = 1; p <= numPlayers; ++p)
{
final List<Feature> candidateFeatures = new ArrayList<Feature>();
candidateFeatures.addAll(candidateAspatialFeaturesPerPlayer.get(p));
candidateFeatures.addAll(candidateSpatialFeaturesPerPlayer.get(p));
candidateFeaturesPerPlayer.add(candidateFeatures);
// System.out.println("Candidate features for player " + p);
//
// for (final Feature f : candidateFeatures)
// {
// System.out.println(f);
// }
//
// System.out.println();
}
evaluateCandidateFeatures(game, candidateFeaturesPerPlayer, candidateFeatureWeightsPerPlayer, parsedArgs);
}
catch (final Exception e)
{
System.err.println("Exception in game: " + gameName + " (ruleset = " + ruleset + ")");
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Evaluates all the given candidate features and tries to rank them by playing
* a bunch of trials with them.
*
* @param game
* @param candidateFeaturesPerPlayer
* @param candidateFeatureWeightsPerPlayer
* @param parsedArgs
*/
private static void evaluateCandidateFeatures
(
final Game game,
final List<List<Feature>> candidateFeaturesPerPlayer,
final FVector[] candidateFeatureWeightsPerPlayer,
final CommandLineArgParse parsedArgs
)
{
String outDir = parsedArgs.getValueString("--out-dir");
if (!outDir.endsWith("/"))
outDir += "/";
new File(outDir).mkdirs();
final int numPlayers = game.players().count();
final IncrementalStats[][] playerFeatureScores = new IncrementalStats[numPlayers + 1][];
final TIntArrayList[] remainingFeaturesPerPlayer = new TIntArrayList[numPlayers + 1];
final BaseFeatureSet[] playerFeatureSets = new BaseFeatureSet[numPlayers + 1];
final LinearFunction[] playerLinFuncs = new LinearFunction[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
playerFeatureScores[p] = new IncrementalStats[candidateFeaturesPerPlayer.get(p).size()];
for (int i = 0; i < playerFeatureScores[p].length; ++i)
{
playerFeatureScores[p][i] = new IncrementalStats();
}
remainingFeaturesPerPlayer[p] = ListUtils.range(candidateFeaturesPerPlayer.get(p).size());
playerLinFuncs[p] = new LinearFunction(new WeightVector(FVector.wrap(new float[] {Float.NaN})));
}
boolean terminateProcess = false;
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
int generation = 0;
while (!terminateProcess)
{
// Start a new generation
++generation;
for (int p = 1; p <= numPlayers; ++p)
{
// An evaluation round for all features of player p
for (int i = 0; i < remainingFeaturesPerPlayer[p].size(); ++i)
{
// Evaluate i'th feature for player p
final int idxFeatureToEval = remainingFeaturesPerPlayer[p].getQuick(i);
playerFeatureSets[p] = JITSPatterNetFeatureSet.construct(
Arrays.asList(candidateFeaturesPerPlayer.get(p).get(idxFeatureToEval)));
playerFeatureSets[p].init(game, new int[] {p}, null);
playerLinFuncs[p].trainableParams().allWeights().set(0, candidateFeatureWeightsPerPlayer[p].get(idxFeatureToEval));
for (int trialIdx = 0; trialIdx < (NUM_TRIALS_PER_FEATURE_EVAL * generation); ++trialIdx)
{
game.start(context);
// Pick random feature indices for all other players
final int[] featureIndices = new int[numPlayers + 1];
featureIndices[0] = Integer.MIN_VALUE;
featureIndices[p] = idxFeatureToEval;
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
for (int opp = 1; opp <= numPlayers; ++opp)
{
if (opp != p)
{
featureIndices[opp] =
ThreadLocalRandom.current().nextInt(remainingFeaturesPerPlayer[opp].size());
playerFeatureSets[opp] = JITSPatterNetFeatureSet.construct(
Arrays.asList(candidateFeaturesPerPlayer.get(opp).get(featureIndices[opp])));
playerLinFuncs[opp].trainableParams().allWeights().set(0, candidateFeatureWeightsPerPlayer[opp].get(featureIndices[opp]));
}
}
for (int player = 1; player <= numPlayers; ++player)
{
final SoftmaxPolicyLinear softmax = new SoftmaxPolicyLinear(playerLinFuncs, playerFeatureSets);
ais.add(softmax);
softmax.initAI(game, player);
}
// Play the trial
game.playout(context, ais, 1.0, null, -1, -1, null);
// Cleanup memory
for (int player = 1; player <= numPlayers; ++player)
{
ais.get(player).closeAI();
}
// Update feature evaluations
final double[] agentUtils = RankUtils.agentUtilities(context);
for (int player = 1; player <= numPlayers; ++player)
{
playerFeatureScores[player][featureIndices[player]].observe(agentUtils[player]);
}
}
}
}
// We'll terminate except if in the evaluation we decide that we want to keep going
terminateProcess = true;
// Evaluate the entire generation
for (int p = 1; p <= numPlayers; ++p)
{
// Sort remaining feature indices for this player based on their scores
final List<ScoredInt> scoredIndices = new ArrayList<ScoredInt>();
for (int i = 0; i < remainingFeaturesPerPlayer[p].size(); ++i)
{
final int fIdx = remainingFeaturesPerPlayer[p].getQuick(i);
scoredIndices.add(new ScoredInt(fIdx, playerFeatureScores[p][fIdx].getMean()));
}
Collections.sort(scoredIndices, ScoredInt.DESCENDING);
// Keep only the best ones
final int numToKeep = Math.min(scoredIndices.size(), Math.max(GOAL_NUM_FEATURES, scoredIndices.size() / 2));
final TIntArrayList keepIndices = new TIntArrayList();
for (int i = 0; i < numToKeep; ++i)
{
final int fIdx = scoredIndices.get(i).object();
keepIndices.add(fIdx);
}
remainingFeaturesPerPlayer[p] = keepIndices;
if (numToKeep > GOAL_NUM_FEATURES)
terminateProcess = false; // Should keep going
}
}
// Obtain the rankings of feature indices per player
final List<List<ScoredInt>> scoredIndicesPerPlayer = new ArrayList<List<ScoredInt>>();
scoredIndicesPerPlayer.add(null);
for (int p = 1; p <= numPlayers; ++p)
{
final List<ScoredInt> scoredIndices = new ArrayList<ScoredInt>();
for (int i = 0; i < remainingFeaturesPerPlayer[p].size(); ++i)
{
final int fIdx = remainingFeaturesPerPlayer[p].getQuick(i);
scoredIndices.add(new ScoredInt(fIdx, playerFeatureScores[p][fIdx].getMean()));
}
Collections.sort(scoredIndices, ScoredInt.DESCENDING);
scoredIndicesPerPlayer.add(scoredIndices);
}
// Print initial rankings of features for all players
try (final PrintWriter writer = new PrintWriter(outDir + "RankedFeatures.txt", "UTF-8"))
{
for (int p = 1; p <= numPlayers; ++p)
{
writer.println("Scores for Player " + p);
for (final ScoredInt scoredIdx : scoredIndicesPerPlayer.get(p))
{
final int fIdx = scoredIdx.object();
writer.println
(
"Feature=" + candidateFeaturesPerPlayer.get(p).get(fIdx) +
",weight=" + candidateFeatureWeightsPerPlayer[p].get(fIdx) +
",score=" + playerFeatureScores[p][fIdx].getMean()
);
}
writer.println();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Now we're going to try to build bigger featuresets that beat smaller ones
final BaseFeatureSet[] bestFeatureSetPerPlayer = new BaseFeatureSet[numPlayers + 1];
final LinearFunction[] bestLinFuncPerPlayer = new LinearFunction[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
final int fIdx = scoredIndicesPerPlayer.get(p).get(0).object();
bestFeatureSetPerPlayer[p] = JITSPatterNetFeatureSet.construct(
Arrays.asList(candidateFeaturesPerPlayer.get(p).get(fIdx)));
bestLinFuncPerPlayer[p] = new LinearFunction(
new WeightVector(FVector.wrap(new float[] {candidateFeatureWeightsPerPlayer[p].get(fIdx)})));
}
//final boolean[] keepGrowing = new boolean[numPlayers + 1];
//Arrays.fill(keepGrowing, 1, numPlayers + 1, true);
int nextFeatureRank = 1;
//while (ArrayUtils.contains(keepGrowing, true))
while (nextFeatureRank < GOAL_NUM_FEATURES)
{
// Evaluate baselines against each other
final IncrementalStats[] baselinePerformancePerPlayer = new IncrementalStats[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
baselinePerformancePerPlayer[p] = new IncrementalStats();
}
// Create baseline AIs
final List<AI> baselineAIs = new ArrayList<AI>();
baselineAIs.add(null);
for (int p = 1; p <= numPlayers; ++p)
{
baselineAIs.add(new SoftmaxPolicyLinear(bestLinFuncPerPlayer, bestFeatureSetPerPlayer));
}
for (int t = 0; t < NUM_EVAL_TRIALS_FEATURESET_GROWING; ++t)
{
game.start(context);
// Init AIs
for (int p = 1; p <= numPlayers; ++p)
{
baselineAIs.get(p).initAI(game, p);
}
// Play the trial
game.playout(context, baselineAIs, 1.0, null, -1, -1, null);
// Update baseline stats
final double[] agentUtils = RankUtils.agentUtilities(context);
for (int p = 1; p <= numPlayers; ++p)
{
baselinePerformancePerPlayer[p].observe(agentUtils[p]);
}
}
// Now, for every player, try adding the next-best feature and see if that helps us
// perform better against opposing baselines
final boolean[] updateBaseline = new boolean[numPlayers + 1];
for (int player = 1; player <= numPlayers; ++player)
{
//if (keepGrowing[player])
if (nextFeatureRank < scoredIndicesPerPlayer.get(player).size())
{
// Create list of AIs for this eval round
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
for (int p = 1; p <= numPlayers; ++p)
{
if (p == player)
{
// Create AI with extra feature
final int fIdx = scoredIndicesPerPlayer.get(p).get(nextFeatureRank).object();
final Feature newFeature = candidateFeaturesPerPlayer.get(p).get(fIdx);
final List<Feature> features = new ArrayList<Feature>();
for (final Feature f : bestFeatureSetPerPlayer[p].aspatialFeatures())
{
features.add(f);
}
for (final Feature f : bestFeatureSetPerPlayer[p].spatialFeatures())
{
features.add(f);
}
features.add(newFeature);
final BaseFeatureSet biggerFeatureSet = JITSPatterNetFeatureSet.construct(features);
final LinearFunction biggerLinFunc = new LinearFunction(new WeightVector(new FVector(features.size())));
biggerLinFunc.trainableParams().allWeights().copyFrom(
bestLinFuncPerPlayer[p].trainableParams().allWeights(), 0, 0, features.size() - 1);
biggerLinFunc.trainableParams().allWeights().set(features.size() - 1, candidateFeatureWeightsPerPlayer[p].get(fIdx));
final BaseFeatureSet[] featureSetsArray = Arrays.copyOf(bestFeatureSetPerPlayer, numPlayers + 1);
featureSetsArray[p] = biggerFeatureSet;
final LinearFunction[] linFuncsArray = Arrays.copyOf(bestLinFuncPerPlayer, numPlayers + 1);
linFuncsArray[p] = biggerLinFunc;
ais.add(new SoftmaxPolicyLinear(linFuncsArray, featureSetsArray));
}
else
{
// Just use the baseline
ais.add(baselineAIs.get(p));
}
}
// Play trials with these AIs; all baselines except a bigger featureset for the one to evaluate
final IncrementalStats evalStats = new IncrementalStats();
for (int t = 0; t < NUM_EVAL_TRIALS_FEATURESET_GROWING; ++t)
{
game.start(context);
// Init AIs
for (int p = 1; p <= numPlayers; ++p)
{
ais.get(p).initAI(game, p);
}
// Play the trial
game.playout(context, ais, 1.0, null, -1, -1, null);
// Cleanup memory
for (int p = 1; p <= numPlayers; ++p)
{
ais.get(p).closeAI();
}
// Update eval stats
final double[] agentUtils = RankUtils.agentUtilities(context);
evalStats.observe(agentUtils[player]);
}
// Check whether the bigger featureset outperforms the smaller one
if (evalStats.getMean() > baselinePerformancePerPlayer[player].getMean())
{
// We performed better, so we'll want the baseline to grow
updateBaseline[player] = true;
}
// else
// {
// // Did not perform better, so skip trying to grow this player's featureset forever
// keepGrowing[player] = false;
// }
}
}
// Went through all players, so now update baselines if necessary
for (int p = 1; p <= numPlayers; ++p)
{
if (updateBaseline[p])
{
// Create the bigger feature set and linear function again
final int fIdx = scoredIndicesPerPlayer.get(p).get(nextFeatureRank).object();
final Feature newFeature = candidateFeaturesPerPlayer.get(p).get(fIdx);
final List<Feature> features = new ArrayList<Feature>();
for (final Feature f : bestFeatureSetPerPlayer[p].aspatialFeatures())
{
features.add(f);
}
for (final Feature f : bestFeatureSetPerPlayer[p].spatialFeatures())
{
features.add(f);
}
features.add(newFeature);
final BaseFeatureSet biggerFeatureSet = JITSPatterNetFeatureSet.construct(features);
final LinearFunction biggerLinFunc = new LinearFunction(new WeightVector(new FVector(features.size())));
biggerLinFunc.trainableParams().allWeights().copyFrom(
bestLinFuncPerPlayer[p].trainableParams().allWeights(), 0, 0, features.size() - 1);
biggerLinFunc.trainableParams().allWeights().set(features.size() - 1, candidateFeatureWeightsPerPlayer[p].get(fIdx));
// Update the baselines
bestFeatureSetPerPlayer[p] = biggerFeatureSet;
bestLinFuncPerPlayer[p] = biggerLinFunc;
}
}
++nextFeatureRank;
}
// Create metadata items of the best feature sets
final metadata.ai.features.FeatureSet[] featureSets = new metadata.ai.features.FeatureSet[numPlayers];
for (int p = 1; p <= numPlayers; ++p)
{
final Pair[] pairs = new Pair[bestFeatureSetPerPlayer[p].getNumFeatures()];
final SpatialFeature[] features = bestFeatureSetPerPlayer[p].spatialFeatures();
final FVector weights = bestLinFuncPerPlayer[p].trainableParams().allWeights();
for (int i = 0; i < pairs.length; ++i)
{
pairs[i] = new Pair(features[i].toString(), Float.valueOf(weights.get(i)));
}
featureSets[p - 1] = new metadata.ai.features.FeatureSet(RoleType.roleForPlayerId(p), pairs);
}
// Write all the features metadata
final metadata.ai.features.Features featuresMetadata = new metadata.ai.features.Features(featureSets);
try (final PrintWriter writer = new PrintWriter(outDir + "BestFeatures.txt", "UTF-8"))
{
writer.print(featuresMetadata.toString());
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* @param candidateFeatureSet
* @param originalFeatureSet
* @param oracleFunction
* @param experienceBuffer
* @return Vector of weights, with one weight for every feature in the candidate feature set.
*/
private static FVector computeCandidateFeatureWeights
(
final BaseFeatureSet candidateFeatureSet,
final BaseFeatureSet originalFeatureSet,
final LinearFunction oracleFunction,
final ExperienceBuffer experienceBuffer
)
{
final WeightVector oracleWeightVector = oracleFunction.effectiveParams();
final ExItExperience[] samples = experienceBuffer.allExperience();
final List<FeatureVector> allCandidateFeatureVectors = new ArrayList<FeatureVector>();
final TFloatArrayList allTargetLogits = new TFloatArrayList();
for (final ExItExperience sample : samples)
{
if (sample != null && sample.moves().size() > 1)
{
final FeatureVector[] featureVectors = sample.generateFeatureVectors(originalFeatureSet);
final FeatureVector[] candidateFeatureVectors = sample.generateFeatureVectors(candidateFeatureSet);
final float[] logits = new float[featureVectors.length];
for (int i = 0; i < featureVectors.length; ++i)
{
final FeatureVector featureVector = featureVectors[i];
logits[i] = oracleWeightVector.dot(featureVector);
}
final float maxLogit = ArrayUtils.max(logits);
final float minLogit = ArrayUtils.min(logits);
if (maxLogit == minLogit)
continue; // Nothing to learn from this, just skip it
// Maximise logits for winning moves and minimise for losing moves
for (int i = sample.winningMoves().nextSetBit(0); i >= 0; i = sample.winningMoves().nextSetBit(i + 1))
{
logits[i] = maxLogit;
}
for (int i = sample.losingMoves().nextSetBit(0); i >= 0; i = sample.losingMoves().nextSetBit(i + 1))
{
logits[i] = minLogit;
}
for (int i = 0; i < candidateFeatureVectors.length; ++i)
{
allCandidateFeatureVectors.add(candidateFeatureVectors[i]);
allTargetLogits.add(logits[i]);
}
}
}
final FVector candidateFeatureWeights = new FVector(candidateFeatureSet.getNumFeatures());
final IncrementalStats[] logitStatsPerFeatureWhenTrue = new IncrementalStats[candidateFeatureWeights.dim()];
final IncrementalStats[] logitStatsPerFeatureWhenFalse = new IncrementalStats[candidateFeatureWeights.dim()];
final IncrementalStats totalAvgLogit = new IncrementalStats();
for (int i = 0; i < logitStatsPerFeatureWhenTrue.length; ++i)
{
logitStatsPerFeatureWhenTrue[i] = new IncrementalStats();
logitStatsPerFeatureWhenFalse[i] = new IncrementalStats();
}
final int numAspatialFeatures = candidateFeatureSet.getNumAspatialFeatures();
final int numSpatialFeatures = candidateFeatureSet.getNumSpatialFeatures();
for (int i = 0; i < allCandidateFeatureVectors.size(); ++i)
{
final FeatureVector featureVector = allCandidateFeatureVectors.get(i);
final float targetLogit = allTargetLogits.getQuick(i);
totalAvgLogit.observe(targetLogit);
final FVector aspatialFeatureValues = featureVector.aspatialFeatureValues();
final TIntArrayList activeSpatialFeatureIndices = featureVector.activeSpatialFeatureIndices();
for (int j = 0; j < aspatialFeatureValues.dim(); ++j)
{
if (aspatialFeatureValues.get(j) != 0.f)
logitStatsPerFeatureWhenTrue[j].observe(targetLogit);
else
logitStatsPerFeatureWhenFalse[j].observe(targetLogit);
}
boolean[] spatialActive = new boolean[numSpatialFeatures];
for (int j = 0; j < activeSpatialFeatureIndices.size(); ++j)
{
final int fIdx = activeSpatialFeatureIndices.getQuick(j);
logitStatsPerFeatureWhenTrue[fIdx + numAspatialFeatures].observe(targetLogit);
spatialActive[fIdx] = true;
}
for (int j = 0; j < numSpatialFeatures; ++j)
{
if (!spatialActive[j])
logitStatsPerFeatureWhenFalse[j + numAspatialFeatures].observe(targetLogit);
}
}
for (int i = 0; i < candidateFeatureWeights.dim(); ++i)
{
candidateFeatureWeights.set(i, (float) (logitStatsPerFeatureWhenTrue[i].getMean() - totalAvgLogit.getMean()));
}
return candidateFeatureWeights;
}
//-------------------------------------------------------------------------
/**
* Collects all features under a given decision tree node
* @param node Root of (sub)tree from which to collect features
* @param outList List in which to place features
*/
private static void collectFeatures(final DecisionTreeNode node, final List<Feature> outList)
{
if (node instanceof DecisionConditionNode)
{
final DecisionConditionNode conditionNode = (DecisionConditionNode) node;
outList.add(conditionNode.feature());
collectFeatures(conditionNode.trueNode(), outList);
collectFeatures(conditionNode.falseNode(), outList);
}
}
//-------------------------------------------------------------------------
/**
* Loads feature sets and weights into the provided arrays
* @param game
* @param trainingOutDirPath
* @param outFeatureSets
* @param outLinearFunctionsPlayout
* @param outLinearFunctionsTSPG
* @return Did we successfully load files?
*/
private static boolean loadFeaturesAndWeights
(
final Game game,
final String trainingOutDirPath,
final BaseFeatureSet[] outFeatureSets,
final LinearFunction[] outLinearFunctionsPlayout,
final LinearFunction[] outLinearFunctionsTSPG
)
{
try
{
// First Playout policy
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String playoutPolicyFilepath =
ExperimentFileUtils.getLastFilepath
(
trainingOutDirPath + "PolicyWeightsPlayout_P" + p,
"txt"
);
if (playoutPolicyFilepath == null)
return false;
playoutSb.append(",policyweights" + p + "=" + playoutPolicyFilepath);
}
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
System.arraycopy(featureSets, 0, outFeatureSets, 0, featureSets.length);
System.arraycopy(linearFunctions, 0, outLinearFunctionsPlayout, 0, linearFunctions.length);
}
// Repeat the entire process again for TSPG
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String playoutPolicyFilepath =
ExperimentFileUtils.getLastFilepath
(
trainingOutDirPath + "PolicyWeightsTSPG_P" + p,
"txt"
);
if (playoutPolicyFilepath == null)
return false;
playoutSb.append(",policyweights" + p + "=" + playoutPolicyFilepath);
}
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
System.arraycopy(linearFunctions, 0, outLinearFunctionsTSPG, 0, linearFunctions.length);
return true;
}
}
catch (final Exception e)
{
e.printStackTrace(System.out);
return false;
}
}
/**
* Loads experience buffers into the provided array
* @param game
* @param trainingOutDirPath
* @param experienceBuffers
*/
private static void loadExperienceBuffers
(
final Game game,
final String trainingOutDirPath,
final ExperienceBuffer[] experienceBuffers
)
{
for (int p = 1; p < experienceBuffers.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
trainingOutDirPath +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
experienceBuffers[p] = buffer;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Identify top features for a game."
);
argParse.addOption(new ArgOption()
.withNames("--training-out-dir")
.help("Directory with training results (features, weights, experience buffers, ...).")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-dir")
.help("Directory in which to write our outputs.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--ruleset")
.help("Ruleset name.")
.withNumVals(1)
.withType(OptionTypes.String)
.withDefault(""));
// parse the args
if (!argParse.parseArguments(args))
return;
System.out.println("Identifying top features for args: " + Arrays.toString(args));
identifyTopFeatures(argParse);
}
//-------------------------------------------------------------------------
}
| 35,295 | 33.168441 | 149 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_sets/InstantiationTime.java
|
package supplementary.experiments.feature_sets;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import features.feature_sets.BaseFeatureSet;
import features.feature_sets.BaseFeatureSet.FeatureSetImplementations;
import features.feature_sets.network.JITSPatterNetFeatureSet;
import features.feature_sets.network.SPatterNetFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import gnu.trove.list.array.TLongArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.math.statistics.Stats;
import other.GameLoader;
import utils.ExperimentFileUtils;
/**
* Script to check SPatterNet instantiation time
*
* @author Dennis Soemers
*/
public class InstantiationTime
{
//-------------------------------------------------------------------------
/** Games we have featuresets for */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Kensington.lud",
"Knightthrough.lud",
"Konane.lud",
"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
//-------------------------------------------------------------------------
/**
* Eval the memory usage of feature sets
* @param parsedArgs
*/
private static void evalInitTimes(final CommandLineArgParse parsedArgs)
{
String trainingOutDir = parsedArgs.getValueString("--training-out-dir");
if (!trainingOutDir.endsWith("/"))
trainingOutDir += "/";
try (final PrintWriter writer = new UnixPrintWriter(new File(parsedArgs.getValueString("--out-file")), "UTF-8"))
{
// Write header
writer.println
(
StringRoutines.join
(
",",
"game",
"spatternet_mean_init",
"spatternet_std_init",
"spatternet_n_init",
"jit_mean_init",
"jit_std_init",
"jit_n_init"
)
);
for (final String gameName : GAMES)
{
System.out.println("Game: " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
final int numPlayers = game.players().count();
final String cleanGameName = StringRoutines.cleanGameName(gameName.replaceAll(Pattern.quote(".lud"), ""));
//final File gameTrainingDir = new File(trainingOutDir + cleanGameName + "/");
final String[] policyWeightFilepathsPerPlayer = new String[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
String policyWeightsFilepath = trainingOutDir + cleanGameName + "/PolicyWeightsCE_P" + p + "_00201.txt";
if (!new File(policyWeightsFilepath).exists())
{
final String parentDir = new File(policyWeightsFilepath).getParent();
// Replace with whatever is the latest file we have
if (policyWeightsFilepath.contains("Selection"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsSelection_P" + p, "txt");
}
else if (policyWeightsFilepath.contains("Playout"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsPlayout_P" + p, "txt");
}
else if (policyWeightsFilepath.contains("TSPG"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsTSPG_P" + p, "txt");
}
else if (policyWeightsFilepath.contains("PolicyWeightsCE"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsCE_P" + p, "txt");
}
else
{
policyWeightsFilepath = null;
}
}
if (policyWeightsFilepath == null)
System.err.println("Cannot resolve policy weights filepath: " + trainingOutDir + cleanGameName + "/PolicyWeightsCE_P" + p + "_00201.txt");
policyWeightFilepathsPerPlayer[p] = policyWeightsFilepath;
}
final LinearFunction[] linFuncs = new LinearFunction[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
linFuncs[p] = LinearFunction.fromFile(policyWeightFilepathsPerPlayer[p]);
}
final BaseFeatureSet[] featureSets = new BaseFeatureSet[numPlayers + 1];
final TLongArrayList startTimesSpatternet = new TLongArrayList();
final TLongArrayList endTimesSpatternet = new TLongArrayList();
final TLongArrayList startTimesJIT = new TLongArrayList();
final TLongArrayList endTimesJIT = new TLongArrayList();
for
(
final FeatureSetImplementations impl :
new FeatureSetImplementations[]
{
FeatureSetImplementations.SPATTERNET,
FeatureSetImplementations.JITSPATTERNET
}
)
{
//System.out.println("Implementation: " + impl);
for (int p = 1; p <= numPlayers; ++p)
{
final String parentDir = new File(policyWeightFilepathsPerPlayer[p]).getParent();
final String featureSetFilepath = parentDir + File.separator + linFuncs[p].featureSetFile();
if (impl == FeatureSetImplementations.SPATTERNET)
featureSets[p] = new SPatterNetFeatureSet(featureSetFilepath);
else if (impl == FeatureSetImplementations.JITSPATTERNET)
featureSets[p] = JITSPatterNetFeatureSet.construct(featureSetFilepath);
}
// Warming up
final long warmingUpStartTime = System.currentTimeMillis();
long timeSpent = 0L;
while (timeSpent < 30000L)
{
for (int p = 1; p <= numPlayers; ++p)
{
featureSets[p].gameRef().clear(); // Force reinit
featureSets[p].init(game, new int[] {p}, null);
timeSpent = System.currentTimeMillis() - warmingUpStartTime;
if (timeSpent >= 30000L)
break;
}
}
// Start actually measuring
final long timingStartTime = System.currentTimeMillis();
while (System.currentTimeMillis() - timingStartTime < 5 * 60 * 1000L) // 5 minutes
{
if (impl == FeatureSetImplementations.SPATTERNET)
{
startTimesSpatternet.add(System.currentTimeMillis());
for (int p = 1; p <= numPlayers; ++p)
{
featureSets[p].gameRef().clear(); // Force reinit
featureSets[p].init(game, new int[] {p}, null);
}
endTimesSpatternet.add(System.currentTimeMillis());
//System.out.println(endTimesSpatternet.getQuick(endTimesSpatternet.size() - 1) - startTimesSpatternet.getQuick(startTimesSpatternet.size() - 1));
}
else if (impl == FeatureSetImplementations.JITSPATTERNET)
{
startTimesJIT.add(System.currentTimeMillis());
for (int p = 1; p <= numPlayers; ++p)
{
featureSets[p].gameRef().clear(); // Force reinit
featureSets[p].init(game, new int[] {p}, null);
}
endTimesJIT.add(System.currentTimeMillis());
}
}
}
final Stats spatternetStats = new Stats();
for (int i = 0; i < startTimesSpatternet.size(); ++i)
{
spatternetStats.addSample(endTimesSpatternet.getQuick(i) - startTimesSpatternet.getQuick(i));
}
spatternetStats.measure();
final Stats jitStats = new Stats();
for (int i = 0; i < startTimesJIT.size(); ++i)
{
jitStats.addSample(endTimesJIT.getQuick(i) - startTimesJIT.getQuick(i));
}
jitStats.measure();
final List<String> stringsToWrite = new ArrayList<String>();
stringsToWrite.add(StringRoutines.quote(gameName));
stringsToWrite.add(String.valueOf(spatternetStats.mean()));
stringsToWrite.add(String.valueOf(spatternetStats.sd()));
stringsToWrite.add(String.valueOf(spatternetStats.n()));
stringsToWrite.add(String.valueOf(jitStats.mean()));
stringsToWrite.add(String.valueOf(jitStats.sd()));
stringsToWrite.add(String.valueOf(jitStats.n()));
writer.println(StringRoutines.join(",", stringsToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Eval init times of feature sets."
);
argParse.addOption(new ArgOption()
.withNames("--training-out-dir")
.help("Output directory for training results.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write our output CSV to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// Parse the args
if (!argParse.parseArguments(args))
return;
evalInitTimes(argParse);
}
}
| 9,534 | 29.659164 | 153 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_sets/MemoryUsage.java
|
package supplementary.experiments.feature_sets;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import features.feature_sets.BaseFeatureSet;
import features.feature_sets.BaseFeatureSet.FeatureSetImplementations;
import features.feature_sets.BaseFeatureSet.MoveFeaturesKey;
import features.feature_sets.BaseFeatureSet.ProactiveFeaturesKey;
import features.feature_sets.BaseFeatureSet.ReactiveFeaturesKey;
import features.feature_sets.network.JITSPatterNetFeatureSet;
import features.feature_sets.network.SPatterNet;
import features.feature_sets.network.SPatterNetFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.AI;
import other.GameLoader;
import other.context.Context;
import other.trial.Trial;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import search.mcts.MCTS.QInit;
import search.mcts.backpropagation.MonteCarloBackprop;
import search.mcts.finalmoveselection.RobustChild;
import search.mcts.selection.AG0Selection;
import utils.ExperimentFileUtils;
/**
* Script to check memory usage of different feature set implementations
*
* @author Dennis Soemers
*/
public class MemoryUsage
{
//-------------------------------------------------------------------------
/** Games we have featuresets for */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Kensington.lud",
"Knightthrough.lud",
"Konane.lud",
"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
//-------------------------------------------------------------------------
/**
* Eval the memory usage of feature sets
* @param parsedArgs
*/
private static void evalMemoryUsage(final CommandLineArgParse parsedArgs)
{
String trainingOutDir = parsedArgs.getValueString("--training-out-dir");
if (!trainingOutDir.endsWith("/"))
trainingOutDir += "/";
try (final PrintWriter writer = new UnixPrintWriter(new File(parsedArgs.getValueString("--out-file")), "UTF-8"))
{
// Write header
writer.println
(
StringRoutines.join
(
",",
"game",
"spatternet_num_keys_proactive",
"spatternet_num_keys_reactive",
"spatternet_num_props_proactive",
"spatternet_num_props_reactive",
"jit_num_keys_proactive",
"jit_num_keys_reactive",
"jit_num_props_proactive",
"jit_num_props_reactive",
"keys_ratio",
"keys_ratio_proactive",
"keys_ratio_reactive",
"props_ratio",
"props_ratio_proactive",
"props_ratio_reactive"
)
);
for (final String gameName : GAMES)
{
System.out.println("Game: " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
final int numPlayers = game.players().count();
final String cleanGameName = StringRoutines.cleanGameName(gameName.replaceAll(Pattern.quote(".lud"), ""));
//final File gameTrainingDir = new File(trainingOutDir + cleanGameName + "/");
final String[] policyWeightFilepathsPerPlayer = new String[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
String policyWeightsFilepath = trainingOutDir + cleanGameName + "/PolicyWeightsCE_P" + p + "_00201.txt";
if (!new File(policyWeightsFilepath).exists())
{
final String parentDir = new File(policyWeightsFilepath).getParent();
// Replace with whatever is the latest file we have
if (policyWeightsFilepath.contains("Selection"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsSelection_P" + p, "txt");
}
else if (policyWeightsFilepath.contains("Playout"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsPlayout_P" + p, "txt");
}
else if (policyWeightsFilepath.contains("TSPG"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsTSPG_P" + p, "txt");
}
else if (policyWeightsFilepath.contains("PolicyWeightsCE"))
{
policyWeightsFilepath =
ExperimentFileUtils.getLastFilepath(parentDir + "/PolicyWeightsCE_P" + p, "txt");
}
else
{
policyWeightsFilepath = null;
}
}
if (policyWeightsFilepath == null)
System.err.println("Cannot resolve policy weights filepath: " + trainingOutDir + cleanGameName + "/PolicyWeightsCE_P" + p + "_00201.txt");
policyWeightFilepathsPerPlayer[p] = policyWeightsFilepath;
}
final LinearFunction[] linFuncs = new LinearFunction[numPlayers + 1];
for (int p = 1; p <= numPlayers; ++p)
{
linFuncs[p] = LinearFunction.fromFile(policyWeightFilepathsPerPlayer[p]);
}
final BaseFeatureSet[] featureSets = new BaseFeatureSet[numPlayers + 1];
final Map<ReactiveFeaturesKey, SPatterNet> spatternetReactiveMap = new HashMap<ReactiveFeaturesKey, SPatterNet>();
final Map<ProactiveFeaturesKey, SPatterNet> spatternetProactiveMap = new HashMap<ProactiveFeaturesKey, SPatterNet>();
final Map<ReactiveFeaturesKey, SPatterNet> jitSpatternetReactiveMap = new HashMap<ReactiveFeaturesKey, SPatterNet>();
final Map<ProactiveFeaturesKey, SPatterNet> jitSpatternetProactiveMap = new HashMap<ProactiveFeaturesKey, SPatterNet>();
long spatternetNumPropsProactive = 0L;
long spatternetNumPropsReactive = 0L;
long jitNumPropsProactive = 0L;
long jitNumPropsReactive = 0L;
for
(
final FeatureSetImplementations impl :
new FeatureSetImplementations[]
{
FeatureSetImplementations.SPATTERNET,
FeatureSetImplementations.JITSPATTERNET
}
)
{
System.out.println("Implementation: " + impl);
for (int p = 1; p <= numPlayers; ++p)
{
final String parentDir = new File(policyWeightFilepathsPerPlayer[p]).getParent();
final String featureSetFilepath = parentDir + File.separator + linFuncs[p].featureSetFile();
if (impl == FeatureSetImplementations.SPATTERNET)
featureSets[p] = new SPatterNetFeatureSet(featureSetFilepath);
else if (impl == FeatureSetImplementations.JITSPATTERNET)
featureSets[p] = JITSPatterNetFeatureSet.construct(featureSetFilepath);
}
final SoftmaxPolicyLinear softmax = new SoftmaxPolicyLinear(linFuncs, featureSets);
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
for (int p = 1; p <= numPlayers; ++p)
{
final MCTS mcts =
new MCTS
(
new AG0Selection(),
softmax,
new MonteCarloBackprop(),
new RobustChild()
);
mcts.setLearnedSelectionPolicy(softmax);
mcts.setQInit(QInit.WIN);
ais.add(mcts);
}
// Play for 60 move ~= 60 seconds
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
boolean needStart = true;
for (int i = 0; i < 60; ++i)
{
if (needStart)
{
needStart = false;
game.start(context);
final long startTime = System.currentTimeMillis();
for (int p = 1; p <= numPlayers; ++p)
{
ais.get(p).initAI(game, p);
}
final long endTime = System.currentTimeMillis();
System.out.println("init for " + numPlayers + " players took " + ((endTime - startTime) / 1000.0) + " seconds.");
}
context.model().startNewStep(context, ais, 1.0);
if (trial.over())
needStart = true;
}
// Check memory usage
if (impl == FeatureSetImplementations.SPATTERNET)
{
for (int p = 1; p <= numPlayers; ++p)
{
System.out.println("p = " + p);
final SPatterNetFeatureSet featureSet = (SPatterNetFeatureSet) featureSets[p];
final HashMap<ReactiveFeaturesKey, SPatterNet> reactiveSPatterNets = featureSet.reactiveFeaturesThresholded();
final HashMap<ProactiveFeaturesKey, SPatterNet> proactiveSPatterNets = featureSet.proactiveFeaturesThresholded();
for (final Entry<ReactiveFeaturesKey, SPatterNet> reactiveEntry : reactiveSPatterNets.entrySet())
{
spatternetNumPropsReactive += reactiveEntry.getValue().numPropositions();
spatternetReactiveMap.put(reactiveEntry.getKey(), reactiveEntry.getValue());
}
for (final Entry<ProactiveFeaturesKey, SPatterNet> proactiveEntry : proactiveSPatterNets.entrySet())
{
spatternetNumPropsProactive += proactiveEntry.getValue().numPropositions();
spatternetProactiveMap.put(proactiveEntry.getKey(), proactiveEntry.getValue());
}
}
}
else if (impl == FeatureSetImplementations.JITSPATTERNET)
{
for (int p = 1; p <= numPlayers; ++p)
{
System.out.println("p = " + p);
final JITSPatterNetFeatureSet featureSet = (JITSPatterNetFeatureSet) featureSets[p];
final Map<MoveFeaturesKey, SPatterNet> spatterNets = featureSet.spatterNetMapThresholded();
for (final MoveFeaturesKey key : spatterNets.keySet())
{
if (key instanceof ReactiveFeaturesKey)
{
if (jitSpatternetReactiveMap.put((ReactiveFeaturesKey)key, spatterNets.get(key)) == null)
jitNumPropsReactive += spatterNets.get(key).numPropositions();
// if (spatternetReactiveMap.containsKey(key))
// {
// if (spatternetReactiveMap.get(key).numPropositions() != spatterNets.get(key).numPropositions())
// {
// System.out.println("normal has " + spatternetReactiveMap.get(key).numPropositions() + " props for " + key);
// System.out.println("JIT has " + spatterNets.get(key).numPropositions() + " props for " + key);
// }
// }
}
else
{
if (jitSpatternetProactiveMap.put((ProactiveFeaturesKey)key, spatterNets.get(key)) == null)
jitNumPropsProactive += spatterNets.get(key).numPropositions();
// if (!spatternetProactiveKeys.contains(key) && spatterNets.get(key).numPropositions() > 0)
// System.out.println("num props = " + spatterNets.get(key).numPropositions() + " for key: " + key);
// if (spatternetProactiveMap.containsKey(key))
// {
// if (spatternetProactiveMap.get(key).numPropositions() != spatterNets.get(key).numPropositions())
// {
// System.out.println("normal has " + spatternetProactiveMap.get(key).numPropositions() + " props for " + key);
// System.out.println("JIT has " + spatterNets.get(key).numPropositions() + " props for " + key);
// }
// }
}
}
for (final MoveFeaturesKey key : featureSet.spatterNetMap().keySet())
{
if (key instanceof ReactiveFeaturesKey)
{
if (jitSpatternetReactiveMap.put((ReactiveFeaturesKey)key, featureSet.spatterNetMap().get(key)) == null)
jitNumPropsReactive += featureSet.spatterNetMap().get(key).numPropositions();
// if (spatternetReactiveMap.containsKey(key))
// {
// if (spatternetReactiveMap.get(key).numPropositions() != featureSet.spatterNetMap().get(key).numPropositions())
// {
// System.out.println("normal has " + spatternetReactiveMap.get(key).numPropositions() + " props for " + key);
// System.out.println("JIT has " + featureSet.spatterNetMap().get(key).numPropositions() + " props for " + key);
// }
// }
}
else
{
if (jitSpatternetProactiveMap.put((ProactiveFeaturesKey)key, featureSet.spatterNetMap().get(key)) == null)
jitNumPropsProactive += featureSet.spatterNetMap().get(key).numPropositions();
// if (!spatternetProactiveKeys.contains(key) && featureSet.spatterNetMap().get(key).numPropositions() > 0)
// System.out.println("num props = " + featureSet.spatterNetMap().get(key).numPropositions() + " for key: " + key);
// if (spatternetProactiveMap.containsKey(key))
// {
// if (spatternetProactiveMap.get(key).numPropositions() != featureSet.spatterNetMap().get(key).numPropositions())
// {
// System.out.println("normal has " + spatternetProactiveMap.get(key).numPropositions() + " props for " + key);
// System.out.println("JIT has " + featureSet.spatterNetMap().get(key).numPropositions() + " props for " + key);
// }
// }
}
}
}
}
System.out.println();
}
// for (final ReactiveFeaturesKey key : jitSpatternetReactiveKeys)
// {
// if (!spatternetReactiveKeys.contains(key))
// System.out.println("JIT-only reactive key: " + key);
// }
//
// for (final ProactiveFeaturesKey key : jitSpatternetProactiveKeys)
// {
// if (!spatternetProactiveKeys.contains(key))
// System.out.println("JIT-only proactive key: " + key);
// }
System.out.println();
// StringRoutines.join
// (
// ",",
// "game",
// "spatternet_num_keys_proactive",
// "spatternet_num_keys_reactive",
// "spatternet_num_props_proactive",
// "spatternet_num_props_reactive",
// "jit_num_keys_proactive",
// "jit_num_keys_reactive",
// "jit_num_props_proactive",
// "jit_num_props_reactive",
// "keys_ratio",
// "keys_ratio_proactive",
// "keys_ratio_reactive"
// )
final List<String> stringsToWrite = new ArrayList<String>();
stringsToWrite.add(StringRoutines.quote(gameName));
stringsToWrite.add(String.valueOf(spatternetProactiveMap.size()));
stringsToWrite.add(String.valueOf(spatternetReactiveMap.size()));
stringsToWrite.add(String.valueOf(spatternetNumPropsProactive));
stringsToWrite.add(String.valueOf(spatternetNumPropsReactive));
stringsToWrite.add(String.valueOf(jitSpatternetProactiveMap.size()));
stringsToWrite.add(String.valueOf(jitSpatternetReactiveMap.size()));
stringsToWrite.add(String.valueOf(jitNumPropsProactive));
stringsToWrite.add(String.valueOf(jitNumPropsReactive));
stringsToWrite.add(String.valueOf(((double) spatternetProactiveMap.size() + spatternetReactiveMap.size()) / (jitSpatternetProactiveMap.size() + jitSpatternetReactiveMap.size())));
stringsToWrite.add(String.valueOf(((double) spatternetProactiveMap.size()) / (jitSpatternetProactiveMap.size())));
stringsToWrite.add(String.valueOf(((double) spatternetReactiveMap.size()) / (jitSpatternetReactiveMap.size())));
stringsToWrite.add(String.valueOf(((double) spatternetNumPropsProactive + spatternetNumPropsReactive) / (jitNumPropsProactive + jitNumPropsReactive)));
stringsToWrite.add(String.valueOf(((double) spatternetNumPropsProactive) / (jitNumPropsProactive)));
stringsToWrite.add(String.valueOf(((double) spatternetNumPropsReactive) / (jitNumPropsReactive)));
writer.println(StringRoutines.join(",", stringsToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Eval memory usage of feature sets."
);
argParse.addOption(new ArgOption()
.withNames("--training-out-dir")
.help("Output directory for training results.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write our output CSV to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// Parse the args
if (!argParse.parseArguments(args))
return;
evalMemoryUsage(argParse);
}
}
| 16,957 | 35.235043 | 183 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/GenerateExactFeatureTree.java
|
package supplementary.experiments.feature_trees;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import decision_trees.logits.ExactLogitTreeLearner;
import decision_trees.logits.LogitTreeNode;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.types.play.RoleType;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import metadata.ai.features.trees.logits.LogitNode;
import metadata.ai.features.trees.logits.LogitTree;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
/**
* Class to convert a trained feature set + weights into an exact logit
* tree (with exact meaning that it will be guaranteed to produce identical
* outputs for identical inputs).
*
* @author Dennis Soemers
*/
public class GenerateExactFeatureTree
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private GenerateExactFeatureTree()
{
// Do nothing
}
//-------------------------------------------------------------------------
/** Filepaths for trained feature weights */
protected List<String> featureWeightsFilepaths;
/** File to write tree metadata to */
protected File outFile;
/** If true, we expect Playout policy weight files to be boosted */
protected boolean boosted;
/** Type of tree to build */
protected String treeType;
//-------------------------------------------------------------------------
/**
* Do the work
*/
public void run()
{
// We'll first just use the command line args we got to build a Biased MCTS
// Then we'll extract the features from that one
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= featureWeightsFilepaths.size(); ++p)
{
playoutSb.append(",policyweights" + p + "=" + featureWeightsFilepaths.get(p - 1));
}
if (boosted)
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
final LogitTree[] metadataTrees = new LogitTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Generate logit tree for Player p
final LogitTreeNode root;
if (treeType.equals("Exact"))
root = ExactLogitTreeLearner.buildTree(featureSets[p], linearFunctions[p], 10);
else if (treeType.equals("NaiveMaxAbs"))
root = ExactLogitTreeLearner.buildTreeNaiveMaxAbs(featureSets[p], linearFunctions[p], 10);
else
root = null;
// Convert to metadata structure
final LogitNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new LogitTree(RoleType.roleForPlayerId(p), metadataRoot);
}
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(metadataTrees, null));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Write features to a file."
);
argParse.addOption(new ArgOption()
.withNames("--feature-weights-filepaths")
.help("Filepaths for trained feature weights.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--boosted")
.help("Indicates that the policy weight files are expected to be boosted.")
.withType(OptionTypes.Boolean));
argParse.addOption(new ArgOption()
.withNames("--tree-type")
.help("Type of tree to build.")
.withNumVals(1)
.withType(OptionTypes.String)
.withDefault("Exact")
.withLegalVals("Exact", "NaiveMaxAbs"));
// parse the args
if (!argParse.parseArguments(args))
return;
final GenerateExactFeatureTree task = new GenerateExactFeatureTree();
task.featureWeightsFilepaths = (List<String>) argParse.getValue("--feature-weights-filepaths");
task.outFile = new File(argParse.getValueString("--out-file"));
task.boosted = argParse.getValueBool("--boosted");
task.treeType = argParse.getValueString("--tree-type");
task.run();
}
//-------------------------------------------------------------------------
}
| 5,386 | 27.807487 | 97 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/TrainIQRDecisionTreeFromBuffer.java
|
package supplementary.experiments.feature_trees;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceIQRTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Class to train a decision tree from existing self-play data in an experience
* buffer. The goal is to predict whether actions are in the Interquartile Range
* (IQR) of logits / probabilities, below it, or above it.
*
*
* @author Dennis Soemers
*/
public class TrainIQRDecisionTreeFromBuffer
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainIQRDecisionTreeFromBuffer()
{
// Do nothing
}
//-------------------------------------------------------------------------
/** Filepaths for trained feature weights */
protected List<String> featureWeightsFilepaths;
/** Filepaths for buffers with self-play experience */
protected List<String> experienceBufferFilepaths;
/** File to write tree metadata to */
protected File outFile;
/** If true, we expect Playout policy weight files to be boosted */
protected boolean boosted;
/** Name of game for which we're building tree */
protected String gameName;
//-------------------------------------------------------------------------
/**
* Do the work
*/
public void run()
{
// We'll first just use the command line args we got to build a Biased MCTS
// Then we'll extract the features from that one
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= featureWeightsFilepaths.size(); ++p)
{
playoutSb.append(",policyweights" + p + "=" + featureWeightsFilepaths.get(p - 1));
}
if (boosted)
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
final Game game = GameLoader.loadGameFromName(gameName);
playoutSoftmax.initAI(game, -1);
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, experienceBufferFilepaths.get(p - 1));
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, experienceBufferFilepaths.get(p - 1));
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root = ExperienceIQRTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, 10, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Write features to a file."
);
argParse.addOption(new ArgOption()
.withNames("--feature-weights-filepaths")
.help("Filepaths for trained feature weights.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--experience-buffer-filepaths")
.help("Filepaths for experience buffers.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--boosted")
.help("Indicates that the policy weight files are expected to be boosted.")
.withType(OptionTypes.Boolean));
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of game.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
final TrainIQRDecisionTreeFromBuffer task = new TrainIQRDecisionTreeFromBuffer();
task.featureWeightsFilepaths = (List<String>) argParse.getValue("--feature-weights-filepaths");
task.experienceBufferFilepaths = (List<String>) argParse.getValue("--experience-buffer-filepaths");
task.outFile = new File(argParse.getValueString("--out-file"));
task.boosted = argParse.getValueBool("--boosted");
task.gameName = argParse.getValueString("--game");
task.run();
}
//-------------------------------------------------------------------------
}
| 6,532 | 29.24537 | 125 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/TrainLogitTreeFromBuffer.java
|
package supplementary.experiments.feature_trees;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import decision_trees.logits.ExperienceLogitTreeLearner;
import decision_trees.logits.LogitTreeNode;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import metadata.ai.features.trees.logits.LogitNode;
import metadata.ai.features.trees.logits.LogitTree;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Class to train a logit tree from existing self-play data in an experience
* buffer.
*
* @author Dennis Soemers
*/
public class TrainLogitTreeFromBuffer
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainLogitTreeFromBuffer()
{
// Do nothing
}
//-------------------------------------------------------------------------
/** Filepaths for trained feature weights */
protected List<String> featureWeightsFilepaths;
/** Filepaths for buffers with self-play experience */
protected List<String> experienceBufferFilepaths;
/** File to write tree metadata to */
protected File outFile;
/** If true, we expect Playout policy weight files to be boosted */
protected boolean boosted;
/** Name of game for which we're building tree */
protected String gameName;
//-------------------------------------------------------------------------
/**
* Do the work
*/
public void run()
{
// We'll first just use the command line args we got to build a Biased MCTS
// Then we'll extract the features from that one
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= featureWeightsFilepaths.size(); ++p)
{
playoutSb.append(",policyweights" + p + "=" + featureWeightsFilepaths.get(p - 1));
}
if (boosted)
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
final Game game = GameLoader.loadGameFromName(gameName);
playoutSoftmax.initAI(game, -1);
final LogitTree[] metadataTrees = new LogitTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, experienceBufferFilepaths.get(p - 1));
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, experienceBufferFilepaths.get(p - 1));
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate logit tree for Player p
final LogitTreeNode root = ExperienceLogitTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, 10, 5);
// Convert to metadata structure
final LogitNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new LogitTree(RoleType.roleForPlayerId(p), metadataRoot);
}
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(metadataTrees, null));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Write features to a file."
);
argParse.addOption(new ArgOption()
.withNames("--feature-weights-filepaths")
.help("Filepaths for trained feature weights.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--experience-buffer-filepaths")
.help("Filepaths for experience buffers.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--boosted")
.help("Indicates that the policy weight files are expected to be boosted.")
.withType(OptionTypes.Boolean));
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of game.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
final TrainLogitTreeFromBuffer task = new TrainLogitTreeFromBuffer();
task.featureWeightsFilepaths = (List<String>) argParse.getValue("--feature-weights-filepaths");
task.experienceBufferFilepaths = (List<String>) argParse.getValue("--experience-buffer-filepaths");
task.outFile = new File(argParse.getValueString("--out-file"));
task.boosted = argParse.getValueBool("--boosted");
task.gameName = argParse.getValueString("--game");
task.run();
}
//-------------------------------------------------------------------------
}
| 6,283 | 28.227907 | 118 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/normal_games/TrainBinaryClassificationDecisionTreesNormalGames.java
|
package supplementary.experiments.feature_trees.normal_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceBinaryClassificationTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our "normal" (not especially small) games.
*
* @author Dennis Soemers
*/
public class TrainBinaryClassificationDecisionTreesNormalGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainBinaryClassificationDecisionTreesNormalGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Apps/Ludii_Local_Experiments/TrainFeaturesSnellius4/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceBinaryClassificationTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName +
"/BinaryClassificationTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Binary Classification tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainBinaryClassificationDecisionTreesNormalGames task = new TrainBinaryClassificationDecisionTreesNormalGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,855 | 28.424893 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/normal_games/TrainIQRDecisionTreesNormalGames.java
|
package supplementary.experiments.feature_trees.normal_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceIQRTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our "normal" (not especially small) games.
*
* @author Dennis Soemers
*/
public class TrainIQRDecisionTreesNormalGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainIQRDecisionTreesNormalGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Apps/Ludii_Local_Experiments/TrainFeaturesSnellius4/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root = ExperienceIQRTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName +
"/IQRTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing IQR tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainIQRDecisionTreesNormalGames task = new TrainIQRDecisionTreesNormalGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,709 | 27.922414 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/normal_games/TrainImbalancedBinaryClassificationDecisionTrees2NormalGames.java
|
package supplementary.experiments.feature_trees.normal_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceImbalancedBinaryClassificationTree2Learner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our "normal" (not especially small) games.
*
* @author Dennis Soemers
*/
public class TrainImbalancedBinaryClassificationDecisionTrees2NormalGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainImbalancedBinaryClassificationDecisionTrees2NormalGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Apps/Ludii_Local_Experiments/TrainFeaturesSnellius4/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceImbalancedBinaryClassificationTree2Learner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName +
"/ImbalancedBinaryClassificationTree2_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Imbalanced Binary Classification (2) tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainImbalancedBinaryClassificationDecisionTrees2NormalGames task = new TrainImbalancedBinaryClassificationDecisionTrees2NormalGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,947 | 28.819742 | 143 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/normal_games/TrainImbalancedBinaryClassificationDecisionTreesNormalGames.java
|
package supplementary.experiments.feature_trees.normal_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceImbalancedBinaryClassificationTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our "normal" (not especially small) games.
*
* @author Dennis Soemers
*/
public class TrainImbalancedBinaryClassificationDecisionTreesNormalGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainImbalancedBinaryClassificationDecisionTreesNormalGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Apps/Ludii_Local_Experiments/TrainFeaturesSnellius4/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceImbalancedBinaryClassificationTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName +
"/ImbalancedBinaryClassificationTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Imbalanced Binary Classification tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainImbalancedBinaryClassificationDecisionTreesNormalGames task = new TrainImbalancedBinaryClassificationDecisionTreesNormalGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,936 | 28.772532 | 141 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/normal_games/TrainLogitTreesNormalGames.java
|
package supplementary.experiments.feature_trees.normal_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.logits.ExperienceLogitTreeLearner;
import decision_trees.logits.LogitTreeNode;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our "normal" (not especially small) games.
*
* @author Dennis Soemers
*/
public class TrainLogitTreesNormalGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainLogitTreesNormalGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Apps/Ludii_Local_Experiments/TrainFeaturesSnellius4/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.logits.LogitTree[] metadataTrees =
new metadata.ai.features.trees.logits.LogitTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final LogitTreeNode root =
ExperienceLogitTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.logits.LogitNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.logits.LogitTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName +
"/LogitRegressionTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Logit Regression tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(metadataTrees, null));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainLogitTreesNormalGames task = new TrainLogitTreesNormalGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,671 | 27.635193 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/normal_games/TrainUrgencyTreesNormalGames.java
|
package supplementary.experiments.feature_trees.normal_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceUrgencyTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our "normal" (not especially small) games.
*
* @author Dennis Soemers
*/
public class TrainUrgencyTreesNormalGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainUrgencyTreesNormalGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Apps/Ludii_Local_Experiments/TrainFeaturesSnellius4/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_Baseline/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceUrgencyTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 10);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName +
"/UrgencyTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Urgency tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainUrgencyTreesNormalGames task = new TrainUrgencyTreesNormalGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,719 | 27.841202 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/small_games/TrainBinaryDecisionTreesSmallGames.java
|
package supplementary.experiments.feature_trees.small_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceBinaryClassificationTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train binary classification feature trees for our small games.
*
* @author Dennis Soemers
*/
public class TrainBinaryDecisionTreesSmallGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainBinaryDecisionTreesSmallGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Downloads/results.tar/results/Out/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we ran */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(RULESETS[i]).replaceAll(Pattern.quote("/"), "_");
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceBinaryClassificationTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName + "_" + cleanRulesetName +
"/BinaryClassificationTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Binary Classification tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainBinaryDecisionTreesSmallGames task = new TrainBinaryDecisionTreesSmallGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,820 | 28.274678 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/small_games/TrainIQRDecisionTreesSmallGames.java
|
package supplementary.experiments.feature_trees.small_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceIQRTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train IQR feature trees for our small games.
*
* @author Dennis Soemers
*/
public class TrainIQRDecisionTreesSmallGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainIQRDecisionTreesSmallGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Downloads/results.tar/results/Out/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we ran */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(RULESETS[i]).replaceAll(Pattern.quote("/"), "_");
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root = ExperienceIQRTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName + "_" + cleanRulesetName + "/IQRTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing IQR tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainIQRDecisionTreesSmallGames task = new TrainIQRDecisionTreesSmallGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,704 | 28.025974 | 154 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/small_games/TrainImbalancedBinaryDecisionTrees2SmallGames.java
|
package supplementary.experiments.feature_trees.small_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceImbalancedBinaryClassificationTree2Learner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train imbalanced binary classification feature trees for our small games.
*
* @author Dennis Soemers
*/
public class TrainImbalancedBinaryDecisionTrees2SmallGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainImbalancedBinaryDecisionTrees2SmallGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Downloads/results.tar/results/Out/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we ran */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(RULESETS[i]).replaceAll(Pattern.quote("/"), "_");
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceImbalancedBinaryClassificationTree2Learner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName + "_" + cleanRulesetName +
"/ImbalancedBinaryClassificationTree2_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Imbalanced Binary Classification (2) tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainImbalancedBinaryDecisionTrees2SmallGames task = new TrainImbalancedBinaryDecisionTrees2SmallGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,923 | 28.716738 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/small_games/TrainImbalancedBinaryDecisionTreesSmallGames.java
|
package supplementary.experiments.feature_trees.small_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.classifiers.DecisionTreeNode;
import decision_trees.classifiers.ExperienceImbalancedBinaryClassificationTreeLearner;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train imbalanced binary classification feature trees for our small games.
*
* @author Dennis Soemers
*/
public class TrainImbalancedBinaryDecisionTreesSmallGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainImbalancedBinaryDecisionTreesSmallGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Downloads/results.tar/results/Out/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we ran */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(RULESETS[i]).replaceAll(Pattern.quote("/"), "_");
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.classifiers.DecisionTree[] metadataTrees =
new metadata.ai.features.trees.classifiers.DecisionTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final DecisionTreeNode root =
ExperienceImbalancedBinaryClassificationTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.classifiers.DecisionTreeNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.classifiers.DecisionTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName + "_" + cleanRulesetName +
"/ImbalancedBinaryClassificationTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Imbalanced Binary Classification tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(null, metadataTrees));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainImbalancedBinaryDecisionTreesSmallGames task = new TrainImbalancedBinaryDecisionTreesSmallGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,912 | 28.669528 | 128 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/feature_trees/small_games/TrainLogitTreesSmallGames.java
|
package supplementary.experiments.feature_trees.small_games;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import decision_trees.logits.ExperienceLogitTreeLearner;
import decision_trees.logits.LogitTreeNode;
import features.feature_sets.BaseFeatureSet;
import function_approx.LinearFunction;
import game.Game;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.features.trees.FeatureTrees;
import other.GameLoader;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.ExperimentFileUtils;
import utils.data_structures.experience_buffers.ExperienceBuffer;
import utils.data_structures.experience_buffers.PrioritizedReplayBuffer;
import utils.data_structures.experience_buffers.UniformExperienceBuffer;
/**
* Train logit regression feature trees for our small games.
*
* @author Dennis Soemers
*/
public class TrainLogitTreesSmallGames
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private TrainLogitTreesSmallGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
private static final String RESULTS_DIR = "D:/Downloads/results.tar/results/Out/";
/** Games we ran */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we ran */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] POLICY_WEIGHT_TYPES = new String[] {"Playout", "TSPG"};
private static final boolean[] BOOSTED = new boolean[] {false, true};
private static int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Do the work
*/
@SuppressWarnings("static-method")
public void run()
{
for (int i = 0; i < GAMES.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
final String cleanGameName = StringRoutines.cleanGameName(GAMES[i].replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(RULESETS[i]).replaceAll(Pattern.quote("/"), "_");
for (int j = 0; j < POLICY_WEIGHT_TYPES.length; ++j)
{
// Construct a string to load an MCTS guided by features, from that we can then easily extract the
// features again afterwards
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= game.players().count(); ++p)
{
final String policyFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/PolicyWeights" +
POLICY_WEIGHT_TYPES[j] + "_P" + p,
"txt"
);
playoutSb.append(",policyweights" + p + "=" + policyFilepath);
}
if (BOOSTED[j])
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=playout");
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
final BaseFeatureSet[] featureSets = playoutSoftmax.featureSets();
final LinearFunction[] linearFunctions = playoutSoftmax.linearFunctions();
playoutSoftmax.initAI(game, -1);
for (final int depth : TREE_DEPTHS)
{
final metadata.ai.features.trees.logits.LogitTree[] metadataTrees =
new metadata.ai.features.trees.logits.LogitTree[featureSets.length - 1];
for (int p = 1; p < featureSets.length; ++p)
{
// Load experience buffer for Player p
final String bufferFilepath =
ExperimentFileUtils.getLastFilepath
(
RESULTS_DIR + cleanGameName + "_" + cleanRulesetName + "/" +
"ExperienceBuffer_P" + p,
"buf"
);
ExperienceBuffer buffer = null;
try
{
buffer = PrioritizedReplayBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e)
{
if (buffer == null)
{
try
{
buffer = UniformExperienceBuffer.fromFile(game, bufferFilepath);
}
catch (final Exception e2)
{
e.printStackTrace();
e2.printStackTrace();
}
}
}
// Generate decision tree for Player p
final LogitTreeNode root =
ExperienceLogitTreeLearner.buildTree(featureSets[p], linearFunctions[p], buffer, depth, 5);
// Convert to metadata structure
final metadata.ai.features.trees.logits.LogitNode metadataRoot = root.toMetadataNode();
metadataTrees[p - 1] = new metadata.ai.features.trees.logits.LogitTree(RoleType.roleForPlayerId(p), metadataRoot);
}
final String outFile = RESULTS_DIR + "Trees/" + cleanGameName + "_" + cleanRulesetName +
"/LogitRegressionTree_" + POLICY_WEIGHT_TYPES[j] + "_" + depth + ".txt";
System.out.println("Writing Logit Regression tree to: " + outFile);
new File(outFile).getParentFile().mkdirs();
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(new FeatureTrees(metadataTrees, null));
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final TrainLogitTreesSmallGames task = new TrainLogitTreesSmallGames();
task.run();
}
//-------------------------------------------------------------------------
}
| 6,687 | 27.703863 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/CountGames.java
|
package supplementary.experiments.game_files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import main.FileHandling;
/**
* Simple "experiment" to count the number of games we have in every
* category. The following categories are excluded:
* - bad
* - bad_playout
* - wip
* - reconstruction
*
* @author Dennis Soemers
*/
public class CountGames
{
/** Num spaces per indentation level for printing */
private static final int NUM_INDENT_SPACES = 4;
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final String[] allGames = FileHandling.listGames();
final Category rootCategory = new Category("All Games");
int widestStringLength = 0;
for (String game : allGames)
{
game = game.replaceAll(Pattern.quote("\\"), "/");
final String[] gameParts = game.split(Pattern.quote("/"));
// categories which we've traversed so far
final List<Category> traversedCategories = new ArrayList<Category>();
// we start in the "All Games" category
Category currentCategory = rootCategory;
int currentIndentationLevel = 0;
traversedCategories.add(currentCategory);
for (int i = 2; i < gameParts.length; ++i)
{
final String part = gameParts[i];
if (part.endsWith(".lud"))
{
// we've found the game, increment counts for all traversed categories
for (final Category category : traversedCategories)
{
category.numGames += 1;
}
}
else if
(
part.equals("bad") ||
part.equals("bad_playout") ||
part.equals("wip") || part.equals("wishlist") || part.equals("WishlistDLP")
|| part.equals("pending") || part.equals("validation")
||
part.equals("test") || part.equals("subgame") || part.equals("proprietary")
)
{
// should skip this game
break;
}
else
{
// this is a subcategory, see if we already have it
Category subcategory = null;
for (final Category sub : currentCategory.subcategories)
{
if (sub.name.equals(part))
{
// found it
subcategory = sub;
break;
}
}
currentIndentationLevel += 1;
if (subcategory == null)
{
// need to create new subcategory
subcategory = new Category(part);
currentCategory.subcategories.add(subcategory);
widestStringLength =
Math.max
(
widestStringLength,
currentIndentationLevel * NUM_INDENT_SPACES + part.length()
);
}
traversedCategories.add(subcategory);
currentCategory = subcategory;
}
}
}
// start printing
for (int i = 0; i < widestStringLength + Math.min(4, NUM_INDENT_SPACES) + 4; ++i)
{
System.out.print("=");
}
System.out.println();
System.out.println("Number of .lud files per category:");
System.out.println("");
printCategory(rootCategory, 0, widestStringLength);
for (int i = 0; i < widestStringLength + Math.min(4, NUM_INDENT_SPACES) + 4; ++i)
{
System.out.print("=");
}
System.out.println();
}
/**
* Helper method to print a categories recursively
*
* @param category
* @param indentation
* @param widestStringLength
* @return Number of games in this category
*/
private static int printCategory(final Category category, final int indentation, final int widestStringLength)
{
// indent before category name
for (int i = 0; i < indentation; ++i)
{
for (int j = 0; j < NUM_INDENT_SPACES; ++j)
{
System.out.print(" ");
}
}
// print category name
System.out.print(category.name + ":");
// append extra indentation to accommodate widest category string
final int numCharactersPrinted = indentation * NUM_INDENT_SPACES + category.name.length() + 1;
final int numCharactersWanted = widestStringLength + Math.min(4, NUM_INDENT_SPACES);
for (int i = 0; i < (numCharactersWanted - numCharactersPrinted); ++i)
{
System.out.print(" ");
}
// finally print the count
System.out.print(String.format("%4s", Integer.valueOf(category.numGames)));
// complete the line
System.out.println();
// print subcategories
int accum = 0;
for (final Category subcategory : category.subcategories)
{
accum += printCategory(subcategory, indentation + 1, widestStringLength);
}
if (accum < category.numGames && category.subcategories.size() > 0)
{
final int numOther = category.numGames - accum;
final Category fakeCategory = new Category("other");
fakeCategory.numGames = numOther;
printCategory(fakeCategory, indentation + 1, widestStringLength);
}
return category.numGames;
}
/**
* Helper class for a category of games
*
* @author Dennis Soemers
*/
private static class Category
{
/** Category name */
protected final String name;
/** Number of games in this category (and subcategories) */
protected int numGames = 0;
/** List of subcategories */
protected List<Category> subcategories = new ArrayList<Category>();
/**
* Constructor
* @param name
*/
public Category(final String name)
{
this.name = name;
}
}
}
| 5,207 | 23.682464 | 111 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/CountReconstruction.java
|
package supplementary.experiments.game_files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import main.FileHandling;
/**
* Simple "experiment" to count the number of reconstruction we have in every
* category.
*
* @author Eric Piette
*/
public class CountReconstruction
{
/** Num spaces per indentation level for printing */
private static final int NUM_INDENT_SPACES = 4;
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final String[] allGames = FileHandling.listGames();
final Category rootCategory = new Category("All Games to reconstruct");
int widestStringLength = 0;
for (String game : allGames)
{
if(!game.contains("pending"))
continue;
game = game.replaceAll(Pattern.quote("\\"), "/");
final String[] gameParts = game.split(Pattern.quote("/"));
// categories which we've traversed so far
final List<Category> traversedCategories = new ArrayList<Category>();
// we start in the "All Games" category
Category currentCategory = rootCategory;
int currentIndentationLevel = 0;
traversedCategories.add(currentCategory);
for (int i = 2; i < gameParts.length; ++i)
{
final String part = gameParts[i];
if (part.endsWith(".lud"))
{
// we've found the game, increment counts for all traversed categories
for (final Category category : traversedCategories)
{
category.numGames += 1;
}
}
else if
(
part.equals("bad") ||
part.equals("bad_playout") ||
part.equals("wip") || part.equals("wishlist") || part.equals("WishlistDLP")
||
part.equals("test") || part.equals("subgame") || part.equals("proprietary")
)
{
// should skip this game
break;
}
else
{
// this is a subcategory, see if we already have it
Category subcategory = null;
for (final Category sub : currentCategory.subcategories)
{
if (sub.name.equals(part))
{
// found it
subcategory = sub;
break;
}
}
currentIndentationLevel += 1;
if (subcategory == null)
{
// need to create new subcategory
subcategory = new Category(part);
currentCategory.subcategories.add(subcategory);
widestStringLength =
Math.max
(
widestStringLength,
currentIndentationLevel * NUM_INDENT_SPACES + part.length()
);
}
traversedCategories.add(subcategory);
currentCategory = subcategory;
}
}
}
// start printing
for (int i = 0; i < widestStringLength + Math.min(4, NUM_INDENT_SPACES) + 4; ++i)
{
System.out.print("=");
}
System.out.println();
System.out.println("Number of .lud files per category:");
System.out.println("");
printCategory(rootCategory, 0, widestStringLength);
for (int i = 0; i < widestStringLength + Math.min(4, NUM_INDENT_SPACES) + 4; ++i)
{
System.out.print("=");
}
System.out.println();
}
/**
* Helper method to print a categories recursively
*
* @param category
* @param indentation
* @param widestStringLength
* @return Number of games in this category
*/
private static int printCategory(final Category category, final int indentation, final int widestStringLength)
{
// indent before category name
for (int i = 0; i < indentation; ++i)
{
for (int j = 0; j < NUM_INDENT_SPACES; ++j)
{
System.out.print(" ");
}
}
// print category name
System.out.print(category.name + ":");
// append extra indentation to accommodate widest category string
final int numCharactersPrinted = indentation * NUM_INDENT_SPACES + category.name.length() + 1;
final int numCharactersWanted = widestStringLength + Math.min(4, NUM_INDENT_SPACES);
for (int i = 0; i < (numCharactersWanted - numCharactersPrinted); ++i)
{
System.out.print(" ");
}
// finally print the count
System.out.print(String.format("%4s", Integer.valueOf(category.numGames)));
// complete the line
System.out.println();
// print subcategories
int accum = 0;
for (final Category subcategory : category.subcategories)
{
accum += printCategory(subcategory, indentation + 1, widestStringLength);
}
if (accum < category.numGames && category.subcategories.size() > 0)
{
final int numOther = category.numGames - accum;
final Category fakeCategory = new Category("other");
fakeCategory.numGames = numOther;
printCategory(fakeCategory, indentation + 1, widestStringLength);
}
return category.numGames;
}
/**
* Helper class for a category of games
*
* @author Dennis Soemers
*/
private static class Category
{
/** Category name */
protected final String name;
/** Number of games in this category (and subcategories) */
protected int numGames = 0;
/** List of subcategories */
protected List<Category> subcategories = new ArrayList<Category>();
/**
* Constructor
* @param name
*/
public Category(final String name)
{
this.name = name;
}
}
}
| 5,133 | 23.564593 | 111 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/LoopThroughGames.java
|
package supplementary.experiments.game_files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import features.spatial.Walk;
import game.Game;
import main.FileHandling;
import main.options.Ruleset;
import other.GameLoader;
/**
* A little helper class with a main method to loop through
* all games and do something with them (usually print some
* information about certain games, can change this whenever
* I want to do something new).
*
* @author Dennis Soemers
*/
public class LoopThroughGames
{
public static void main(final String[] args)
{
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
for (final String gameName : allGameNames)
{
//final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
//final String shortGameName = gameNameSplit[gameNameSplit.length - 1];
boolean skipGame = false;
// for (final String game : SKIP_GAMES)
// {
// if (shortGameName.endsWith(game))
// {
// skipGame = true;
// break;
// }
// }
if (skipGame)
continue;
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName);
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName, fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.hasSubgames())
continue;
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.isStacking())
continue;
if (game.isBoardless())
continue;
if (Walk.allGameRotations(game).length <= 1)
{
System.out.println("Rotations for " + gameName + " (" + fullRulesetName + ") = " + Arrays.toString(Walk.allGameRotations(game)));
}
}
}
}
}
| 3,223 | 27.530973 | 134 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/TestFormatLudFile.java
|
package supplementary.experiments.game_files;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import main.FileHandling;
import main.grammar.Report;
/**
* Script to write a formatted version of a .lud file's contents to
* "Ludii/Player/FormattedLud.lud" (this file is ignored by git!)
*
* @author Dennis Soemers
*/
public class TestFormatLudFile
{
/** Path of the .lud file we want to test formatting for */
private static final String LUD_PATH = "/lud/board/space/blocking/Mu Torere.lud";
/** Path we write to */
private static final String WRITE_PATH = "FormattedLud.lud";
//-------------------------------------------------------------------------
/**
* Constructor
*/
private TestFormatLudFile()
{
// Should not construct
}
//-------------------------------------------------------------------------
/**
* Main method
*
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
final String fileContents = FileHandling.loadTextContentsFromFile("../Common/res" + LUD_PATH);
final String formatted = new main.grammar.Token(fileContents, new Report()).toString();
try (final PrintWriter writer = new PrintWriter(new FileWriter(WRITE_PATH)))
{
writer.print(formatted);
}
}
//-------------------------------------------------------------------------
}
| 1,500 | 24.87931 | 96 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/UpdateAIMetadata.java
|
package supplementary.experiments.game_files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import features.feature_sets.BaseFeatureSet;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.grammar.Report;
import main.options.Ruleset;
import metadata.ai.agents.BestAgent;
import metadata.ai.features.Features;
import metadata.ai.heuristics.Heuristics;
import other.GameLoader;
import search.minimax.AlphaBetaSearch;
/**
* Script to update all our AI metadata defines based on a directory
* of best agents data.
*
* @author Dennis Soemers
*/
public class UpdateAIMetadata
{
/**
* Constructor
*/
private UpdateAIMetadata()
{
// Should not construct
}
//-------------------------------------------------------------------------
/**
* Updates our AI metadata
* @param argParse
*/
private static void updateMetadata(final CommandLineArgParse argParse)
{
String bestAgentsDataDirPath = argParse.getValueString("--best-agents-data-dir");
bestAgentsDataDirPath = bestAgentsDataDirPath.replaceAll(Pattern.quote("\\"), "/");
if (!bestAgentsDataDirPath.endsWith("/"))
bestAgentsDataDirPath += "/";
final File bestAgentsDataDir = new File(bestAgentsDataDirPath);
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter
(
s ->
(
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)
).toArray(String[]::new);
// Loop through all the games we have
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
final List<File> bestAgentDataDirsForGame = new ArrayList<File>(); // one per ruleset
final List<Ruleset> rulesets = new ArrayList<Ruleset>();
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
if (game.isStacking())
continue;
if (game.hiddenInformation())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File bestAgentsDataDirForRuleset =
new File(bestAgentsDataDir.getAbsolutePath() + "/" + filepathsGameName + filepathsRulesetName);
if
(
bestAgentsDataDirForRuleset.exists()
&&
bestAgentsDataDirForRuleset.isDirectory()
&&
bestAgentsDataDirForRuleset.list().length > 0
)
{
bestAgentDataDirsForGame.add(bestAgentsDataDirForRuleset);
rulesets.add(ruleset);
}
}
if (!rulesets.isEmpty())
{
updateMetadata(bestAgentDataDirsForGame, gameName, rulesets, fullGamePath, argParse);
}
}
}
//-------------------------------------------------------------------------
/**
* Update metadata based on array of directories for game (sometimes one
* for game as a whole, sometimes one per set of options)
*
* @param gameDirs
* @param gameName
* @param allGameNames
* @param fullGamePath
* @param argParse
*/
private static void updateMetadata
(
final List<File> gameDirs,
final String gameName,
final List<Ruleset> rulesets,
final String fullGamePath,
final CommandLineArgParse argParse
)
{
final List<String> stringsToWrite = new ArrayList<String>();
boolean addedAIContents = false;
final Game defaultGame = GameLoader.loadGameFromName(gameName + ".lud");
// Now process every ruleset
for (int i = 0; i < rulesets.size(); ++i)
{
final Ruleset ruleset = rulesets.get(i);
final List<String> usedOptions = new ArrayList<String>();
if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
usedOptions.addAll(ruleset.optionSettings());
}
final File bestAgentsFile = new File(gameDirs.get(i).getAbsolutePath() + "/BestAgent.txt");
final File bestFeaturesFile = new File(gameDirs.get(i).getAbsolutePath() + "/BestFeatures.txt");
final File bestHeuristicsFile = new File(gameDirs.get(i).getAbsolutePath() + "/BestHeuristics.txt");
try
{
if (!usedOptions.isEmpty())
{
final StringBuilder sb = new StringBuilder();
sb.append("(useFor {");
for (final String opt : usedOptions)
{
sb.append(" " + StringRoutines.quote(opt));
}
sb.append(" }");
stringsToWrite.add(sb.toString());
}
if (bestAgentsFile.exists())
{
BestAgent bestAgent = (BestAgent)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestAgentsFile.getAbsolutePath()),
"metadata.ai.agents.BestAgent",
new Report()
);
if (bestAgent.agent().equals("AlphaBetaMetadata"))
bestAgent = new BestAgent("Alpha-Beta");
stringsToWrite.add(bestAgent.toString());
addedAIContents = true;
}
else
{
System.err.println("No best agents data found at: " + bestAgentsFile.getAbsolutePath());
continue;
}
if (bestHeuristicsFile.exists())
{
final Heuristics heuristics = (Heuristics)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestHeuristicsFile.getAbsolutePath()),
"metadata.ai.heuristics.Heuristics",
new Report()
);
final String thresholdedString = heuristics.toStringThresholded(AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD);
// Make sure heuristics are not empty after thresholding, possible due to null heuristic
if (!thresholdedString.replaceAll(Pattern.quote("\n"), "").equals("(heuristics {})"))
{
stringsToWrite.add(thresholdedString);
addedAIContents = true;
}
}
if (bestFeaturesFile.exists())
{
final Features features = (Features)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestFeaturesFile.getAbsolutePath()),
"metadata.ai.features.Features",
new Report()
);
stringsToWrite.add(features.toStringThresholded(BaseFeatureSet.SPATIAL_FEATURE_WEIGHT_THRESHOLD));
addedAIContents = true;
}
if (!usedOptions.isEmpty())
{
stringsToWrite.add(")");
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
if (addedAIContents)
{
// Find the AI metadata def file
final File aiDefFile = new File(argParse.getValueString("--ai-defs-dir") + "/" + gameName + "_ai.def");
try (final PrintWriter writer = new PrintWriter(aiDefFile, "UTF-8"))
{
System.out.println("Writing to file: " + aiDefFile.getAbsolutePath());
writer.println("(define " + StringRoutines.quote(gameName + "_ai"));
for (final String toWrite : stringsToWrite)
{
writer.println(toWrite);
}
writer.println(")");
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
// Find the .lud file
final File ludFile = new File(argParse.getValueString("--luds-dir") + fullGamePath);
try
{
final String ludFileContents = FileHandling.loadTextContentsFromFile(ludFile.getAbsolutePath());
final String defStr = StringRoutines.quote(gameName + "_ai");
if (defaultGame.metadata().ai().agent() == null)
{
if (!StringRoutines.cleanWhitespace(ludFileContents.replaceAll(Pattern.quote("\n"), "")).contains(defStr))
{
// We need to write the AI metadata
final StringBuffer sb = new StringBuffer(ludFileContents);
final int startMetadataIdx = sb.indexOf("(metadata");
final int endMetadataIdx = StringRoutines.matchingBracketAt(ludFileContents, startMetadataIdx);
sb.insert(endMetadataIdx, " (ai\n " + defStr + "\n )\n");
try (final PrintWriter writer = new PrintWriter(ludFile, "UTF-8"))
{
System.out.println("Updating .lud file: " + ludFile.getAbsolutePath());
writer.print(sb.toString());
}
}
}
else if (!StringRoutines.cleanWhitespace(ludFileContents.replaceAll(Pattern.quote("\n"), "")).contains(defStr))
{
System.err.println("AI Metadata not null, but did not find the AI def: " + defStr);
System.err.println(" looked at file: " + ludFile.getAbsolutePath());
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Main method to update all our metadata
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Updates all our AI metadata to include the new best agents, features, and heuristics."
);
argParse.addOption(new ArgOption()
.withNames("--best-agents-data-dir")
.help("Directory containing our best agents data.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--ai-defs-dir")
.help("Directory containing AI metadata .def files.")
.withNumVals(1)
.withType(OptionTypes.String)
.withDefault("../Common/res/def_ai"));
argParse.addOption(new ArgOption()
.withNames("--luds-dir")
.help("Directory that contains the /lud/** directory.")
.withNumVals(1)
.withType(OptionTypes.String)
.withDefault("../Common/res"));
// parse the args
if (!argParse.parseArguments(args))
return;
updateMetadata(argParse);
}
//-------------------------------------------------------------------------
}
| 11,642 | 29.479058 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/UpdateAIMetadataTopFeatures.java
|
package supplementary.experiments.game_files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import features.spatial.Walk;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.grammar.Report;
import main.options.Ruleset;
import metadata.ai.Ai;
import metadata.ai.features.Features;
import other.GameLoader;
/**
* Main method to update AI Metadata with identified top features.
*
* @author Dennis Soemers
*/
public class UpdateAIMetadataTopFeatures
{
//-------------------------------------------------------------------------
/**
* Games we should skip since they never end anyway (in practice), but do
* take a long time.
*/
private static final String[] SKIP_GAMES = new String[]
{
"Chinese Checkers.lud",
"Li'b al-'Aqil.lud",
"Li'b al-Ghashim.lud",
"Mini Wars.lud",
"Pagade Kayi Ata (Sixteen-handed).lud",
"Taikyoku Shogi.lud"
};
//-------------------------------------------------------------------------
/**
* Updates our AI metadata
* @param argParse
*/
private static void updateMetadata(final CommandLineArgParse argParse)
{
String topFeaturesOutDirPath = argParse.getValueString("--top-features-out-dir");
topFeaturesOutDirPath = topFeaturesOutDirPath.replaceAll(Pattern.quote("\\"), "/");
if (!topFeaturesOutDirPath.endsWith("/"))
topFeaturesOutDirPath += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
for (final String gameName : allGameNames)
{
final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String shortGameName = gameNameSplit[gameNameSplit.length - 1];
boolean skipGame = false;
for (final String game : SKIP_GAMES)
{
if (shortGameName.endsWith(game))
{
skipGame = true;
break;
}
}
if (skipGame)
continue;
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName);
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
final String thisGameName = "/" + shortGameName;
// This will collect the strings we want to write for all rulesets of this game
final List<String> stringsToWrite = new ArrayList<String>();
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName, fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.hasSubgames())
continue;
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.isStacking())
continue;
if (game.isBoardless())
continue;
if (game.hiddenInformation())
continue;
if (Walk.allGameRotations(game).length == 0)
continue;
if (game.players().count() == 0)
continue;
if (game.isSimultaneousMoveGame())
continue;
final String thisRulesetName = fullRulesetName;
// Figure out whether we have features for this ruleset
final String cleanGameName = StringRoutines.cleanGameName(thisGameName.replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(thisRulesetName).replaceAll(Pattern.quote("/"), "_");
final String rulesetFeaturesOutDirPath = topFeaturesOutDirPath + cleanGameName + "_" + cleanRulesetName;
final File rulesetFeaturesOutDir = new File(rulesetFeaturesOutDirPath);
if (!rulesetFeaturesOutDir.exists() || !rulesetFeaturesOutDir.isDirectory())
continue; // No features for this ruleset, move on
final File bestFeaturesFile = new File(rulesetFeaturesOutDirPath + "/BestFeatures.txt");
if (!bestFeaturesFile.exists())
continue; // No features for this ruleset, move on
// Generate the strings we want to write for features metadata
if (!cleanRulesetName.isEmpty())
{
stringsToWrite.add("(useFor { " + StringRoutines.quote(thisRulesetName) + " }");
}
// Get the current metadata out of game, if any exists
Ai aiMetadata = game.metadata().ai();
if (aiMetadata == null)
aiMetadata = new Ai(null, null, null, null, null, null);
try
{
// Load the features we've identified and put them in metadata
final Features features = (Features)compiler.Compiler.compileObject
(
FileHandling.loadTextContentsFromFile(bestFeaturesFile.getAbsolutePath()),
"metadata.ai.features.Features",
new Report()
);
aiMetadata.setTrainedFeatures(features);
}
catch (final IOException e)
{
e.printStackTrace();
}
// write AI metadata string, minus the "(ai" prefix and ")" suffix
final StringBuilder aiMetadataString = new StringBuilder(aiMetadata.toString());
final int aiPrefixIdx = aiMetadataString.indexOf("(ai");
final int aiSuffixIdx = StringRoutines.matchingBracketAt(aiMetadataString.toString(), aiPrefixIdx);
aiMetadataString.replace(aiSuffixIdx, aiSuffixIdx + 1, "");
aiMetadataString.replace(aiPrefixIdx, aiPrefixIdx + "(ai".length(), "");
stringsToWrite.add(aiMetadataString.toString());
// Close the (useFor ...) block if we have one
if (!cleanRulesetName.isEmpty())
{
stringsToWrite.add(")");
}
}
// We have something to write for this game
if (!stringsToWrite.isEmpty())
{
// Write our AI def file
final File aiDefFile = new File(argParse.getValueString("--ai-defs-dir") + "/" + thisGameName.replaceAll(Pattern.quote(".lud"), "") + "_ai.def");
try (final PrintWriter writer = new PrintWriter(aiDefFile, "UTF-8"))
{
System.out.println("Writing to file: " + aiDefFile.getAbsolutePath());
writer.println("(define " + StringRoutines.quote((thisGameName.replaceAll(Pattern.quote(".lud"), "") + "_ai").substring(1)));
for (final String toWrite : stringsToWrite)
{
writer.println(toWrite);
}
writer.println(")");
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
// Also update the .lud file to make sure it points to our AI def file
final File ludFile = new File(argParse.getValueString("--luds-dir") + gameName, "");
try
{
final String ludFileContents = FileHandling.loadTextContentsFromFile(ludFile.getAbsolutePath());
final String defStr = StringRoutines.quote((thisGameName.replaceAll(Pattern.quote(".lud"), "") + "_ai").substring(1));
final int startMetadataIdx = ludFileContents.indexOf("(metadata");
final int endMetadataIdx = StringRoutines.matchingBracketAt(ludFileContents, startMetadataIdx);
final int startAiMetadataIdx = ludFileContents.indexOf("(ai", startMetadataIdx);
final int endAiMetadataIdx;
if (startAiMetadataIdx >= 0)
endAiMetadataIdx = StringRoutines.matchingBracketAt(ludFileContents, startAiMetadataIdx);
else
endAiMetadataIdx = -1;
if (startAiMetadataIdx < 0)
{
if (!StringRoutines.cleanWhitespace(ludFileContents.replaceAll(Pattern.quote("\n"), "")).contains(defStr))
{
// We need to write the AI metadata
final StringBuffer sb = new StringBuffer(ludFileContents);
sb.insert(endMetadataIdx, " (ai\n " + defStr + "\n )\n");
try (final PrintWriter writer = new PrintWriter(ludFile, "UTF-8"))
{
System.out.println("Updating .lud file: " + ludFile.getAbsolutePath());
writer.print(sb.toString());
}
}
}
else if (!StringRoutines.cleanWhitespace(ludFileContents.replaceAll(Pattern.quote("\n"), "")).contains(defStr))
{
// Print warnings
System.err.println("AI Metadata not null, but did not find the AI def: " + defStr);
System.err.println(" looked at file: " + ludFile.getAbsolutePath());
// Replace the (ai ...) metadata part from .lud file with reference to AI def
final StringBuffer sb = new StringBuffer(ludFileContents);
sb.replace(startAiMetadataIdx, endAiMetadataIdx + 1, " (ai\n " + defStr + "\n )\n");
try (final PrintWriter writer = new PrintWriter(ludFile, "UTF-8"))
{
System.out.println("Updating .lud file: " + ludFile.getAbsolutePath());
writer.print(sb.toString());
}
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method to update all our metadata
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Updates all our AI metadata to include identified top features."
);
argParse.addOption(new ArgOption()
.withNames("--top-features-out-dir")
.help("Output directory with identified top features.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--ai-defs-dir")
.help("Directory containing AI metadata .def files.")
.withNumVals(1)
.withType(OptionTypes.String)
.withDefault("../Common/res/def_ai"));
argParse.addOption(new ArgOption()
.withNames("--luds-dir")
.help("Directory that contains the /lud/** directory.")
.withNumVals(1)
.withType(OptionTypes.String)
.withDefault("../Common/res"));
// parse the args
if (!argParse.parseArguments(args))
return;
updateMetadata(argParse);
}
//-------------------------------------------------------------------------
}
| 11,358 | 31.82948 | 149 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/game_files/WriteFeaturesMetadata.java
|
package supplementary.experiments.game_files;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import metadata.ai.features.Features;
import policies.softmax.SoftmaxPolicyLinear;
import search.mcts.MCTS;
import utils.AIFactory;
import utils.AIUtils;
/**
* Class to write a set of features and weights to a file
*
* @author Dennis Soemers
*/
public class WriteFeaturesMetadata
{
//-------------------------------------------------------------------------
/**
* Private constructor
*/
private WriteFeaturesMetadata()
{
// Do nothing
}
//-------------------------------------------------------------------------
/** Filepaths for Selection feature weights to write */
protected List<String> featureWeightsFilepathsSelection;
/** Filepaths for Playout feature weights to write */
protected List<String> featureWeightsFilepathsPlayout;
/** File to write features metadata to */
protected File outFile;
/** If true, we expect Playout policy weight files to be boosted */
protected boolean boosted;
//-------------------------------------------------------------------------
/**
* Do the work
*/
public void run()
{
// We'll first just use the command line args we got to build a Biased MCTS
// Then we'll extract the features from that one
final StringBuilder playoutSb = new StringBuilder();
playoutSb.append("playout=softmax");
for (int p = 1; p <= featureWeightsFilepathsPlayout.size(); ++p)
{
playoutSb.append(",policyweights" + p + "=" + featureWeightsFilepathsPlayout.get(p - 1));
}
if (boosted)
playoutSb.append(",boosted=true");
final StringBuilder selectionSb = new StringBuilder();
selectionSb.append("learned_selection_policy=softmax");
for (int p = 1; p <= featureWeightsFilepathsSelection.size(); ++p)
{
selectionSb.append(",policyweights" + p + "=" + featureWeightsFilepathsSelection.get(p - 1));
}
final String agentStr = StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
playoutSb.toString(),
"final_move=robustchild",
"tree_reuse=true",
selectionSb.toString(),
"friendly_name=BiasedMCTS"
);
final MCTS mcts = (MCTS) AIFactory.createAI(agentStr);
final SoftmaxPolicyLinear selectionSoftmax = (SoftmaxPolicyLinear) mcts.learnedSelectionPolicy();
final SoftmaxPolicyLinear playoutSoftmax = (SoftmaxPolicyLinear) mcts.playoutStrategy();
// Generate our features metadata and write it
final Features features = AIUtils.generateFeaturesMetadata(selectionSoftmax, playoutSoftmax);
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.println(features.toString());
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Write features to a file."
);
argParse.addOption(new ArgOption()
.withNames("--selection-feature-weights-filepaths")
.help("Filepaths for feature weights for Selection.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--playout-feature-weights-filepaths")
.help("Filepaths for feature weights for Selection.")
.withNumVals("+")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--out-file")
.help("Filepath to write to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--boosted")
.help("Indicates that the policy weight files are expected to be boosted.")
.withType(OptionTypes.Boolean));
// parse the args
if (!argParse.parseArguments(args))
return;
final WriteFeaturesMetadata task = new WriteFeaturesMetadata();
task.featureWeightsFilepathsSelection = (List<String>) argParse.getValue("--selection-feature-weights-filepaths");
task.featureWeightsFilepathsPlayout = (List<String>) argParse.getValue("--playout-feature-weights-filepaths");
task.outFile = new File(argParse.getValueString("--out-file"));
task.boosted = argParse.getValueBool("--boosted");
task.run();
}
//-------------------------------------------------------------------------
}
| 4,677 | 27.876543 | 116 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/heuristicWeightTuning/HeuristicWeightTuning.java
|
package supplementary.experiments.heuristicWeightTuning;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.set.hash.TIntHashSet;
import main.collections.ListUtils;
import main.math.statistics.Stats;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.Heuristics;
import metadata.ai.heuristics.terms.CentreProximity;
import metadata.ai.heuristics.terms.ComponentValues;
import metadata.ai.heuristics.terms.CornerProximity;
import metadata.ai.heuristics.terms.HeuristicTerm;
import metadata.ai.heuristics.terms.Influence;
import metadata.ai.heuristics.terms.LineCompletionHeuristic;
import metadata.ai.heuristics.terms.Material;
import metadata.ai.heuristics.terms.MobilitySimple;
import metadata.ai.heuristics.terms.NullHeuristic;
import metadata.ai.heuristics.terms.OwnRegionsCount;
import metadata.ai.heuristics.terms.PlayerRegionsProximity;
import metadata.ai.heuristics.terms.PlayerSiteMapCount;
import metadata.ai.heuristics.terms.RegionProximity;
import metadata.ai.heuristics.terms.Score;
import metadata.ai.heuristics.terms.SidesProximity;
import metadata.ai.heuristics.terms.UnthreatenedMaterial;
import metadata.ai.misc.Pair;
import other.AI;
import other.GameLoader;
import search.flat.HeuristicSampling;
import supplementary.experiments.EvalGamesSet;
//-----------------------------------------------------------------------------
/**
* Experiments to tune the weights of heuristics
*
* @author matthew.stephenson and Dennis Soemers and cambolbro
*/
public class HeuristicWeightTuning
{
// Percentage of population that is chosen for tournament selection.
final static double tournamentSelectionPercentage = 10.0;
// Number of generations before stopping.
final static int numGenerations = 100;
// Number of trials per agent comparison.
final static int numTrialsPerComparison = 100;
// Number of samples when evaluating an agent.
final static int sampleSize = 100;
// Thread executor (maximum number of threads possible)
final static int numThreads = Runtime.getRuntime().availableProcessors();
final static ExecutorService executor = Executors.newFixedThreadPool(numThreads);
// Minimum win-rate against Null heuristic to survive initial pruning.
final static double initialWinRateThreshold = 0.55;
// Try removing heuristic terms which don't pass the improvement requirement.
final static boolean tryHeuristicRemoval = true;
final static double heuristicRemovalImprovementRquirement = -0.01;
// Normalises all weights on heuristic between -1 and 1.
final static boolean normaliseHeuristicWeights = true;
// Simplifies heuristic weights by combining them.
final static boolean simplifyHeuristicWeights = true;
// Fraction value for heuristic sampling agents.
final static int HeuristicSamplingAgentFraction = 4;
//-------------------------------------------------------------------------
/**
* Heuristic statistics object.
*/
static class HeuristicStats implements Comparable<HeuristicStats>
{
private double heuristicWinRateSum = 0.0;
private int numComparisons = 0;
public Double heuristicWinRate()
{
return Double.valueOf(heuristicWinRateSum / numComparisons);
}
public void addHeuristicWinRate(final double winRate)
{
heuristicWinRateSum += winRate;
numComparisons++;
}
@Override
public int compareTo(final HeuristicStats arg0)
{
return heuristicWinRate().compareTo(arg0.heuristicWinRate());
}
}
//-------------------------------------------------------------------------
private static void test()
{
//final Game game = GameLoader.loadGameFromName("Chess.lud");
//final Game game = GameLoader.loadGameFromName("Tic-Tac-Mo.lud");
final Game game = GameLoader.loadGameFromName("Breakthrough.lud");
//final Game game = GameLoader.loadGameFromName("Tablut.lud", Arrays.asList("Play Rules/King Flanked"));
System.out.println("--PERFORMING INITIAL HEURISTIC PRUNING--\n");
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics = initialHeuristics(game);
candidateHeuristics = intialCandidatePruning(game, candidateHeuristics, true);
System.out.println("--DETERMINING INITIAL HEURISTIC WEIGHTS--\n");
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
candidateHeuristics = evaluateCandidateHeuristicsAgainstEachOther(game, candidateHeuristics, candidateHeuristic.getKey());
for (int i = 1; i <= numGenerations; i++)
{
System.out.println("\nGENERATION " + i + "\n");
candidateHeuristics = evolveCandidateHeuristics(game, candidateHeuristics);
// Store the current candidate heuristics to a text file after each generation.
candidateHeuristics = sortCandidateHeuristics(candidateHeuristics);
final File resultDirectory = new File("HWT_results");
if (!resultDirectory.exists())
resultDirectory.mkdirs();
try (PrintWriter out = new PrintWriter(resultDirectory + "/results_" + game.name() + "_" + i + ".txt"))
{
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
{
out.println("-------------------------------");
out.println(candidateHeuristic.getKey());
out.println(candidateHeuristic.getValue().heuristicWinRate());
out.println("-------------------------------");
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
}
// Determine the best heuristic after all generations are complete.
final Heuristics bestHeuristicFound = candidateHeuristics.entrySet().iterator().next().getKey();
System.out.println(bestHeuristicFound);
// Compare best heuristic against the Null heuristic
final List<Heuristics> heuristics = new ArrayList<>();
heuristics.add(bestHeuristicFound);
heuristics.add(new Heuristics(new NullHeuristic()));
ArrayList<Double> agentMeanWinRates = compareHeuristics(game, heuristics);
System.out.println("Performance against Null heuristic: " + agentMeanWinRates.get(0));
// Compare the best heuristic against the default (metadata) HeuristicSampling agent.
heuristics.clear();
heuristics.add(bestHeuristicFound);
heuristics.add(null);
agentMeanWinRates = compareHeuristics(game, heuristics);
System.out.println("Performance against default HeuristicSampling agent : " + agentMeanWinRates.get(0));
bestHeuristicFound.toFile(game, "cameronMathew.heu");
System.out.println("DONE!");
}
//-------------------------------------------------------------------------
/**
* Prunes the initial set of all candidate heuristics
*
* @param game
* @param originalCandidateHeuristics Set of all initial heuristics.
* @param againstNullHeuristic If the comparison should be done against the Null heuristic rather than each other.
* @return
*/
private static LinkedHashMap<Heuristics, HeuristicStats> intialCandidatePruning(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> originalCandidateHeuristics, final boolean againstNullHeuristic)
{
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics = originalCandidateHeuristics;
System.out.println("Num initial heuristics: " + candidateHeuristics.size());
if (againstNullHeuristic)
{
// Initial comparison against Null heuristic.
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
{
System.out.println(candidateHeuristic.getKey());
final LinkedHashMap<Heuristics, HeuristicStats> agentList = new LinkedHashMap<>();
agentList.put(new Heuristics(new NullHeuristic()), new HeuristicStats());
agentList.put(candidateHeuristic.getKey(), candidateHeuristic.getValue());
candidateHeuristics.put(candidateHeuristic.getKey(), evaluateCandidateHeuristicsAgainstEachOther(game, agentList, null).get(candidateHeuristic.getKey()));
}
}
else
{
// Initial comparison against each other.
candidateHeuristics = evaluateCandidateHeuristicsAgainstEachOther(game, candidateHeuristics, null);
}
// Remove any entries that have below required win-rate.
candidateHeuristics.entrySet().removeIf(e -> e.getValue().heuristicWinRate().doubleValue() < initialWinRateThreshold);
return candidateHeuristics;
}
//-------------------------------------------------------------------------
/**
* Evolves the given set of candidate heuristics to create new candidate offspring.
*/
private static final LinkedHashMap<Heuristics, HeuristicStats> evolveCandidateHeuristics(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics)
{
final Heuristics[] parentHeuristics = tournamentSelection(candidateHeuristics);
final HeuristicTerm[] parentA = parentHeuristics[0].heuristicTerms();
final HeuristicTerm[] parentB = parentHeuristics[1].heuristicTerms();
final List<LinkedHashMap<Heuristics, HeuristicStats>> allCandidateHeuristics = new ArrayList<>();
final List<Heuristics> allHeuristics = new ArrayList<>();
allHeuristics.add(combineHeuristicTerms(parentA, parentB)); // Regular
allHeuristics.add(combineHeuristicTerms(parentA, HeuristicUtil.multiplyHeuristicTerms(parentB, 0.5))); // Double
allHeuristics.add(combineHeuristicTerms(parentA, HeuristicUtil.multiplyHeuristicTerms(parentB, 2.0))); // Half
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(0)));
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(1)));
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(2)));
// Record best candidate's results from evaluation
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsBest = null;
Heuristics newHeuristicBest = null;
double newHeuristicBestWeight = -1;
for (int i = 0; i < allHeuristics.size(); i++)
{
final double heurisitcWinRate = allCandidateHeuristics.get(i).get(allHeuristics.get(i)).heuristicWinRate().doubleValue();
if (heurisitcWinRate > newHeuristicBestWeight)
{
candidateHeuristicsBest = allCandidateHeuristics.get(i);
newHeuristicBest = allHeuristics.get(i);
newHeuristicBestWeight = heurisitcWinRate;
}
}
// Remove any unnecessary heuristic terms from the best heuristic.
if (tryHeuristicRemoval)
candidateHeuristicsBest = tryRemovingHeuristicTerms(game, candidateHeuristics, candidateHeuristicsBest, newHeuristicBest, newHeuristicBestWeight);
return candidateHeuristicsBest;
}
//-------------------------------------------------------------------------
private static LinkedHashMap<Heuristics, HeuristicStats> tryRemovingHeuristicTerms(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsBestOri, final Heuristics newHeuristicBestOri, final double newHeuristicBestWeightOri)
{
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsBest = candidateHeuristicsBestOri;
Heuristics newHeuristicBest = newHeuristicBestOri;
double newHeuristicBestWeight = newHeuristicBestWeightOri;
boolean changeMade = true;
while(changeMade)
{
changeMade = false;
final int numHeuristicTerms = newHeuristicBest.heuristicTerms().length;
for (int i = 0; i < numHeuristicTerms; i++)
{
final ArrayList<HeuristicTerm> heuristicsMinusOneTerm = new ArrayList<HeuristicTerm>();
for (int j = 0; j < numHeuristicTerms; j++)
{
if (i == j)
System.out.println("Evaluating without " + newHeuristicBest.heuristicTerms()[j]);
else
heuristicsMinusOneTerm.add(newHeuristicBest.heuristicTerms()[j]);
}
final Heuristics heuristicMinusOne = new Heuristics(heuristicsMinusOneTerm.toArray(new HeuristicTerm[0]));
final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsMinusOneWeight = addAndEvaluateHeuristic(game, candidateHeuristics, heuristicMinusOne);
final double newHeuristicMinusOneWeight = candidateHeuristicsMinusOneWeight.get(heuristicMinusOne).heuristicWinRate().doubleValue();
if (newHeuristicMinusOneWeight > newHeuristicBestWeight + heuristicRemovalImprovementRquirement)
{
candidateHeuristicsBest = candidateHeuristicsMinusOneWeight;
newHeuristicBest = heuristicMinusOne;
newHeuristicBestWeight = newHeuristicMinusOneWeight;
changeMade = true;
break;
}
}
}
return candidateHeuristicsBest;
}
//-------------------------------------------------------------------------
private static LinkedHashMap<Heuristics, HeuristicStats> addAndEvaluateHeuristic(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics, final Heuristics heuristic)
{
final LinkedHashMap<Heuristics, HeuristicStats> newcandidateHeuristics = copyCandidateHeuristics(candidateHeuristics);
if (!newcandidateHeuristics.containsKey(heuristic))
newcandidateHeuristics.put(heuristic, new HeuristicStats());
return evaluateCandidateHeuristicsAgainstEachOther(game, newcandidateHeuristics, heuristic);
}
//-------------------------------------------------------------------------
/**
* Copies an existing candidateHeuristics map.
*/
public static LinkedHashMap<Heuristics, HeuristicStats> copyCandidateHeuristics(final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics)
{
final LinkedHashMap<Heuristics, HeuristicStats> copy = new LinkedHashMap<>();
for (final Map.Entry<Heuristics, HeuristicStats> entry : candidateHeuristics.entrySet())
copy.put(entry.getKey(), entry.getValue());
return copy;
}
//-------------------------------------------------------------------------
/**
* Combines two arrays of heuristicTerms together.
*/
private static Heuristics combineHeuristicTerms(final HeuristicTerm[] heuristicTermsA, final HeuristicTerm[] heuristicTermsB)
{
final ArrayList<HeuristicTerm> heuristicTermsCombined = new ArrayList<>(Arrays.asList(heuristicTermsA));
for (final HeuristicTerm termB : heuristicTermsB)
{
boolean termAdded = false;
for (int i = 0; i < heuristicTermsCombined.size(); i++)
{
final HeuristicTerm termA = heuristicTermsCombined.get(i);
if (termA.canBeMerged(termB))
{
termA.merge(termB);
heuristicTermsCombined.set(i, termA);
termAdded = true;
break;
}
}
if (!termAdded)
heuristicTermsCombined.add(termB);
}
Heuristics combinedHeuristic = new Heuristics(heuristicTermsCombined.toArray(new HeuristicTerm[0]));
if (normaliseHeuristicWeights)
combinedHeuristic = HeuristicUtil.normaliseHeuristic(combinedHeuristic);
if (simplifyHeuristicWeights)
for (final HeuristicTerm term : combinedHeuristic.heuristicTerms())
term.simplify();
return combinedHeuristic;
}
//-------------------------------------------------------------------------
/**
* Selects two random individuals from the set of candidates, with probability based on its win-rate.
*/
private static Heuristics[] tournamentSelection(final LinkedHashMap<Heuristics, HeuristicStats> candidates)
{
// selected parent candidates.
final Heuristics[] selectedCandidates = new Heuristics[2];
if (candidates.size() < 2)
System.out.println("ERROR, candidates must be at least size 2.");
// Select a set of k random candidates;
final int k = Math.max((int) Math.ceil(candidates.keySet().size()/tournamentSelectionPercentage), 2);
final Set<Integer> selectedCandidateIndices = new HashSet<>();
while (selectedCandidateIndices.size() < k)
{
final int randomNum = ThreadLocalRandom.current().nextInt(0, candidates.keySet().size());
selectedCandidateIndices.add(Integer.valueOf(randomNum));
}
// Select the two best candidates from our random candidate set.
double highestWinRate = -1.0;
double secondHighestWinRate = -1.0;
int counter = 0;
for (final Map.Entry<Heuristics, HeuristicStats> candidate : candidates.entrySet())
{
if (selectedCandidateIndices.contains(Integer.valueOf(counter)))
{
if (candidate.getValue().heuristicWinRate().doubleValue() > highestWinRate)
{
selectedCandidates[1] = Heuristics.copy(selectedCandidates[0]);
secondHighestWinRate = highestWinRate;
selectedCandidates[0] = Heuristics.copy(candidate.getKey());
highestWinRate = candidate.getValue().heuristicWinRate().doubleValue();
}
else if (candidate.getValue().heuristicWinRate().doubleValue() > secondHighestWinRate)
{
selectedCandidates[1] = Heuristics.copy(candidate.getKey());
secondHighestWinRate = candidate.getValue().heuristicWinRate().doubleValue();
}
}
counter++;
}
return selectedCandidates;
}
//-------------------------------------------------------------------------
/**
* Selects a random individual from the set of candidates, with probability based on its win-rate.
*/
// private static Heuristics tournamentSelection(final Map<Heuristics, Double> candidates)
// {
// final double random = Math.random() * candidates.values().stream().mapToDouble(f -> f.doubleValue()).sum();
// double acumulatedChance = 0.0;
//
// for (final Map.Entry<Heuristics,Double> candidate : candidates.entrySet())
// {
// acumulatedChance += candidate.getValue();
// if (acumulatedChance >= random)
// return candidate.getKey();
// }
//
// System.out.println("SHOULDN'T REACH HERE");
// return null;
// }
//-------------------------------------------------------------------------
/**
* Evaluates a set of heuristics against each other, updating their associated win-rates.
*/
private static LinkedHashMap<Heuristics, HeuristicStats> evaluateCandidateHeuristicsAgainstEachOther(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics, final Heuristics requiredHeuristic)
{
final List<Heuristics> allHeuristics = new ArrayList<>(candidateHeuristics.keySet());
final List<TIntArrayList> allIndexCombinations = allHeuristicIndexCombinations(game.players().count(), allHeuristics, requiredHeuristic, sampleSize);
System.out.println("number of pairups: " + allIndexCombinations.size());
System.out.println("number of agents: " + allHeuristics.size());
try
{
// Run trials concurrently
final CountDownLatch latch = new CountDownLatch(allIndexCombinations.size());
for (final TIntArrayList agentIndices : allIndexCombinations)
{
executor.submit
(
() ->
{
final List<Heuristics> selectedHeuristiscs = new ArrayList<>();
for (final int i : agentIndices.toArray())
selectedHeuristiscs.add(Heuristics.copy(allHeuristics.get(i)));
final ArrayList<Double> agentMeanWinRates = compareHeuristics(game, selectedHeuristiscs);
for (int i = 0; i < agentMeanWinRates.size(); i++)
candidateHeuristics.get(allHeuristics.get(agentIndices.get(i))).addHeuristicWinRate(agentMeanWinRates.get(i).doubleValue());
System.out.print(".");
latch.countDown();
}
);
}
latch.await(); // wait for all trials to finish
}
catch (final Exception e)
{
e.printStackTrace();
}
System.out.println("\n");
return candidateHeuristics;
}
//-------------------------------------------------------------------------
/**
* Compares a set of agents on a given game.
*/
private static ArrayList<Double> compareHeuristics(final Game game, final List<Heuristics> heuristics)
{
final ArrayList<Double> agentMeanWinRates = new ArrayList<>();
final List<AI> agents = new ArrayList<>();
for (final Heuristics h : heuristics)
{
if (h == null)
agents.add(new HeuristicSampling(HeuristicSamplingAgentFraction));
else
agents.add(new HeuristicSampling(h, HeuristicSamplingAgentFraction));
}
final EvalGamesSet gamesSet =
new EvalGamesSet()
.setGameName(game.name() + ".lud")
.setAgents(agents)
.setWarmingUpSecs(0)
.setNumGames(numTrialsPerComparison)
.setPrintOut(false)
.setRoundToNextPermutationsDivisor(true)
.setRotateAgents(true);
gamesSet.startGames(game);
for (final Stats agentStats : gamesSet.resultsSummary().agentPoints())
{
agentStats.measure();
agentMeanWinRates.add(Double.valueOf(agentStats.mean()));
}
return agentMeanWinRates;
}
//-------------------------------------------------------------------------
/**
* Provides a list of TIntArrayList, describing all combinations of agent indices from allAgents.
*/
private static List<TIntArrayList> allHeuristicIndexCombinations(final int numPlayers, final List<Heuristics> allHeuristics, final Heuristics requiredHeuristic, final int samepleSize)
{
final int numHeuristics = allHeuristics.size();
final TIntArrayList heuristicIndices = new TIntArrayList(numHeuristics);
for (int i = 0; i < numHeuristics; ++i)
heuristicIndices.add(i);
List<TIntArrayList> allHeuristicIndexCombinations = new ArrayList<TIntArrayList>();
ListUtils.generateAllCombinations(heuristicIndices, numPlayers, 0, new int[numPlayers], allHeuristicIndexCombinations);
// Only select heuristic combinations that includes our required heuristic. Also remove combinations with duplicates to prevent potential issues.
if (requiredHeuristic != null)
{
final int requiredHeuristicIndex = allHeuristics.indexOf(requiredHeuristic);
final List<TIntArrayList> allHeuristicIndexCombinationsNew = new ArrayList<TIntArrayList>();
for (final TIntArrayList heuristicIndexCombination : allHeuristicIndexCombinations)
if (heuristicIndexCombination.contains(requiredHeuristicIndex) && !containsDuplicates(heuristicIndexCombination))
allHeuristicIndexCombinationsNew.add(heuristicIndexCombination);
allHeuristicIndexCombinations = allHeuristicIndexCombinationsNew;
}
// Select a random number of combinations based on our desired sample size.
if (samepleSize > 0 && samepleSize <= allHeuristicIndexCombinations.size())
{
Collections.shuffle(allHeuristicIndexCombinations);
return allHeuristicIndexCombinations.subList(0, samepleSize);
}
return allHeuristicIndexCombinations;
}
/**
* @return True if duplicate values are present in list
*/
private static boolean containsDuplicates(final TIntArrayList list)
{
final TIntHashSet set = new TIntHashSet();
for (int i = 0; i < list.size(); i++)
{
if (!set.add(list.getQuick(i)))
return true;
}
return false;
}
//-------------------------------------------------------------------------
/**
* Provides a list of all initial heuristics.
*/
private static LinkedHashMap<Heuristics, HeuristicStats> initialHeuristics(final Game game)
{
final LinkedHashMap<Heuristics, HeuristicStats> initialHeuristics = new LinkedHashMap<>();
final List<HeuristicTerm> heuristicTerms = new ArrayList<>();
// All possible initial component pair combinations.
final List<Pair[]> allComponentPairsCombinations = new ArrayList<>();
for (int i = 0; i < game.equipment().components().length-1; i++)
{
final Pair[] componentPairs = new Pair[game.equipment().components().length-1];
for (int j = 0; j < game.equipment().components().length-1; j++)
{
if (j == i)
componentPairs[j] = new Pair(game.equipment().components()[j+1].name(), Float.valueOf(1));
else
componentPairs[j] = new Pair(game.equipment().components()[j+1].name(), Float.valueOf(0));
}
allComponentPairsCombinations.add(componentPairs);
}
for (float weight = -1f; weight < 2; weight+=2)
{
if (LineCompletionHeuristic.isApplicableToGame(game))
heuristicTerms.add(new LineCompletionHeuristic(null, Float.valueOf(weight), null));
if (MobilitySimple.isApplicableToGame(game))
heuristicTerms.add(new MobilitySimple(null, Float.valueOf(weight)));
if (Influence.isApplicableToGame(game))
heuristicTerms.add(new Influence(null, Float.valueOf(weight)));
if (OwnRegionsCount.isApplicableToGame(game))
heuristicTerms.add(new OwnRegionsCount(null, Float.valueOf(weight)));
if (PlayerSiteMapCount.isApplicableToGame(game))
heuristicTerms.add(new PlayerSiteMapCount(null, Float.valueOf(weight)));
if (Score.isApplicableToGame(game))
heuristicTerms.add(new Score(null, Float.valueOf(weight)));
if (CentreProximity.isApplicableToGame(game))
{
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), componentPairs));
}
if (ComponentValues.isApplicableToGame(game))
{
heuristicTerms.add(new ComponentValues(null, Float.valueOf(weight), null, null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new ComponentValues(null, Float.valueOf(weight), componentPairs, null));
}
if (CornerProximity.isApplicableToGame(game))
{
heuristicTerms.add(new CornerProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CornerProximity(null, Float.valueOf(weight), componentPairs));
}
if (Material.isApplicableToGame(game))
{
heuristicTerms.add(new Material(null, Float.valueOf(weight), null, null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new Material(null, Float.valueOf(weight), componentPairs, null));
}
if (SidesProximity.isApplicableToGame(game))
{
heuristicTerms.add(new SidesProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), componentPairs));
}
if (PlayerRegionsProximity.isApplicableToGame(game))
{
for (int p = 1; p <= game.players().count(); ++p)
{
heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(weight), Integer.valueOf(p), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(weight), Integer.valueOf(p), componentPairs));
}
}
if (RegionProximity.isApplicableToGame(game))
{
for (int i = 0; i < game.equipment().regions().length; ++i)
{
heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), componentPairs));
}
}
if (UnthreatenedMaterial.isApplicableToGame(game)) {
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new UnthreatenedMaterial(null, Float.valueOf(weight), componentPairs));
}
// if (ThreatenedMaterial.isApplicableToGame(game)) {
// for (final Pair[] componentPairs : allComponentPairsCombinations)
// heuristicTerms.add(new ThreatenedMaterial(null, Float.valueOf(weight), componentPairs));
// }
//
// if (ThreatenedMaterialMultipleCount.isApplicableToGame(game)) {
// for (final Pair[] componentPairs : allComponentPairsCombinations)
// heuristicTerms.add(new ThreatenedMaterialMultipleCount(null, Float.valueOf(weight), componentPairs));
// }
}
for (final HeuristicTerm h : heuristicTerms)
initialHeuristics.put(new Heuristics(h), new HeuristicStats());
return initialHeuristics;
}
//-------------------------------------------------------------------------
private static LinkedHashMap<Heuristics, HeuristicStats> sortCandidateHeuristics(final LinkedHashMap<Heuristics, HeuristicStats> unsortedMap)
{
final LinkedHashMap<Heuristics, HeuristicStats> sortedMap = new LinkedHashMap<>();
unsortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
return sortedMap;
}
//-------------------------------------------------------------------------
public static void main(final String[] args)
{
test();
}
//-------------------------------------------------------------------------
}
| 28,792 | 38.714483 | 323 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/heuristicWeightTuning/HeuristicWeightTuningOld.java
|
package supplementary.experiments.heuristicWeightTuning;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.collections.ListUtils;
import main.math.statistics.Stats;
import metadata.ai.heuristics.Heuristics;
import metadata.ai.heuristics.terms.CentreProximity;
import metadata.ai.heuristics.terms.ComponentValues;
import metadata.ai.heuristics.terms.CornerProximity;
import metadata.ai.heuristics.terms.HeuristicTerm;
import metadata.ai.heuristics.terms.Influence;
import metadata.ai.heuristics.terms.LineCompletionHeuristic;
import metadata.ai.heuristics.terms.Material;
import metadata.ai.heuristics.terms.MobilitySimple;
import metadata.ai.heuristics.terms.NullHeuristic;
import metadata.ai.heuristics.terms.OwnRegionsCount;
import metadata.ai.heuristics.terms.PlayerRegionsProximity;
import metadata.ai.heuristics.terms.PlayerSiteMapCount;
import metadata.ai.heuristics.terms.RegionProximity;
import metadata.ai.heuristics.terms.Score;
import metadata.ai.heuristics.terms.SidesProximity;
import metadata.ai.misc.Pair;
import other.AI;
import other.GameLoader;
import search.flat.HeuristicSampling;
import supplementary.experiments.EvalGamesSet;
//-----------------------------------------------------------------------------
/**
* Experiments to tune the weights of heuristics
*
* @author matthew.stephenson and cambolbro
*/
public class HeuristicWeightTuningOld
{
// Percentage of population that is chosen for tournament selection.
final static double tournamentSelectionPercentage = 10.0;
// Number of generations before stopping.
final static int numGenerations = 100;
// Number of trials per agent comparison.
final static int numTrialsPerComparison = 100;
// Number of samples when evaluating an agent.
final static int sampleSize = 100;
// Minimum win-rate against Null heuristic to survive initial pruning.
final static double initialWinRateThreshold = 0.55;
final static boolean tryHeuristicRemoval = true;
final static double heuristicRemovalImprovementRquirement = -0.01;
final static boolean normaliseHeuristicWeights = true;
final static boolean simplifyHeuristicWeights = true;
final static int HeuristicSamplingAgentFraction = 4;
//-------------------------------------------------------------------------
static class HeuristicStats implements Comparable<HeuristicStats>
{
private double heuristicWinRateSum = 0.0;
private int numComparisons = 0;
public Double heuristicWinRate()
{
return Double.valueOf(heuristicWinRateSum / numComparisons);
}
public void addHeuristicWinRate(final double winRate)
{
heuristicWinRateSum += winRate;
numComparisons++;
}
@Override
public int compareTo(final HeuristicStats arg0)
{
return heuristicWinRate().compareTo(arg0.heuristicWinRate());
}
}
//-------------------------------------------------------------------------
private static void test()
{
//final Game game = GameLoader.loadGameFromName("Tic-Tac-Toe.lud");
//final Game game = GameLoader.loadGameFromName("Tic-Tac-Mo.lud");
//final Game game = GameLoader.loadGameFromName("Breakthrough.lud");
final Game game = GameLoader.loadGameFromName("Tablut.lud", Arrays.asList("Play Rules/King Flanked"));
System.out.println("--PERFORMING INITIAL HEURISTIC PRUNING--\n");
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics = initialHeuristics(game);
candidateHeuristics = intialCandidatePruning(game, candidateHeuristics, true);
System.out.println("--DETERMINING INITIAL HEURISTIC WEIGHTS--\n");
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
candidateHeuristics = evaluateCandidateHeuristicsAgainstEachOther(game, candidateHeuristics, candidateHeuristic.getKey());
for (int i = 1; i <= numGenerations; i++)
{
System.out.println("\nGENERATION " + i + "\n");
candidateHeuristics = evolveCandidateHeuristics(game, candidateHeuristics);
// Store the current candidate heuristics to a text file after each generation.
candidateHeuristics = sortCandidateHeuristics(candidateHeuristics);
final File resultDirectory = new File("HWT_results");
if (!resultDirectory.exists())
resultDirectory.mkdirs();
try (PrintWriter out = new PrintWriter(resultDirectory + "/results_" + game.name() + "_" + i + ".txt"))
{
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
{
out.println("-------------------------------");
out.println(candidateHeuristic.getKey());
out.println(candidateHeuristic.getValue().heuristicWinRate());
out.println("-------------------------------");
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
}
// Determine the best heuristic after all generations are complete.
final Heuristics bestHeuristicFound = candidateHeuristics.entrySet().iterator().next().getKey();
System.out.println(bestHeuristicFound);
// Compare best heuristic against the Null heuristic
final List<AI> agents = new ArrayList<>();
agents.add(new HeuristicSampling(bestHeuristicFound, HeuristicSamplingAgentFraction));
agents.add(new HeuristicSampling(new Heuristics(new NullHeuristic()), HeuristicSamplingAgentFraction));
ArrayList<Double> agentMeanWinRates = compareAgents(game, agents);
System.out.println("Performance against Null heuristic: " + agentMeanWinRates.get(0));
// Compare the best heuristic against the default (metadata) HeuristicSampling agent.
agents.clear();
agents.add(new HeuristicSampling(bestHeuristicFound, HeuristicSamplingAgentFraction));
agents.add(new HeuristicSampling(HeuristicSamplingAgentFraction));
agentMeanWinRates = compareAgents(game, agents);
System.out.println("Performance against default HeuristicSampling agent : " + agentMeanWinRates.get(0));
System.out.println("DONE!");
}
//-------------------------------------------------------------------------
/**
* Prunes the initial set of all candidate heuristics
*
* @param game
* @param originalCandidateHeuristics Set of all initial heuristics.
* @param againstNullHeuristic If the comparison should be done against the Null heuristic rather than each other.
* @return
*/
private static LinkedHashMap<Heuristics, HeuristicStats> intialCandidatePruning(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> originalCandidateHeuristics, final boolean againstNullHeuristic)
{
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics = originalCandidateHeuristics;
System.out.println("Num initial heuristics: " + candidateHeuristics.size());
if (againstNullHeuristic)
{
// Initial comparison against Null heuristic.
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
{
System.out.println(candidateHeuristic.getKey());
final LinkedHashMap<Heuristics, HeuristicStats> agentList = new LinkedHashMap<>();
agentList.put(new Heuristics(new NullHeuristic()), new HeuristicStats());
agentList.put(candidateHeuristic.getKey(), candidateHeuristic.getValue());
candidateHeuristics.put(candidateHeuristic.getKey(), evaluateCandidateHeuristicsAgainstEachOther(game, agentList, null).get(candidateHeuristic.getKey()));
}
}
else
{
// Initial comparison against each other.
candidateHeuristics = evaluateCandidateHeuristicsAgainstEachOther(game, candidateHeuristics, null);
}
// Remove any entries that have below required win-rate.
candidateHeuristics.entrySet().removeIf(e -> e.getValue().heuristicWinRate().doubleValue() < initialWinRateThreshold);
return candidateHeuristics;
}
//-------------------------------------------------------------------------
/**
* Evolves the given set of candidate heuristics to create new candidate offspring.
*/
private static final LinkedHashMap<Heuristics, HeuristicStats> evolveCandidateHeuristics(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics)
{
final Heuristics[] parentHeuristics = tournamentSelection(candidateHeuristics);
final HeuristicTerm[] parentA = parentHeuristics[0].heuristicTerms();
final HeuristicTerm[] parentB = parentHeuristics[1].heuristicTerms();
final List<LinkedHashMap<Heuristics, HeuristicStats>> allCandidateHeuristics = new ArrayList<>();
final List<Heuristics> allHeuristics = new ArrayList<>();
allHeuristics.add(combineHeuristicTerms(parentA, parentB)); // Regular
allHeuristics.add(combineHeuristicTerms(parentA, multiplyHeuristicTerms(parentB, 0.5))); // Double
allHeuristics.add(combineHeuristicTerms(parentA, multiplyHeuristicTerms(parentB, 2.0))); // Half
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(0)));
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(1)));
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(2)));
// Record best candidate's results from evaluation
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsBest = null;
Heuristics newHeuristicBest = null;
double newHeuristicBestWeight = -1;
for (int i = 0; i < allHeuristics.size(); i++)
{
final double heurisitcWinRate = allCandidateHeuristics.get(i).get(allHeuristics.get(i)).heuristicWinRate().doubleValue();
if (heurisitcWinRate > newHeuristicBestWeight)
{
candidateHeuristicsBest = allCandidateHeuristics.get(i);
newHeuristicBest = allHeuristics.get(i);
newHeuristicBestWeight = heurisitcWinRate;
}
}
// Remove any unnecessary heuristic terms from the best heuristic.
if (tryHeuristicRemoval)
candidateHeuristicsBest = tryRemovingHeuristicTerms(game, candidateHeuristics, candidateHeuristicsBest, newHeuristicBest, newHeuristicBestWeight);
return candidateHeuristicsBest;
}
private static LinkedHashMap<Heuristics, HeuristicStats> tryRemovingHeuristicTerms(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsBestOri, final Heuristics newHeuristicBestOri, final double newHeuristicBestWeightOri)
{
LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsBest = candidateHeuristicsBestOri;
Heuristics newHeuristicBest = newHeuristicBestOri;
double newHeuristicBestWeight = newHeuristicBestWeightOri;
boolean changeMade = true;
while(changeMade)
{
changeMade = false;
final int numHeuristicTerms = newHeuristicBest.heuristicTerms().length;
for (int i = 0; i < numHeuristicTerms; i++)
{
final ArrayList<HeuristicTerm> heuristicsMinusOneTerm = new ArrayList<HeuristicTerm>();
for (int j = 0; j < numHeuristicTerms; j++)
{
if (i == j)
System.out.println("Evaluating without " + newHeuristicBest.heuristicTerms()[j]);
else
heuristicsMinusOneTerm.add(newHeuristicBest.heuristicTerms()[j]);
}
final Heuristics heuristicMinusOne = new Heuristics(heuristicsMinusOneTerm.toArray(new HeuristicTerm[0]));
final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristicsMinusOneWeight = addAndEvaluateHeuristic(game, candidateHeuristics, heuristicMinusOne);
final double newHeuristicMinusOneWeight = candidateHeuristicsMinusOneWeight.get(heuristicMinusOne).heuristicWinRate().doubleValue();
if (newHeuristicMinusOneWeight > newHeuristicBestWeight + heuristicRemovalImprovementRquirement)
{
candidateHeuristicsBest = candidateHeuristicsMinusOneWeight;
newHeuristicBest = heuristicMinusOne;
newHeuristicBestWeight = newHeuristicMinusOneWeight;
changeMade = true;
break;
}
}
}
return candidateHeuristicsBest;
}
private static LinkedHashMap<Heuristics, HeuristicStats> addAndEvaluateHeuristic(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics, final Heuristics heuristic)
{
final LinkedHashMap<Heuristics, HeuristicStats> newcandidateHeuristics = copyCandidateHeuristics(candidateHeuristics);
if (!newcandidateHeuristics.containsKey(heuristic))
newcandidateHeuristics.put(heuristic, new HeuristicStats());
return evaluateCandidateHeuristicsAgainstEachOther(game, newcandidateHeuristics, heuristic);
}
/**
* Copies an existing candidateHeuristics map.
*/
public static LinkedHashMap<Heuristics, HeuristicStats> copyCandidateHeuristics(final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics)
{
final LinkedHashMap<Heuristics, HeuristicStats> copy = new LinkedHashMap<>();
for (final Map.Entry<Heuristics, HeuristicStats> entry : candidateHeuristics.entrySet())
copy.put(entry.getKey(), entry.getValue());
return copy;
}
/**
* Multiplies the weights for an array of heuristicTerms by the specified multiplier.
*/
private static HeuristicTerm[] multiplyHeuristicTerms(final HeuristicTerm[] heuristicTerms, final double multiplier)
{
final HeuristicTerm[] heuristicTermsMultiplied = new HeuristicTerm[heuristicTerms.length];
for (int i = 0; i < heuristicTermsMultiplied.length; i++)
{
final HeuristicTerm halvedHeuristicTerm = heuristicTerms[i].copy();
halvedHeuristicTerm.setWeight((float) (heuristicTerms[i].weight()*multiplier));
heuristicTermsMultiplied[i] = halvedHeuristicTerm;
}
return heuristicTermsMultiplied;
}
/**
* Combines two arrays of heuristicTerms together.
*/
private static Heuristics combineHeuristicTerms(final HeuristicTerm[] heuristicTermsA, final HeuristicTerm[] heuristicTermsB)
{
final ArrayList<HeuristicTerm> heuristicTermsCombined = new ArrayList<>(Arrays.asList(heuristicTermsA));
for (final HeuristicTerm termB : heuristicTermsB)
{
boolean termAdded = false;
for (int i = 0; i < heuristicTermsCombined.size(); i++)
{
final HeuristicTerm termA = heuristicTermsCombined.get(i);
if (termA.canBeMerged(termB))
{
termA.merge(termB);
heuristicTermsCombined.set(i, termA);
termAdded = true;
break;
}
}
if (!termAdded)
heuristicTermsCombined.add(termB);
}
Heuristics combinedHeuristic = new Heuristics(heuristicTermsCombined.toArray(new HeuristicTerm[0]));
if (normaliseHeuristicWeights)
combinedHeuristic = normaliseHeuristic(combinedHeuristic);
if (simplifyHeuristicWeights)
for (final HeuristicTerm term : combinedHeuristic.heuristicTerms())
term.simplify();
return combinedHeuristic;
}
/**
* Normalises all weights on heuristic between -1 and 1.
*/
private static Heuristics normaliseHeuristic(final Heuristics heuristic)
{
double maxWeight = 0.0;
for (final HeuristicTerm term : heuristic.heuristicTerms())
maxWeight = Math.max(maxWeight, term.maxAbsWeight());
return new Heuristics(multiplyHeuristicTerms(heuristic.heuristicTerms(), 1.0/maxWeight));
}
//-------------------------------------------------------------------------
/**
* Selects two random individuals from the set of candidates, with probability based on its win-rate.
*/
private static Heuristics[] tournamentSelection(final LinkedHashMap<Heuristics, HeuristicStats> candidates)
{
// selected parent candidates.
final Heuristics[] selectedCandidates = new Heuristics[2];
if (candidates.size() < 2)
System.out.println("ERROR, candidates must be at least size 2.");
// Select a set of k random candidates;
final int k = Math.max((int) Math.ceil(candidates.keySet().size()/tournamentSelectionPercentage), 2);
final Set<Integer> selectedCandidateIndices = new HashSet<>();
while (selectedCandidateIndices.size() < k)
{
final int randomNum = ThreadLocalRandom.current().nextInt(0, candidates.keySet().size());
selectedCandidateIndices.add(Integer.valueOf(randomNum));
}
// Select the two best candidates from our random candidate set.
double highestWinRate = -1.0;
double secondHighestWinRate = -1.0;
int counter = 0;
for (final Map.Entry<Heuristics, HeuristicStats> candidate : candidates.entrySet())
{
if (selectedCandidateIndices.contains(Integer.valueOf(counter)))
{
if (candidate.getValue().heuristicWinRate().doubleValue() > highestWinRate)
{
selectedCandidates[1] = Heuristics.copy(selectedCandidates[0]);
secondHighestWinRate = highestWinRate;
selectedCandidates[0] = Heuristics.copy(candidate.getKey());
highestWinRate = candidate.getValue().heuristicWinRate().doubleValue();
}
else if (candidate.getValue().heuristicWinRate().doubleValue() > secondHighestWinRate)
{
selectedCandidates[1] = Heuristics.copy(candidate.getKey());
secondHighestWinRate = candidate.getValue().heuristicWinRate().doubleValue();
}
}
counter++;
}
return selectedCandidates;
}
//-------------------------------------------------------------------------
/**
* Evaluates a set of heuristics against each other, updating their associated win-rates.
*/
private static LinkedHashMap<Heuristics, HeuristicStats> evaluateCandidateHeuristicsAgainstEachOther(final Game game, final LinkedHashMap<Heuristics, HeuristicStats> candidateHeuristics, final Heuristics requiredHeuristic)
{
final List<Heuristics> allHeuristics = new ArrayList<>(candidateHeuristics.keySet());
final List<TIntArrayList> allIndexCombinations = allHeuristicIndexCombinations(game.players().count(), allHeuristics, requiredHeuristic, sampleSize);
final List<HeuristicSampling> allAgents = createAgents(allHeuristics);
System.out.println("number of pairups: " + allIndexCombinations.size());
System.out.println("number of agents: " + allAgents.size());
// Perform initial comparison across all agents/heuristics
for (final TIntArrayList agentIndices : allIndexCombinations)
{
System.out.print(".");
final List<AI> agents = new ArrayList<>();
for (final int i : agentIndices.toArray())
agents.add(allAgents.get(i));
final ArrayList<Double> agentMeanWinRates = compareAgents(game, agents);
for (int i = 0; i < agentMeanWinRates.size(); i++)
candidateHeuristics.get
(
allHeuristics.get
(
agentIndices.get(i))
).addHeuristicWinRate(agentMeanWinRates.get(i).doubleValue()
);
}
System.out.println("\n");
return candidateHeuristics;
}
//-------------------------------------------------------------------------
/**
* Compares a set of agents on a given game.
*/
private static ArrayList<Double> compareAgents(final Game game, final List<AI> agents)
{
final EvalGamesSet gamesSet =
new EvalGamesSet()
.setGameName(game.name() + ".lud")
.setAgents(agents)
.setWarmingUpSecs(0)
.setNumGames(numTrialsPerComparison)
.setPrintOut(false)
.setRoundToNextPermutationsDivisor(true)
.setRotateAgents(true);
gamesSet.startGames(game);
final ArrayList<Double> agentMeanWinRates = new ArrayList<>();
for (final Stats agentStats : gamesSet.resultsSummary().agentPoints())
{
agentStats.measure();
agentMeanWinRates.add(Double.valueOf(agentStats.mean()));
}
return agentMeanWinRates;
}
// private static ArrayList<Double> compareAgents(final Game game, final List<AI> agents)
// {
// final ArrayList<Double> agentMeanWinRates = new ArrayList<>();
//
// try
// {
// final int numTrials = numTrialsPerComparison;
//
// AI aiA = null;
// AI aiB = null;
//
// // Run trials concurrently
// final ExecutorService executor = Executors.newFixedThreadPool(numTrials);
// final List<Future<TrialRecord>> futures = new ArrayList<>(numTrials);
//
// final CountDownLatch latch = new CountDownLatch(numTrials);
//
// for (int t = 0; t < numTrials; t++)
// {
// final int starter = t % 2;
//
// final List<AI> ais = new ArrayList<>();
// ais.add(null); // null placeholder for player 0
//
// aiA = agents.get(0);
// aiB = agents.get(1);
//
// if (t % 2 == 0)
// {
// ais.add(aiA);
// ais.add(aiB);
// }
// else
// {
// ais.add(aiB);
// ais.add(aiA);
// }
//
// futures.add
// (
// executor.submit
// (
// () ->
// {
// final Trial trial = new Trial(game);
// final Context context = new Context(game, trial);
//
// game.start(context);
//
// for (int p = 1; p <= game.players().count(); ++p)
// ais.get(p).initAI(game, p);
//
// final Model model = context.model();
// while (!trial.over())
// model.startNewStep(context, ais, -1, -1, 1, 0);
//
// latch.countDown();
// System.out.println(latch.getCount());
//
// return new TrialRecord(starter, trial);
// }
// )
// );
// }
//
// latch.await(); // wait for all trials to finish
//
// // Accumulate wins per player
// final double[] results = new double[Constants.MAX_PLAYERS + 1];
//
// for (int t = 0; t < numTrials; t++)
// {
// final TrialRecord trialRecord = futures.get(t).get();
// final Trial trial = trialRecord.trial();
//
// final int result = trial.status().winner(); //futures.get(t).get().intValue();
// if (result == 0)
// {
// // Draw: share win
// results[0] += 0.5;
// results[1] += 0.5;
// }
// else
// {
// // Reward winning AI
// if (trialRecord.starter() == 0)
// {
// if (result == 1)
// results[0]++;
// else
// results[1]++;
// }
// else
// {
// if (result == 1)
// results[1]++;
// else
// results[0]++;
// }
// }
//
// //System.out.println(trialRecord.starter() + " => " + trial.status().winner());
// }
//
// //System.out.println("\naiA=" + results[0] + ", aiB=" + results[1] + ".");
// System.out.println("aiA success rate " + results[0] / numTrials * 100 + "%."); //+ ", aiB=" + results[1] + ".");
//
// agentMeanWinRates.add(results[0] / numTrials);
// agentMeanWinRates.add(results[1] / numTrials);
//
// executor.shutdown();
// }
// catch (final Exception e)
// {
// e.printStackTrace();
// }
//
// return agentMeanWinRates;
// }
// private static ArrayList<Double> compareAgents(final Game game, final List<AI> agents)
// {
// final ArrayList<Double> agentMeanWinRates = new ArrayList<>();
//
// try
// {
// final int numTrials = numTrialsPerComparison;
//
// AI aiA = null;
// AI aiB = null;
//
// // Run trials concurrently
// final ExecutorService executor = Executors.newFixedThreadPool(numTrials);
// final List<TrialRecord> futures = new ArrayList<>(numTrials);
//
// final CountDownLatch latch = new CountDownLatch(numTrials);
//
// for (int t = 0; t < numTrials; t++)
// {
// final int starter = t % 2;
//
// final List<AI> ais = new ArrayList<>();
// ais.add(null); // null placeholder for player 0
//
// aiA = agents.get(0);
// aiB = agents.get(1);
//
// if (t % 2 == 0)
// {
// ais.add(aiA);
// ais.add(aiB);
// }
// else
// {
// ais.add(aiB);
// ais.add(aiA);
// }
//
//
// final Trial trial = new Trial(game);
// final Context context = new Context(game, trial);
//
// game.start(context);
//
// for (int p = 1; p <= game.players().count(); ++p)
// ais.get(p).initAI(game, p);
//
// final Model model = context.model();
// while (!trial.over())
// model.startNewStep(context, ais, -1, -1, 1, 0);
//
// latch.countDown();
// //System.out.println(latch.getCount());
//
// futures.add(new TrialRecord(starter, trial));
//
// }
//
// latch.await();
//
//
// // Accumulate wins per player
// final double[] results = new double[Constants.MAX_PLAYERS + 1];
//
// for (int t = 0; t < numTrials; t++)
// {
// final TrialRecord trialRecord = futures.get(t);
// final Trial trial = trialRecord.trial();
//
// final int result = trial.status().winner(); //futures.get(t).get().intValue();
// if (result == 0)
// {
// // Draw: share win
// results[0] += 0.5;
// results[1] += 0.5;
// }
// else
// {
// // Reward winning AI
// if (trialRecord.starter() == 0)
// {
// if (result == 1)
// results[0]++;
// else
// results[1]++;
// }
// else
// {
// if (result == 1)
// results[1]++;
// else
// results[0]++;
// }
// }
//
// //System.out.println(trialRecord.starter() + " => " + trial.status().winner());
// }
//
// //System.out.println("\naiA=" + results[0] + ", aiB=" + results[1] + ".");
// //System.out.println("aiA success rate " + results[0] / numTrials * 100 + "%."); //+ ", aiB=" + results[1] + ".");
//
// agentMeanWinRates.add(results[0] / numTrials);
// agentMeanWinRates.add(results[1] / numTrials);
//
// executor.shutdown();
// }
// catch (final Exception e)
// {
// e.printStackTrace();
// }
//
// return agentMeanWinRates;
// }
//-------------------------------------------------------------------------
/**
* Provides a list of TIntArrayList, describing all combinations of agent indices from allAgents.
*/
private static List<TIntArrayList> allHeuristicIndexCombinations(final int numPlayers, final List<Heuristics> allHeuristics, final Heuristics requiredHeuristic, final int samepleSize)
{
final int numHeuristics = allHeuristics.size();
final TIntArrayList heuristicIndices = new TIntArrayList(numHeuristics);
for (int i = 0; i < numHeuristics; ++i)
heuristicIndices.add(i);
List<TIntArrayList> allHeuristicIndexCombinations = new ArrayList<TIntArrayList>();
ListUtils.generateAllCombinations(heuristicIndices, numPlayers, 0, new int[numPlayers], allHeuristicIndexCombinations);
// Only select heuristic combinations that includes our required heuristic. Also remove combinations with duplicates to prevent potential issues.
if (requiredHeuristic != null)
{
final int requiredHeuristicIndex = allHeuristics.indexOf(requiredHeuristic);
final List<TIntArrayList> allHeuristicIndexCombinationsNew = new ArrayList<TIntArrayList>();
for (final TIntArrayList heuristicIndexCombination : allHeuristicIndexCombinations)
if (heuristicIndexCombination.contains(requiredHeuristicIndex) && !containsDuplicates(heuristicIndexCombination))
allHeuristicIndexCombinationsNew.add(heuristicIndexCombination);
allHeuristicIndexCombinations = allHeuristicIndexCombinationsNew;
}
// Select a random number of combinations based on our desired sample size.
if (samepleSize > 0 && samepleSize <= allHeuristicIndexCombinations.size())
{
Collections.shuffle(allHeuristicIndexCombinations);
return allHeuristicIndexCombinations.subList(0, samepleSize);
}
return allHeuristicIndexCombinations;
}
/**
* @return True if duplicate values are present in list
*/
private static boolean containsDuplicates(final TIntArrayList list)
{
final Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < list.size(); i++)
set.add(Integer.valueOf(list.get(i)));
return set.size() < list.size();
}
//-------------------------------------------------------------------------
/**
* Provides a list of all initial heuristics.
*/
private static LinkedHashMap<Heuristics, HeuristicStats> initialHeuristics(final Game game)
{
final LinkedHashMap<Heuristics, HeuristicStats> initialHeuristics = new LinkedHashMap<>();
final List<HeuristicTerm> heuristicTerms = new ArrayList<>();
// All possible initial component pair combinations.
final List<Pair[]> allComponentPairsCombinations = new ArrayList<>();
for (int i = 0; i < game.equipment().components().length-1; i++)
{
final Pair[] componentPairs = new Pair[game.equipment().components().length-1];
for (int j = 0; j < game.equipment().components().length-1; j++)
{
if (j == i)
componentPairs[j] = new Pair
(
game.equipment().components()[j+1].name(),
Float.valueOf(1f)
);
else
componentPairs[j] = new Pair
(
game.equipment().components()[j+1].name(),
Float.valueOf(0f)
);
}
allComponentPairsCombinations.add(componentPairs);
}
for (float weight = -1f; weight < 2; weight+=2)
{
heuristicTerms.add(new LineCompletionHeuristic(null, Float.valueOf(weight), null));
heuristicTerms.add(new MobilitySimple(null, Float.valueOf(weight)));
heuristicTerms.add(new Influence(null, Float.valueOf(weight)));
heuristicTerms.add(new OwnRegionsCount(null, Float.valueOf(weight)));
heuristicTerms.add(new PlayerSiteMapCount(null, Float.valueOf(weight)));
heuristicTerms.add(new Score(null, Float.valueOf(weight)));
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), componentPairs));
heuristicTerms.add(new ComponentValues(null, Float.valueOf(weight), null, null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new ComponentValues(null, Float.valueOf(weight), componentPairs, null));
heuristicTerms.add(new CornerProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CornerProximity(null, Float.valueOf(weight), componentPairs));
heuristicTerms.add(new Material(null, Float.valueOf(weight), null, null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new Material(null, Float.valueOf(weight), componentPairs, null));
heuristicTerms.add(new SidesProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), componentPairs));
for (int p = 1; p <= game.players().count(); ++p)
{
heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(weight), Integer.valueOf(p), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(weight), Integer.valueOf(p), componentPairs));
}
for (int i = 0; i < game.equipment().regions().length; ++i)
{
heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), componentPairs));
}
}
for (final HeuristicTerm h : heuristicTerms)
initialHeuristics.put(new Heuristics(h), new HeuristicStats());
return initialHeuristics;
}
//-------------------------------------------------------------------------
/**
* Provides a list of all initial HeuristicSampling agents, one for each provided heuristic.
*/
private static List<HeuristicSampling> createAgents(final List<Heuristics> heuristics)
{
final List<HeuristicSampling> allAgents = new ArrayList<>();
for (final Heuristics h : heuristics)
allAgents.add(new HeuristicSampling(h, HeuristicSamplingAgentFraction));
return allAgents;
}
//-------------------------------------------------------------------------
private static LinkedHashMap<Heuristics, HeuristicStats> sortCandidateHeuristics(final LinkedHashMap<Heuristics, HeuristicStats> unsortedMap)
{
final LinkedHashMap<Heuristics, HeuristicStats> sortedMap = new LinkedHashMap<>();
unsortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
return sortedMap;
}
//-------------------------------------------------------------------------
public static void main(final String[] args)
{
test();
}
//-------------------------------------------------------------------------
// private static int binom(final int N, final int K)
// {
// int ret = 1;
// for (int k = 0; k < K; k++)
// ret = ret * (N-k) / (k+1);
// return ret;
// }
//-------------------------------------------------------------------------
/**
* Selects a random individual from the set of candidates, with probability based on its win-rate.
*/
// private static Heuristics tournamentSelection(final Map<Heuristics, Double> candidates)
// {
// final double random = Math.random() * candidates.values().stream().mapToDouble(f -> f.doubleValue()).sum();
// double acumulatedChance = 0.0;
//
// for (final Map.Entry<Heuristics,Double> candidate : candidates.entrySet())
// {
// acumulatedChance += candidate.getValue();
// if (acumulatedChance >= random)
// return candidate.getKey();
// }
//
// System.out.println("SHOULDN'T REACH HERE");
// return null;
// }
}
| 33,405 | 35.429662 | 323 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/ludemes/CountLudemes.java
|
package supplementary.experiments.ludemes;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import grammar.ClassEnumerator;
/**
* Counts ludemes by category.
*
* @author cambolbro (based on code by Dennis Soemers).
*/
public class CountLudemes
{
/**
* Record of a ludeme class category and number of times it occurs.
*/
class Record
{
private final String label;
private final Class<?> category;
private int count = 0;
//-------------------------------------
public Record(final String label, final Class<?> category)
{
this.label = label;
this.category = category;
}
//-------------------------------------
public String label()
{
return label;
}
public Class<?> category()
{
return category;
}
public int count()
{
return count;
}
public void reset()
{
count = 0;
}
public void increment()
{
count++;
}
}
//---------------------------------------------------------
private final List<Record> records = new ArrayList<Record>();
private String result = "No count yet.";
//-------------------------------------------------------------------------
public CountLudemes()
{
prepareCategories();
countLudemes();
}
//-------------------------------------------------------------------------
public String result()
{
return result;
}
//-------------------------------------------------------------------------
/**
* Add ludemes categories to be counted here.
*/
void prepareCategories()
{
records.clear();
try
{
records.add(new Record("Ludeme classes", Class.forName("other.Ludeme")));
records.add(new Record("Integer functions", Class.forName("game.functions.ints.BaseIntFunction")));
records.add(new Record("Boolean functions", Class.forName("game.functions.booleans.BaseBooleanFunction")));
records.add(new Record("Region functions", Class.forName("game.functions.region.RegionFunction")));
records.add(new Record("Equipment (total)", Class.forName("game.equipment.Item")));
records.add(new Record("Containers", Class.forName("game.equipment.container.Container")));
records.add(new Record("Components", Class.forName("game.equipment.component.Component")));
records.add(new Record("Start rules", Class.forName("game.rules.start.StartRule")));
records.add(new Record("Moves rules", Class.forName("game.rules.play.moves.Moves")));
records.add(new Record("End rules", Class.forName("game.rules.end.End")));
//records.add(new Record("Game type modifiers", Class.forName("game.types.GameType")));
//records.add(new Record("", Class.forName("game.")));
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Count ludemes by category.
* @return String describing ludeme counts by category.
*/
public String countLudemes()
{
final String rootPackage = "game.Game";
for (final Record record : records)
record.reset();
// Get all classes from root package down
Class<?> clsRoot = null;
try
{
clsRoot = Class.forName(rootPackage);
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
return "Couldn't find root package \"game\".";
}
final List<Class<?>> classes = ClassEnumerator.getClassesForPackage(clsRoot.getPackage());
// Get the reference Ludeme class
Class<?> clsLudeme = null;
try
{
clsLudeme = Class.forName("other.Ludeme");
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
// Count ludemes in each category
int numEnums = 0;
int numEnumConstants = 0;
for (final Class<?> cls : classes)
{
for (final Record record : records)
{
if
(
clsLudeme.isAssignableFrom(cls)
&&
record.category().isAssignableFrom(cls)
&&
!Modifier.isAbstract(cls.getModifiers())
&&
!cls.getName().contains("$")
)
{
// Is a ludeme class
record.increment();
}
}
if (cls.isEnum())
{
// Is an enum class
numEnums++;
numEnumConstants += cls.getEnumConstants().length;
}
}
// Format the result
final StringBuilder sb = new StringBuilder();
//sb.append(classes.size() + " classes found from \"" + rootPackage + "\" root package.\n");
sb.append("\n");
for (final Record record : records)
sb.append(record.label() + ": " + record.count() + "\n");
sb.append("Enum classes: " + numEnums + "\n");
sb.append("Enum constants: " + numEnumConstants + "\n");
sb.append("\n");
result = sb.toString();
return result;
}
//-------------------------------------------------------------------------
}
| 4,807 | 22.684729 | 113 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/ludemes/ListAllLudemesUsage.java
|
package supplementary.experiments.ludemes;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import game.Game;
import grammar.ClassEnumerator;
import main.CommandLineArgParse;
import main.FileHandling;
import main.ReflectionUtils;
import other.GameLoader;
import other.Ludeme;
/**
* Lists information on usage for ALL ludemes
*
* @author Dennis Soemers
*/
public class ListAllLudemesUsage
{
/**
* This generates the results
*/
public static void listAllLudemesUsage()
{
Class<?> clsRoot = null;
try
{
clsRoot = Class.forName("game.Game");
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
return;
}
final List<Class<?>> classes = ClassEnumerator.getClassesForPackage(clsRoot.getPackage());
final Map<String, Set<String>> ludemesToUsingGames = new HashMap<String, Set<String>>();
for (final Class<?> clazz : classes)
{
if (clazz.getName().contains("$"))
continue; // is an internal class or enum?
if (Ludeme.class.isAssignableFrom(clazz))
{
ludemesToUsingGames.put(clazz.getName(), new HashSet<String>());
}
}
final String[] allGames = FileHandling.listGames();
for (String gameName : allGames)
{
gameName = gameName.replaceAll(Pattern.quote("\\"), "/");
final String[] gameNameParts = gameName.split(Pattern.quote("/"));
boolean skipGame = false;
for (final String part : gameNameParts)
{
if
(
part.equals("bad") ||
part.equals("bad_playout") ||
part.equals("wip") ||
part.equals("test") ||
part.equals("wishlist")
)
{
skipGame = true;
break;
}
}
if (skipGame)
continue;
System.out.println("Checking game: " + gameName + "...");
final Game game = GameLoader.loadGameFromName(gameName);
ludemesToUsingGames.get(Game.class.getName()).add(gameName);
updateMap(ludemesToUsingGames, game, gameName, new HashMap<Object, Set<String>>());
}
System.out.println();
final String[] ludemeNames = ludemesToUsingGames.keySet().toArray(new String[ludemesToUsingGames.keySet().size()]);
Arrays.sort(ludemeNames);
System.out.println("Usage of all ludemes:");
for (final String ludemeName : ludemeNames)
{
final Set<String> games = ludemesToUsingGames.get(ludemeName);
final StringBuilder sb = new StringBuilder();
sb.append(ludemeName + ": ");
while (sb.length() < 62)
{
sb.append(" ");
}
sb.append(games.size() + " games");
if (games.size() > 0)
{
final String[] sortedGames = games.toArray(new String[games.size()]);
Arrays.sort(sortedGames);
sb.append("(");
for (int i = 0; i < sortedGames.length; ++i)
{
final String[] nameSplit = sortedGames[i].split(Pattern.quote("/"));
sb.append(nameSplit[nameSplit.length - 1]);
if (i + 1 < sortedGames.length)
sb.append(", ");
}
sb.append(")");
}
System.out.println(sb.toString());
}
System.out.println();
int numUnusedLudemes = 0;
System.out.println("Unused Ludemes:");
for (final String ludemeName : ludemeNames)
{
final Set<String> games = ludemesToUsingGames.get(ludemeName);
if (games.isEmpty())
{
System.out.println(ludemeName);
++numUnusedLudemes;
}
}
System.out.println();
System.out.println("Number of ludemes used in at least 1 game: " + (ludemeNames.length - numUnusedLudemes));
}
/**
* Recursive method to update our map from ludemes to lists of games,
* to include ludemes encountered in subtree rooted in the given ludeme.
*
* @param ludemesToUsingGames
* @param ludeme
* @param gameName
* @param visited
*/
private static void updateMap
(
final Map<String, Set<String>> ludemesToUsingGames,
final Ludeme ludeme,
final String gameName,
final Map<Object, Set<String>> visited
)
{
final Class<? extends Ludeme> clazz = ludeme.getClass();
final List<Field> fields = ReflectionUtils.getAllFields(clazz);
try
{
for (final Field field : fields)
{
field.setAccessible(true);
//System.out.println("Field = " + field.getName() + " of class = " + clazz.getName());
if ((field.getModifiers() & Modifier.STATIC) != 0)
{
//System.out.println("skipping " + field.getName() + " because static");
continue;
}
if (visited.containsKey(ludeme) && visited.get(ludeme).contains(field.getName()))
{
//System.out.println("skipping " + field.getName() + " because already visited");
continue; // avoid stack overflow
}
final Object value = field.get(ludeme);
if (!visited.containsKey(ludeme))
visited.put(ludeme, new HashSet<String>());
visited.get(ludeme).add(field.getName());
if (value != null)
{
final Class<?> valueClass = value.getClass();
if (Ludeme.class.isAssignableFrom(valueClass))
{
// We've found a ludeme!
if (ludemesToUsingGames.containsKey(valueClass.getName()))
{
ludemesToUsingGames.get(valueClass.getName()).add(gameName);
}
else if
(
valueClass.getDeclaringClass() != null &&
ludemesToUsingGames.containsKey(valueClass.getDeclaringClass().getName())
)
{
// An inner ludeme class, give credit to outer class ludeme
ludemesToUsingGames.get(valueClass.getDeclaringClass().getName()).add(gameName);
}
else if (!valueClass.getName().contains("$"))
{
System.err.println("WARNING: ludeme class " + valueClass.getName() + " not in map!");
}
updateMap(ludemesToUsingGames, (Ludeme) value, gameName, visited);
}
else if (valueClass.isArray())
{
final Object[] array = ReflectionUtils.castArray(value);
for (final Object element : array)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
if (ludemesToUsingGames.containsKey(elementClass.getName()))
{
ludemesToUsingGames.get(elementClass.getName()).add(gameName);
}
else if
(
elementClass.getDeclaringClass() != null &&
ludemesToUsingGames.containsKey(elementClass.getDeclaringClass().getName())
)
{
// An inner ludeme class, give credit to outer class ludeme
ludemesToUsingGames.get(elementClass.getDeclaringClass().getName()).add(gameName);
}
else if (!elementClass.getName().contains("$"))
{
System.err.println("WARNING: ludeme class " + elementClass.getName() + " not in map!");
}
updateMap(ludemesToUsingGames, (Ludeme) element, gameName, visited);
}
}
}
}
else if (Iterable.class.isAssignableFrom(valueClass))
{
final Iterable<?> iterable = (Iterable<?>) value;
for (final Object element : iterable)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
if (ludemesToUsingGames.containsKey(elementClass.getName()))
{
ludemesToUsingGames.get(elementClass.getName()).add(gameName);
}
else if
(
elementClass.getDeclaringClass() != null &&
ludemesToUsingGames.containsKey(elementClass.getDeclaringClass().getName())
)
{
// An inner ludeme class, give credit to outer class ludeme
ludemesToUsingGames.get(elementClass.getDeclaringClass().getName()).add(gameName);
}
else if (!elementClass.getName().contains("$"))
{
System.err.println("WARNING: ludeme class " + elementClass.getName() + " not in map!");
}
updateMap(ludemesToUsingGames, (Ludeme) element, gameName, visited);
}
}
}
}
}
}
}
catch (final IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"List information on usage for ALL ludemes in Ludii."
);
if (!argParse.parseArguments(args))
return;
ListAllLudemesUsage.listAllLudemesUsage();
}
}
| 8,741 | 25.815951 | 117 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/ludemes/ListGamesUsingLudeme.java
|
package supplementary.experiments.ludemes;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import other.GameLoader;
import other.Ludeme;
import main.FileHandling;
import main.ReflectionUtils;
/**
* Implements a function to list all the games using a
* particular ludeme (AFTER compilation!).
*
* Only considers games compiled with their default options.
*
* @author Dennis Soemers
*/
public class ListGamesUsingLudeme
{
/** Name of ludeme for which to list games that use it */
private String ludemeName;
//-------------------------------------------------------------------------
/**
* This generates the results
*/
public void listGames()
{
final String[] allGames = FileHandling.listGames();
final TObjectIntHashMap<String> gameCounts = new TObjectIntHashMap<String>();
final Set<String> matchingLudemes = new HashSet<String>();
for (String gameName : allGames)
{
gameName = gameName.replaceAll(Pattern.quote("\\"), "/");
final String[] gameNameParts = gameName.split(Pattern.quote("/"));
boolean skipGame = false;
for (final String part : gameNameParts)
{
if (part.equals("bad") || part.equals("bad_playout") || part.equals("wip") || part.equals("test"))
{
skipGame = true;
break;
}
}
if (skipGame)
continue;
final Game game = GameLoader.loadGameFromName(gameName);
updateGameCounts(gameCounts, matchingLudemes, game, gameName, ludemeName, new HashMap<Object, Set<String>>());
}
if (matchingLudemes.size() > 1)
{
System.err.println("Warning! Target ludeme name is ambiguous. Included ludemes:");
for (final String name : matchingLudemes)
{
System.err.println(name);
}
System.err.println("");
}
final String[] gameNames = gameCounts.keySet().toArray(new String[gameCounts.keySet().size()]);
Arrays.sort(gameNames);
System.out.println("Games using ludeme: " + ludemeName);
for (final String gameName : gameNames)
{
System.out.println(gameName + ": " + gameCounts.get(gameName));
}
}
/**
* Recursive method to update game counts in given map, to include ludemes encountered
* in subtree rooted in the given ludeme.
*
* @param gameCounts
* @param matchingLudemes
* @param ludeme
* @param gameName
* @param targetLudemeName
*/
private static void updateGameCounts
(
final TObjectIntHashMap<String> gameCounts,
final Set<String> matchingLudemes,
final Ludeme ludeme,
final String gameName,
final String targetLudemeName,
final Map<Object, Set<String>> visited
)
{
final Class<? extends Ludeme> clazz = ludeme.getClass();
final List<Field> fields = ReflectionUtils.getAllFields(clazz);
try
{
for (final Field field : fields)
{
field.setAccessible(true);
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
if (visited.containsKey(ludeme) && visited.get(ludeme).contains(field.getName()))
continue; // avoid stack overflow
final Object value = field.get(ludeme);
if (!visited.containsKey(ludeme))
visited.put(ludeme, new HashSet<String>());
visited.get(ludeme).add(field.getName());
if (value != null)
{
final Class<?> valueClass = value.getClass();
if (Ludeme.class.isAssignableFrom(valueClass))
{
// We've found a ludeme!
boolean matchesTargetLudeme = false;
if (valueClass.getName().endsWith(targetLudemeName))
{
matchesTargetLudeme = true;
}
else if (valueClass.getDeclaringClass() != null)
{
if (valueClass.getDeclaringClass().getName().endsWith(targetLudemeName))
matchesTargetLudeme = true;
}
if (matchesTargetLudeme)
{
matchingLudemes.add(valueClass.getName());
gameCounts.adjustOrPutValue(gameName, 1, 1);
}
//System.out.println("recursing into " + field.getName() + " of " + clazz.getName());
updateGameCounts(gameCounts, matchingLudemes, (Ludeme) value, gameName, targetLudemeName, visited);
}
else if (valueClass.isArray())
{
final Object[] array = ReflectionUtils.castArray(value);
for (final Object element : array)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
boolean matchesTargetLudeme = false;
if (elementClass.getName().endsWith(targetLudemeName))
{
matchesTargetLudeme = true;
}
else if (elementClass.getDeclaringClass() != null)
{
if (elementClass.getDeclaringClass().getName().endsWith(targetLudemeName))
matchesTargetLudeme = true;
}
if (matchesTargetLudeme)
{
matchingLudemes.add(elementClass.getName());
gameCounts.adjustOrPutValue(gameName, 1, 1);
}
updateGameCounts(gameCounts, matchingLudemes, (Ludeme) element, gameName, targetLudemeName, visited);
}
}
}
}
else if (List.class.isAssignableFrom(valueClass))
{
final List<?> list = (List<?>) value;
for (final Object element : list)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
// We've found a ludeme!
boolean matchesTargetLudeme = false;
if (elementClass.getName().endsWith(targetLudemeName))
{
matchesTargetLudeme = true;
}
else if (elementClass.getDeclaringClass() != null)
{
if (elementClass.getDeclaringClass().getName().endsWith(targetLudemeName))
matchesTargetLudeme = true;
}
if (matchesTargetLudeme)
{
matchingLudemes.add(elementClass.getName());
gameCounts.adjustOrPutValue(gameName, 1, 1);
}
updateGameCounts(gameCounts, matchingLudemes, (Ludeme) element, gameName, targetLudemeName, visited);
}
}
}
}
}
}
}
catch (final IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"List all the games that use a particular ludeme (after compilation)."
);
argParse.addOption(new ArgOption()
.withNames("--ludeme")
.help("Name of the ludeme for which to find users.")
.withNumVals("1")
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final ListGamesUsingLudeme func = new ListGamesUsingLudeme();
func.ludemeName = (String) argParse.getValue("--ludeme");
func.listGames();
}
}
| 7,532 | 26.097122 | 113 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/ludemes/ListUsedLudemes.java
|
package supplementary.experiments.ludemes;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import game.Game;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import other.GameLoader;
import other.Ludeme;
import main.ReflectionUtils;
/**
* Implements a function to list all the ludemes used by a
* specific game (AFTER compilation!).
*
* @author Dennis Soemers
*/
public final class ListUsedLudemes
{
/** Name of game for which to list ludemes */
private String gameName;
/** Options to tweak game (variant, rules, board, etc.) */
private List<String> gameOptions;
//-------------------------------------------------------------------------
/**
* This generates the results
*/
public void listUsedLudemes()
{
final Game game = GameLoader.loadGameFromName(gameName, gameOptions);
final TObjectIntHashMap<String> ludemeCounts = new TObjectIntHashMap<String>();
ludemeCounts.put(Game.class.getName(), 1);
updateLudemeCounts(ludemeCounts, game, new HashMap<Object, Set<String>>());
final String[] ludemeNames = ludemeCounts.keySet().toArray(new String[0]);
Arrays.sort(ludemeNames);
System.out.println("Ludemes used by game: " + gameName);
for (final String ludemeName : ludemeNames)
{
System.out.println(ludemeName + ": " + ludemeCounts.get(ludemeName));
}
}
/**
* Recursive method to update ludeme counts in given map, to include ludemes encountered
* in subtree rooted in the given ludeme.
*
* @param ludemeCounts
* @param ludeme
* @param visited
*/
private static void updateLudemeCounts
(
final TObjectIntHashMap<String> ludemeCounts,
final Ludeme ludeme,
final Map<Object, Set<String>> visited
)
{
final Class<? extends Ludeme> clazz = ludeme.getClass();
final List<Field> fields = ReflectionUtils.getAllFields(clazz);
try
{
for (final Field field : fields)
{
field.setAccessible(true);
if ((field.getModifiers() & Modifier.STATIC) != 0)
{
continue;
}
if (visited.containsKey(ludeme) && visited.get(ludeme).contains(field.getName()))
{
continue; // avoid stack overflow
}
final Object value = field.get(ludeme);
if (!visited.containsKey(ludeme))
visited.put(ludeme, new HashSet<String>());
visited.get(ludeme).add(field.getName());
if (value != null)
{
final Class<?> valueClass = value.getClass();
if (Ludeme.class.isAssignableFrom(valueClass))
{
// We've found a ludeme!
ludemeCounts.adjustOrPutValue(valueClass.getName(), 1, 1);
updateLudemeCounts(ludemeCounts, (Ludeme) value, visited);
}
else if (valueClass.isArray())
{
final Object[] array = ReflectionUtils.castArray(value);
for (final Object element : array)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
ludemeCounts.adjustOrPutValue(element.getClass().getName(), 1, 1);
updateLudemeCounts(ludemeCounts, (Ludeme) element, visited);
}
}
}
}
else if (Iterable.class.isAssignableFrom(valueClass))
{
final Iterable<?> iterable = (Iterable<?>) value;
for (final Object element : iterable)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
ludemeCounts.adjustOrPutValue(element.getClass().getName(), 1, 1);
updateLudemeCounts(ludemeCounts, (Ludeme) element, visited);
}
}
}
}
}
}
}
catch (final IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"List all the ludemes used by a game (after compilation)."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to inspect. Should end with \".lud\".")
.withNumVals("1")
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--game-options")
.help("Game Options to load.")
.withDefault(new ArrayList<String>(0))
.withNumVals("*")
.withType(OptionTypes.String));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final ListUsedLudemes func = new ListUsedLudemes();
func.gameName = (String) argParse.getValue("--game");
func.gameOptions = (List<String>) argParse.getValue("--game-options");
func.listUsedLudemes();
}
}
| 5,250 | 25.124378 | 89 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/optim/EvolOptimHeuristics.java
|
package supplementary.experiments.optim;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.collections.ListUtils;
import main.math.statistics.Stats;
import metadata.ai.heuristics.Heuristics;
import metadata.ai.heuristics.terms.CentreProximity;
import metadata.ai.heuristics.terms.ComponentValues;
import metadata.ai.heuristics.terms.CornerProximity;
import metadata.ai.heuristics.terms.HeuristicTerm;
import metadata.ai.heuristics.terms.Influence;
import metadata.ai.heuristics.terms.InfluenceAdvanced;
import metadata.ai.heuristics.terms.LineCompletionHeuristic;
import metadata.ai.heuristics.terms.Material;
import metadata.ai.heuristics.terms.MobilityAdvanced;
import metadata.ai.heuristics.terms.MobilitySimple;
import metadata.ai.heuristics.terms.NullHeuristic;
import metadata.ai.heuristics.terms.OwnRegionsCount;
import metadata.ai.heuristics.terms.PlayerRegionsProximity;
import metadata.ai.heuristics.terms.PlayerSiteMapCount;
import metadata.ai.heuristics.terms.RegionProximity;
import metadata.ai.heuristics.terms.Score;
import metadata.ai.heuristics.terms.SidesProximity;
import metadata.ai.heuristics.terms.UnthreatenedMaterial;
import metadata.ai.misc.Pair;
import other.AI;
import other.GameLoader;
import search.flat.HeuristicSampling;
import supplementary.experiments.EvalGamesSet;
//-----------------------------------------------------------------------------
/**
* Experiments to optimise heuristics using a simple evolutionary-inspired approach
*
* @author Dennis Soemers and matthew.stephenson
*/
public class EvolOptimHeuristics
{
/** Name of game to compile */
private String gameName = null;
/** List of options to compile game with (ignored if ruleset is provided) */
private List<String> gameOptions = null;
/** Ruleset to compile game with */
private String ruleset = null;
/** List of names of heuristics we'd like to skip */
private List<String> skipHeuristics = null;
// Percentage of population that is chosen for tournament selection.
private double tournamentSelectionPercentage = 10.0;
// Number of generations before stopping.
private int numGenerations = 100;
// Number of trials per agent comparison.
private int numTrialsPerComparison = 100;
/** Max number of combinations of opponents we sample for evaluating a heuristic */
private int opponentsSampleSize = 100;
// Normalises all weights on heuristic between -1 and 1.
private boolean normaliseHeuristicWeights = true;
// Simplifies heuristic weights by combining them.
private boolean simplifyHeuristicWeights = true;
// Fraction value for heuristic sampling agents.
private int heuristicSamplingAgentFraction = 4;
/** Directory to write output to */
private File outDir = null;
//-------------------------------------------------------------------------
/**
* Constructor
*/
private EvolOptimHeuristics()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Runs our evolutionary optimisation of heuristics
*/
private void runOptim()
{
if (outDir == null)
System.err.println("Warning: no outDir specified!");
else if (!outDir.exists())
outDir.mkdirs();
final Game game;
if (ruleset != null && !ruleset.equals(""))
game = GameLoader.loadGameFromName(gameName, ruleset);
else
game = GameLoader.loadGameFromName(gameName, gameOptions);
Map<Heuristics, HeuristicStats> candidateHeuristics = initialHeuristics(game);
System.out.println("--DETERMINING INITIAL HEURISTIC WEIGHTS--\n");
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
candidateHeuristics = evaluateCandidateHeuristicsAgainstOthers(game, candidateHeuristics, candidateHeuristic.getKey());
for (int i = 1; i <= numGenerations; i++)
{
System.out.println("\nGENERATION " + i + "\n");
candidateHeuristics = evolveCandidateHeuristics(game, candidateHeuristics);
// Store the current candidate heuristics to a text file after each generation.
candidateHeuristics = sortCandidateHeuristics(candidateHeuristics);
if (outDir != null)
{
try (PrintWriter out = new PrintWriter(outDir + "/results_" + game.name() + "_" + i + ".txt"))
{
for (final Map.Entry<Heuristics, HeuristicStats> candidateHeuristic : candidateHeuristics.entrySet())
{
out.println("-------------------------------");
out.println(candidateHeuristic.getKey());
out.println(candidateHeuristic.getValue().heuristicWinRate());
out.println("-------------------------------");
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
}
}
// Determine the best heuristic after all generations are complete.
final Heuristics bestHeuristicFound = candidateHeuristics.entrySet().iterator().next().getKey();
System.out.println(bestHeuristicFound);
// Compare best heuristic against the Null heuristic
final List<Heuristics> heuristics = new ArrayList<>();
heuristics.add(bestHeuristicFound);
heuristics.add(new Heuristics(new NullHeuristic()));
TDoubleArrayList agentMeanWinRates = compareHeuristics(game, heuristics);
System.out.println("Performance against Null heuristic: " + agentMeanWinRates.getQuick(0));
// Compare the best heuristic against the default (metadata) HeuristicSampling agent.
heuristics.clear();
heuristics.add(bestHeuristicFound);
heuristics.add(null);
agentMeanWinRates = compareHeuristics(game, heuristics);
System.out.println("Performance against default HeuristicSampling agent : " + agentMeanWinRates.getQuick(0));
System.out.println("DONE!");
}
//-------------------------------------------------------------------------
/**
* Evolves the given set of candidate heuristics to create new candidate offspring.
*/
private final Map<Heuristics, HeuristicStats> evolveCandidateHeuristics
(
final Game game,
final Map<Heuristics, HeuristicStats> candidateHeuristics
)
{
final Heuristics[] parentHeuristics = tournamentSelection(candidateHeuristics);
final HeuristicTerm[] parentA = parentHeuristics[0].heuristicTerms();
final HeuristicTerm[] parentB = parentHeuristics[1].heuristicTerms();
final List<Map<Heuristics, HeuristicStats>> allCandidateHeuristics = new ArrayList<>();
final List<Heuristics> allHeuristics = new ArrayList<>();
allHeuristics.add(combineHeuristicTerms(parentA, parentB)); // Regular
allHeuristics.add(combineHeuristicTerms(parentA, multiplyHeuristicTerms(parentB, 0.5))); // Double
allHeuristics.add(combineHeuristicTerms(parentA, multiplyHeuristicTerms(parentB, 2.0))); // Half
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(0)));
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(1)));
allCandidateHeuristics.add(addAndEvaluateHeuristic(game, candidateHeuristics, allHeuristics.get(2)));
// Record best candidate's results from evaluation
Map<Heuristics, HeuristicStats> candidateHeuristicsBest = null;
double newHeuristicBestWeight = -1;
for (int i = 0; i < allHeuristics.size(); i++)
{
final double heurisitcWinRate = allCandidateHeuristics.get(i).get(allHeuristics.get(i)).heuristicWinRate();
if (heurisitcWinRate > newHeuristicBestWeight)
{
candidateHeuristicsBest = allCandidateHeuristics.get(i);
newHeuristicBestWeight = heurisitcWinRate;
}
}
return candidateHeuristicsBest;
}
private Map<Heuristics, HeuristicStats> addAndEvaluateHeuristic
(
final Game game,
final Map<Heuristics, HeuristicStats> candidateHeuristics,
final Heuristics heuristic
)
{
final Map<Heuristics, HeuristicStats> newcandidateHeuristics = copyCandidateHeuristics(candidateHeuristics);
if (!newcandidateHeuristics.containsKey(heuristic))
newcandidateHeuristics.put(heuristic, new HeuristicStats());
return evaluateCandidateHeuristicsAgainstOthers(game, newcandidateHeuristics, heuristic);
}
/**
* Copies an existing candidateHeuristics map.
* @return The copy
*/
private static Map<Heuristics, HeuristicStats> copyCandidateHeuristics(final Map<Heuristics, HeuristicStats> candidateHeuristics)
{
final LinkedHashMap<Heuristics, HeuristicStats> copy = new LinkedHashMap<>();
for (final Map.Entry<Heuristics, HeuristicStats> entry : candidateHeuristics.entrySet())
copy.put(entry.getKey(), entry.getValue());
return copy;
}
/**
* Multiplies the weights for an array of heuristicTerms by the specified multiplier.
*/
private static HeuristicTerm[] multiplyHeuristicTerms(final HeuristicTerm[] heuristicTerms, final double multiplier)
{
final HeuristicTerm[] heuristicTermsMultiplied = new HeuristicTerm[heuristicTerms.length];
for (int i = 0; i < heuristicTermsMultiplied.length; i++)
{
final HeuristicTerm halvedHeuristicTerm = heuristicTerms[i].copy();
halvedHeuristicTerm.setWeight((float) (heuristicTerms[i].weight()*multiplier));
heuristicTermsMultiplied[i] = halvedHeuristicTerm;
}
return heuristicTermsMultiplied;
}
/**
* Combines two arrays of heuristicTerms together.
*/
private Heuristics combineHeuristicTerms(final HeuristicTerm[] heuristicTermsA, final HeuristicTerm[] heuristicTermsB)
{
final ArrayList<HeuristicTerm> heuristicTermsCombined = new ArrayList<>(Arrays.asList(heuristicTermsA));
for (final HeuristicTerm termB : heuristicTermsB)
{
boolean termAdded = false;
for (int i = 0; i < heuristicTermsCombined.size(); i++)
{
final HeuristicTerm termA = heuristicTermsCombined.get(i);
if (termA.canBeMerged(termB))
{
termA.merge(termB);
heuristicTermsCombined.set(i, termA);
termAdded = true;
break;
}
}
if (!termAdded)
heuristicTermsCombined.add(termB);
}
Heuristics combinedHeuristic = new Heuristics(heuristicTermsCombined.toArray(new HeuristicTerm[0]));
if (normaliseHeuristicWeights)
combinedHeuristic = normaliseHeuristic(combinedHeuristic);
if (simplifyHeuristicWeights)
for (final HeuristicTerm term : combinedHeuristic.heuristicTerms())
term.simplify();
return combinedHeuristic;
}
/**
* Normalises all weights on heuristic between -1 and 1.
*/
private static Heuristics normaliseHeuristic(final Heuristics heuristic)
{
double maxWeight = 0.0;
for (final HeuristicTerm term : heuristic.heuristicTerms())
maxWeight = Math.max(maxWeight, term.maxAbsWeight());
return new Heuristics(multiplyHeuristicTerms(heuristic.heuristicTerms(), 1.0/maxWeight));
}
//-------------------------------------------------------------------------
/**
* Selects two random individuals from the set of candidates, with probability based on its win-rate.
*/
private Heuristics[] tournamentSelection(final Map<Heuristics, HeuristicStats> candidates)
{
// selected parent candidates.
final Heuristics[] selectedCandidates = new Heuristics[2];
if (candidates.size() < 2)
System.out.println("ERROR, candidates must be at least size 2.");
// Select a set of k random candidates;
final int k = Math.max((int) Math.ceil(candidates.keySet().size()/tournamentSelectionPercentage), 2);
final TIntSet selectedCandidateIndices = new TIntHashSet();
while (selectedCandidateIndices.size() < k)
{
final int randomNum = ThreadLocalRandom.current().nextInt(0, candidates.keySet().size());
selectedCandidateIndices.add(randomNum);
}
// Select the two best candidates from our random candidate set.
double highestWinRate = -1.0;
double secondHighestWinRate = -1.0;
int counter = 0;
for (final Map.Entry<Heuristics, HeuristicStats> candidate : candidates.entrySet())
{
if (selectedCandidateIndices.contains(counter))
{
if (candidate.getValue().heuristicWinRate() > highestWinRate)
{
selectedCandidates[1] = Heuristics.copy(selectedCandidates[0]);
secondHighestWinRate = highestWinRate;
selectedCandidates[0] = Heuristics.copy(candidate.getKey());
highestWinRate = candidate.getValue().heuristicWinRate();
}
else if (candidate.getValue().heuristicWinRate() > secondHighestWinRate)
{
selectedCandidates[1] = Heuristics.copy(candidate.getKey());
secondHighestWinRate = candidate.getValue().heuristicWinRate();
}
}
counter++;
}
return selectedCandidates;
}
/**
* Selects a random individual from the set of candidates, with probability based on its win-rate.
*/
// private Heuristics tournamentSelection(final Map<Heuristics, Double> candidates)
// {
// final double random = Math.random() * candidates.values().stream().mapToDouble(f -> f.doubleValue()).sum();
// double acumulatedChance = 0.0;
//
// for (final Map.Entry<Heuristics,Double> candidate : candidates.entrySet())
// {
// acumulatedChance += candidate.getValue();
// if (acumulatedChance >= random)
// return candidate.getKey();
// }
//
// System.out.println("SHOULDN'T REACH HERE");
// return null;
// }
//-------------------------------------------------------------------------
/**
* Evaluates a heuristic against (a sample of) all others, updating their associated win-rates.
*/
private Map<Heuristics, HeuristicStats> evaluateCandidateHeuristicsAgainstOthers
(
final Game game,
final Map<Heuristics, HeuristicStats> candidateHeuristics,
final Heuristics requiredHeuristic
)
{
final List<Heuristics> allHeuristics = new ArrayList<>(candidateHeuristics.keySet());
final List<TIntArrayList> allIndexCombinations = allHeuristicIndexCombinationsWithRequired(game.players().count(), allHeuristics, requiredHeuristic);
System.out.println("number of pairups: " + allIndexCombinations.size());
System.out.println("number of agents: " + allHeuristics.size());
for (final TIntArrayList agentIndices : allIndexCombinations)
{
final List<Heuristics> selectedHeuristiscs = new ArrayList<>(agentIndices.size());
for (int i = 0; i < agentIndices.size(); ++i)
selectedHeuristiscs.add(Heuristics.copy(allHeuristics.get(agentIndices.getQuick(i))));
final TDoubleArrayList agentMeanWinRates = compareHeuristics(game, selectedHeuristiscs);
for (int i = 0; i < agentMeanWinRates.size(); i++)
candidateHeuristics.get(allHeuristics.get(agentIndices.getQuick(i))).addHeuristicWinRate(agentMeanWinRates.getQuick(i));
System.out.print(".");
}
System.out.println("\n");
return candidateHeuristics;
}
//-------------------------------------------------------------------------
/**
* Compares a set of agents on a given game.
*/
private TDoubleArrayList compareHeuristics(final Game game, final List<Heuristics> heuristics)
{
final TDoubleArrayList agentMeanWinRates = new TDoubleArrayList();
final List<AI> agents = new ArrayList<>();
for (final Heuristics h : heuristics)
{
if (h == null)
agents.add(new HeuristicSampling(heuristicSamplingAgentFraction));
else
agents.add(new HeuristicSampling(h, heuristicSamplingAgentFraction));
}
final EvalGamesSet gamesSet =
new EvalGamesSet()
.setAgents(agents)
.setWarmingUpSecs(0)
.setNumGames(numTrialsPerComparison)
.setPrintOut(false)
.setRoundToNextPermutationsDivisor(true)
.setRotateAgents(true);
gamesSet.startGames(game);
for (final Stats agentStats : gamesSet.resultsSummary().agentPoints())
{
agentStats.measure();
agentMeanWinRates.add(agentStats.mean());
}
return agentMeanWinRates;
}
//-------------------------------------------------------------------------
/**
* Provides a list of TIntArrayList, describing all combinations of agent indices from allHeuristics,
* such that every combination includes the index of the given required heuristic.
*
* @param numPlayers
* @param allHeuristics
* @param requiredHeuristic
* @return
*/
private List<TIntArrayList> allHeuristicIndexCombinationsWithRequired
(
final int numPlayers,
final List<Heuristics> allHeuristics,
final Heuristics requiredHeuristic
)
{
final int numHeuristics = allHeuristics.size();
final TIntArrayList heuristicIndices = new TIntArrayList(numHeuristics);
for (int i = 0; i < numHeuristics; ++i)
heuristicIndices.add(i);
final List<TIntArrayList> allHeuristicIndexCombinations = new ArrayList<TIntArrayList>();
ListUtils.generateAllCombinations(heuristicIndices, numPlayers, 0, new int[numPlayers], allHeuristicIndexCombinations);
// Only keep heuristic combinations that include our required heuristic.
final int requiredHeuristicIndex = allHeuristics.indexOf(requiredHeuristic);
ListUtils.removeSwapIf(allHeuristicIndexCombinations, (l) -> {return !l.contains(requiredHeuristicIndex);});
// Select a random number of combinations based on our desired sample size.
if (opponentsSampleSize > 0 && opponentsSampleSize <= allHeuristicIndexCombinations.size())
{
Collections.shuffle(allHeuristicIndexCombinations);
return allHeuristicIndexCombinations.subList(0, opponentsSampleSize);
}
return allHeuristicIndexCombinations;
}
//-------------------------------------------------------------------------
/**
* Provides a list of all initial heuristics.
* @param game
*/
private LinkedHashMap<Heuristics, HeuristicStats> initialHeuristics(final Game game)
{
final LinkedHashMap<Heuristics, HeuristicStats> initialHeuristics = new LinkedHashMap<>();
final List<HeuristicTerm> heuristicTerms = new ArrayList<>();
// All possible initial component pair combinations.
final List<Pair[]> allComponentPairsCombinations = new ArrayList<>();
for (int i = 0; i < game.equipment().components().length - 1; i++)
{
final Pair[] componentPairs = new Pair[game.equipment().components().length - 1];
for (int j = 0; j < game.equipment().components().length - 1; j++)
{
if (j == i)
componentPairs[j] = new Pair(game.equipment().components()[j + 1].name(), Float.valueOf(1.f));
else
componentPairs[j] = new Pair(game.equipment().components()[j + 1].name(), Float.valueOf(0.f));
}
allComponentPairsCombinations.add(componentPairs);
}
for (final float weight : new float[]{-1.f, 1.f})
{
if (LineCompletionHeuristic.isSensibleForGame(game) && !skipHeuristics.contains("LineCompletionHeuristic"))
heuristicTerms.add(new LineCompletionHeuristic(null, Float.valueOf(weight), null));
if (MobilitySimple.isSensibleForGame(game) && !skipHeuristics.contains("MobilitySimple"))
heuristicTerms.add(new MobilitySimple(null, Float.valueOf(weight)));
if (MobilityAdvanced.isSensibleForGame(game) && !skipHeuristics.contains("MobilityAdvanced"))
heuristicTerms.add(new MobilityAdvanced(null, Float.valueOf(weight)));
if (Influence.isSensibleForGame(game) && !skipHeuristics.contains("Influence"))
heuristicTerms.add(new Influence(null, Float.valueOf(weight)));
if (InfluenceAdvanced.isSensibleForGame(game) && !skipHeuristics.contains("InfluenceAdvanced"))
heuristicTerms.add(new InfluenceAdvanced(null, Float.valueOf(weight)));
if (OwnRegionsCount.isSensibleForGame(game) && !skipHeuristics.contains("OwnRegionsCount"))
heuristicTerms.add(new OwnRegionsCount(null, Float.valueOf(weight)));
if (PlayerSiteMapCount.isSensibleForGame(game) && !skipHeuristics.contains("PlayerSiteMapCount"))
heuristicTerms.add(new PlayerSiteMapCount(null, Float.valueOf(weight)));
if (Score.isSensibleForGame(game) && !skipHeuristics.contains("Score"))
heuristicTerms.add(new Score(null, Float.valueOf(weight)));
if (CentreProximity.isSensibleForGame(game) && !skipHeuristics.contains("CentreProximity"))
{
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), componentPairs));
}
if (ComponentValues.isSensibleForGame(game) && !skipHeuristics.contains("ComponentValues"))
{
heuristicTerms.add(new ComponentValues(null, Float.valueOf(weight), null, null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new ComponentValues(null, Float.valueOf(weight), componentPairs, null));
}
if (CornerProximity.isSensibleForGame(game) && !skipHeuristics.contains("CornerProximity"))
{
heuristicTerms.add(new CornerProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CornerProximity(null, Float.valueOf(weight), componentPairs));
}
if (Material.isSensibleForGame(game) && !skipHeuristics.contains("Material"))
{
heuristicTerms.add(new Material(null, Float.valueOf(weight), null, null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new Material(null, Float.valueOf(weight), componentPairs, null));
}
if (UnthreatenedMaterial.isSensibleForGame(game) && !skipHeuristics.contains("UnthreatenedMaterial"))
{
heuristicTerms.add(new UnthreatenedMaterial(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new UnthreatenedMaterial(null, Float.valueOf(weight), componentPairs));
}
if (SidesProximity.isSensibleForGame(game) && !skipHeuristics.contains("SidesProximity"))
{
heuristicTerms.add(new SidesProximity(null, Float.valueOf(weight), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new CentreProximity(null, Float.valueOf(weight), componentPairs));
}
if (PlayerRegionsProximity.isSensibleForGame(game) && !skipHeuristics.contains("PlayerRegionsProximity"))
{
for (int p = 1; p <= game.players().count(); ++p)
{
heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(weight), Integer.valueOf(p), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new PlayerRegionsProximity(null, Float.valueOf(weight), Integer.valueOf(p), componentPairs));
}
}
if (RegionProximity.isSensibleForGame(game) && !skipHeuristics.contains("RegionProximity"))
{
for (int i = 0; i < game.equipment().regions().length; ++i)
{
heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), null));
for (final Pair[] componentPairs : allComponentPairsCombinations)
heuristicTerms.add(new RegionProximity(null, Float.valueOf(weight), Integer.valueOf(i), componentPairs));
}
}
}
for (final HeuristicTerm h : heuristicTerms)
initialHeuristics.put(new Heuristics(h), new HeuristicStats());
return initialHeuristics;
}
//-------------------------------------------------------------------------
private static Map<Heuristics, HeuristicStats> sortCandidateHeuristics(final Map<Heuristics, HeuristicStats> unsortedMap)
{
final Map<Heuristics, HeuristicStats> sortedMap = new LinkedHashMap<>();
unsortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
return sortedMap;
}
//-------------------------------------------------------------------------
/**
* Heuristic statistics object.
*/
protected static class HeuristicStats implements Comparable<HeuristicStats>
{
private double heuristicWinRateSum = 0.0;
private int numComparisons = 0;
public double heuristicWinRate()
{
return heuristicWinRateSum / numComparisons;
}
public void addHeuristicWinRate(final double winRate)
{
heuristicWinRateSum += winRate;
numComparisons++;
}
@Override
public int compareTo(final HeuristicStats other)
{
return Double.compare(heuristicWinRate(), other.heuristicWinRate());
}
}
//-------------------------------------------------------------------------
/**
* Run the evolutionary optimisation of heuristics
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args)
{
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Runs evolutionary optimisation of heuristics for a single game."
);
argParse.addOption(new ArgOption()
.withNames("--game")
.help("Name of the game to play. Should end with \".lud\".")
.withDefault("/Tic-Tac-Toe.lud")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--game-options")
.help("Game Options to load.")
.withDefault(new ArrayList<String>())
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--ruleset")
.help("Ruleset to compile.")
.withDefault("")
.withNumVals(1)
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--skip-heuristics")
.help("List of heuristics to skip.")
.withDefault(new ArrayList<String>())
.withNumVals("*")
.withType(OptionTypes.String));
argParse.addOption(new ArgOption()
.withNames("--out-dir", "--output-directory")
.help("Filepath for output directory")
.withNumVals(1)
.withType(OptionTypes.String));
// parse the args
if (!argParse.parseArguments(args))
return;
// use the parsed args
final EvolOptimHeuristics experiment = new EvolOptimHeuristics();
experiment.gameName = argParse.getValueString("--game");
experiment.gameOptions = (List<String>) argParse.getValue("--game-options");
experiment.ruleset = argParse.getValueString("--ruleset");
experiment.skipHeuristics = (List<String>) argParse.getValue("--skip-heuristics");
final String outDirFilepath = argParse.getValueString("--out-dir");
if (outDirFilepath != null)
experiment.outDir = new File(outDirFilepath);
else
experiment.outDir = null;
experiment.runOptim();
}
//-------------------------------------------------------------------------
}
| 26,689 | 35.763085 | 157 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/AtomicFeaturesPlayoutTimingScriptsGen.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Generates job scripts to submit to SLURM for running timings of
* playouts for a variety of different atomic feature sets.
*
* Script generation currently made for Cartesius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class AtomicFeaturesPlayoutTimingScriptsGen
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */
private static final String JVM_MEM = "4096";
/** JVM warming up time (in seconds) */
private static final int WARMUP_TIME = 60;
/** Time over which we measure playouts */
private static final int MEASURE_TIME = 600;
/** Max wall time (in minutes) (warming up time + measure time + some safety margin) */
private static final int MAX_WALL_TIME = 40;
/** We get 24 cores per job; we'll give 2 cores per process */
private static final int PROCESSES_PER_JOB = 12;
/** Only run on the Haswell nodes */
private static final String PROCESSOR = "haswell";
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Kensington.lud",
"Knightthrough.lud",
"Konane.lud",
"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptions of collections of features we want to benchmark */
private static final String[] FEATURES_TO_USE =
new String[]
{
"Atomic-1-1",
"Atomic-1-2",
"Atomic-2-2",
"Atomic-2-3",
"Atomic-2-4",
};
/** Different feature set implementations we want to benchmark */
private static final String[] FEATURE_SETS =
new String[]
{
"JITSPatterNet",
"SPatterNet",
"Legacy",
"Naive"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private AtomicFeaturesPlayoutTimingScriptsGen()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (final String gameName : GAMES)
{
// Sanity check: make sure game with this name loads correctly
System.out.println("gameName = " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName);
for (final String features : FEATURES_TO_USE)
{
for (final String featureSet : FEATURE_SETS)
{
processDataList.add(new ProcessData(gameName, features, featureSet));
}
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "BenchmarkFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J BenchmarkFeatures");
writer.println("#SBATCH -o /home/" + userName + "/BenchmarkFeatures/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/BenchmarkFeatures/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --constraint=" + PROCESSOR);
// load Java modules
writer.println("module load 2020");
writer.println("module load Java/1.8.0_261");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/BenchmarkFeatures/Ludii.jar"),
"--time-playouts",
"--warming-up-secs",
String.valueOf(WARMUP_TIME),
"--measure-secs",
String.valueOf(MEASURE_TIME),
"--game-names",
StringRoutines.quote("/" + processData.gameName),
"--export-csv",
StringRoutines.quote
(
"/home/" + userName + "/BenchmarkFeatures/Out/" + StringRoutines.join
(
"_",
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")),
processData.features,
processData.featureSet
) + ".csv"
),
//"--suppress-prints",
"--features-to-use",
processData.features,
"--feature-set-type",
processData.featureSet,
">",
"/home/" + userName + "/BenchmarkFeatures/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String features;
public final String featureSet;
/**
* Constructor
* @param gameName
* @param features
* @param featureSet
*/
public ProcessData(final String gameName, final String features, final String featureSet)
{
this.gameName = gameName;
this.features = features;
this.featureSet = featureSet;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating timing job scripts for playouts with atomic feature sets."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 9,848 | 27.14 | 118 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/CustomPlayoutsTimingScriptsGen.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to generate scripts for playouts timing with and without custom playouts.
*
* @author Dennis Soemers
*/
public class CustomPlayoutsTimingScriptsGen
{
/** Memory to assign per CPU, in MB */
private static final String MEM_PER_CPU = "5120";
/** Memory to assign to JVM, in MB */
private static final String JVM_MEM = "4096";
/** JVM warming up time (in seconds) */
private static final int WARMUP_TIME = 60;
/** Time over which we measure playouts (in seconds) */
private static final int MEASURE_TIME = 600;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 40;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private CustomPlayoutsTimingScriptsGen()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
//final BestBaseAgents bestBaseAgents = BestBaseAgents.loadData();
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
if (game.isStacking())
continue;
if (game.hiddenInformation())
continue;
if (!game.hasCustomPlayouts())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
for (final boolean disableCustom : new boolean[]{false, true})
{
final String experimentType = disableCustom ? "NoCustom" : "Custom";
final String jobScriptFilename = experimentType + filepathsGameName + filepathsRulesetName + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J " + experimentType + "_" + filepathsGameName + filepathsRulesetName);
writer.println("#SBATCH -o /work/" + userName + "/" + experimentType + "/Out"
+ filepathsGameName + filepathsRulesetName + "_%J.out");
writer.println("#SBATCH -e /work/" + userName + "/" + experimentType + "/Err"
+ filepathsGameName + filepathsRulesetName + "_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU);
writer.println("#SBATCH -A " + argParse.getValueString("--project"));
writer.println("unset JAVA_TOOL_OPTIONS");
String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/CustomPlayouts/Ludii.jar"),
"--time-playouts",
"--warming-up-secs",
String.valueOf(WARMUP_TIME),
"--measure-secs",
String.valueOf(MEASURE_TIME),
"--game-names",
StringRoutines.quote("/" + gameName + ".lud"),
"--ruleset",
StringRoutines.quote(fullRulesetName),
"--export-csv",
StringRoutines.quote
(
"/work/" + userName + "/" + experimentType + "/" +
filepathsGameName + filepathsRulesetName + ".csv"
),
"--suppress-prints"
);
if (disableCustom)
javaCall += " --no-custom-playouts";
writer.println(javaCall);
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates timing scripts."
);
argParse.addOption(new ArgOption()
.withNames("--project")
.help("Project for which to submit the job on cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 9,179 | 30.013514 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalDecisionTreesNormalGamesSnellius.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs
*
* @author Dennis Soemers
*/
public class EvalDecisionTreesNormalGamesSnellius
{
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 100;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 100;
/** Num trials per matchup */
private static final int NUM_TRIALS = 50;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/** Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final String[] TREE_TYPES =
new String[]
{
"BinaryClassificationTree_Playout",
"BinaryClassificationTree_TSPG",
"ImbalancedBinaryClassificationTree_Playout",
"ImbalancedBinaryClassificationTree_TSPG",
"ImbalancedBinaryClassificationTree2_Playout",
"ImbalancedBinaryClassificationTree2_TSPG",
"IQRTree_Playout",
"IQRTree_TSPG",
"LogitRegressionTree_Playout",
"LogitRegressionTree_TSPG"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
private static final String[] EXPERIMENT_TYPES = new String[] {"Greedy", "Sampling"};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalDecisionTreesNormalGamesSnellius()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("Random");
algorithms.add("CE");
algorithms.add("TSPG");
//algorithms.add("UCT");
for (final String treeType : TREE_TYPES)
{
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add(treeType + "_" + treeDepth);
}
}
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
final List<ProcessData> processDataListUCT = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(algorithms.toArray(), numPlayers));
for (final Object[] matchup : matchupsPerPlayerCount.get(numPlayers))
{
boolean includesUCT = false;
for (final Object obj : matchup)
{
final String s = (String) obj;
includesUCT = includesUCT || s.equals("UCT");
}
if (includesUCT)
{
for (final String experimentType : EXPERIMENT_TYPES)
{
processDataListUCT.add(new ProcessData(gameName, matchup, experimentType, numPlayers));
}
}
else
{
for (final String experimentType : EXPERIMENT_TYPES)
{
processDataList.add(new ProcessData(gameName, matchup, experimentType, numPlayers));
}
}
}
}
processDataList.addAll(0, processDataListUCT);
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalDecisionTrees_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalDecisionTrees");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalDecisionTrees/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalDecisionTrees/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
if (exclusive) // We're requesting full node anyway, might as well take all the cores
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
else
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final String s = (String) agent;
final String agentStr;
if (s.equals("Random"))
{
agentStr = "Random";
}
else if (s.equals("UCT"))
{
agentStr = "UCT";
}
else if (s.equals("CE") || s.equals("TSPG"))
{
final String algName = (processData.experimentType.equals("Greedy")) ? "Greedy" : "Softmax";
final String weightsFileName = (s.equals("CE")) ? "PolicyWeightsPlayout_P" : "PolicyWeightsTSPG_P";
final List<String> policyStrParts = new ArrayList<String>();
policyStrParts.add("algorithm=" + algName);
for (int p = 1; p <= processData.numPlayers; ++p)
{
policyStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
cleanGameName + "_Baseline" +
"/" + weightsFileName + p + "_00201.txt"
);
}
policyStrParts.add("friendly_name=" + s);
if (s.equals("TSPG"))
policyStrParts.add("boosted=true");
agentStr =
StringRoutines.join
(
";",
policyStrParts
);
}
else if (s.startsWith("LogitRegressionTree"))
{
agentStr =
StringRoutines.join
(
";",
"algorithm=SoftmaxPolicyLogitTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"TrainFeaturesSnellius4",
"Out",
"Trees",
cleanGameName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
else
{
agentStr =
StringRoutines.join
(
";",
"algorithm=ProportionalPolicyClassificationTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"TrainFeaturesSnellius4",
"Out",
"Trees",
cleanGameName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalDecisionTrees/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(0),
"--game-length-cap",
String.valueOf(1000),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalDecisionTrees/Out/" +
processData.experimentType + "/" +
cleanGameName +
"/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalDecisionTrees/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final Object[] matchup;
public final String experimentType;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param matchup
* @param experimentType
* @param numPlayers
*/
public ProcessData(final String gameName, final Object[] matchup, final String experimentType, final int numPlayers)
{
this.gameName = gameName;
this.matchup = matchup;
this.experimentType = experimentType;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,962 | 28.969965 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalDecisionTreesSmallGames.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalDecisionTreesSmallGames
{
/** Memory to assign to JVM */
private static final String JVM_MEM = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 10080;
/** Num trials per matchup */
private static final int NUM_TRIALS = 50;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we want to run */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] TREE_TYPES =
new String[]
{
"BinaryClassificationTree_Playout",
"BinaryClassificationTree_TSPG",
"ImbalancedBinaryClassificationTree_Playout",
"ImbalancedBinaryClassificationTree_TSPG",
"IQRTree_Playout",
"IQRTree_TSPG",
"LogitRegressionTree_Playout",
"LogitRegressionTree_TSPG"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
private static final String[] EXPERIMENT_TYPES = new String[] {"Greedy", "Sampling"};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalDecisionTreesSmallGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("Random");
for (final String treeType : TREE_TYPES)
{
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add(treeType + "_" + treeDepth);
}
}
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final String rulesetName = RULESETS[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(algorithms.toArray(), numPlayers));
for (final String experimentType : EXPERIMENT_TYPES)
{
processDataList.add(new ProcessData(gameName, rulesetName, matchupsPerPlayerCount.get(numPlayers), experimentType));
}
}
int callIdx = 0;
for (int processIdx = 0; processIdx < processDataList.size(); ++processIdx)
{
// Start a new job script
final String jobScriptFilename = "EvalDecisionTrees_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_");
for (final Object[] matchup : processData.matchups)
{
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : matchup)
{
final String s = (String) agent;
final String agentStr;
if (s.equals("Random"))
{
agentStr = "Random";
}
else if (s.startsWith("LogitRegressionTree"))
{
agentStr =
StringRoutines.join
(
";",
"algorithm=SoftmaxPolicyLogitTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"projects",
"ludi",
"Out",
"Trees",
cleanGameName + "_" + cleanRulesetName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
else
{
agentStr =
StringRoutines.join
(
";",
"algorithm=ProportionalPolicyClassificationTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"projects",
"ludi",
"Out",
"Trees",
cleanGameName + "_" + cleanRulesetName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/projects/ludi/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"--ruleset",
StringRoutines.quote(processData.rulesetName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(0),
"--game-length-cap",
String.valueOf(250),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/projects/ludi/Out/Evals/" +
processData.experimentType + "/" +
cleanGameName +
"_" +
cleanRulesetName
+
"/" +
StringRoutines.join("_", matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/projects/ludi/Out/Evals/Out_" + callIdx + ".out"
);
writer.println(javaCall);
callIdx++;
}
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "RunJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("bash " + jobScriptName + " &");
}
writer.println("wait");
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String rulesetName;
public final Object[][] matchups;
public final String experimentType;
/**
* Constructor
* @param gameName
* @param rulesetName
* @param matchups
* @param experimentType
*/
public ProcessData(final String gameName, final String rulesetName, final Object[][] matchups, final String experimentType)
{
this.gameName = gameName;
this.rulesetName = rulesetName;
this.matchups = matchups;
this.experimentType = experimentType;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 11,982 | 26.674365 | 129 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalDecisionTreesSmallGamesRWTH.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs
*
* @author Dennis Soemers
*/
public class EvalDecisionTreesSmallGamesRWTH
{
/** Memory to assign to JVM */
private static final String JVM_MEM = "4096";
/** Memory to assign per CPU, in MB */
private static final String MEM_PER_CPU = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 3000;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Num trials per matchup */
private static final int NUM_TRIALS = 50;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we want to run */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] TREE_TYPES =
new String[]
{
"BinaryClassificationTree_Playout",
"BinaryClassificationTree_TSPG",
"ImbalancedBinaryClassificationTree_Playout",
"ImbalancedBinaryClassificationTree_TSPG",
"IQRTree_Playout",
"IQRTree_TSPG",
"LogitRegressionTree_Playout",
"LogitRegressionTree_TSPG"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
private static final String[] EXPERIMENT_TYPES = new String[] {"Greedy", "Sampling"};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalDecisionTreesSmallGamesRWTH()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("Random");
algorithms.add("CE");
algorithms.add("TSPG");
algorithms.add("UCT");
for (final String treeType : TREE_TYPES)
{
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add(treeType + "_" + treeDepth);
}
}
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final String rulesetName = RULESETS[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(algorithms.toArray(), numPlayers));
// We already ran most matchups on another cluster, only still need to do the ones
// that contain at least one out of UCT, CE and TSPG
for (final Object[] matchup : matchupsPerPlayerCount.get(numPlayers))
{
boolean keep = false;
for (final Object obj : matchup)
{
final String s = (String) obj;
if (s.equals("UCT") || s.equals("CE") || s.equals("TSPG"))
{
keep = true;
break;
}
}
if (keep)
{
for (final String experimentType : EXPERIMENT_TYPES)
{
processDataList.add(new ProcessData(gameName, rulesetName, matchup, experimentType, numPlayers));
}
}
}
}
for (int processIdx = 0; processIdx < processDataList.size(); ++processIdx)
{
// Start a new job script
final String jobScriptFilename = "EvalDecisionTrees_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_");
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J Eval" + cleanGameName + cleanRulesetName);
writer.println("#SBATCH -o /work/" + userName + "/EvalSmallGames/Out/Out"
+ cleanGameName + cleanRulesetName + processData.matchup[0] + processData.matchup[1] + "_%J.out");
writer.println("#SBATCH -e /work/" + userName + "/EvalSmallGames/Out/Err"
+ cleanGameName + cleanRulesetName + processData.matchup[0] + processData.matchup[1] + "_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU);
writer.println("#SBATCH -A " + argParse.getValueString("--project"));
writer.println("unset JAVA_TOOL_OPTIONS");
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final String s = (String) agent;
final String agentStr;
if (s.equals("Random"))
{
agentStr = "Random";
}
else if (s.equals("UCT"))
{
agentStr = "UCT";
}
else if (s.equals("CE") || s.equals("TSPG"))
{
final String algName = (processData.experimentType.equals("Greedy")) ? "Greedy" : "Softmax";
final String weightsFileName = (s.equals("CE")) ? "PolicyWeightsPlayout_P" : "PolicyWeightsTSPG_P";
final List<String> policyStrParts = new ArrayList<String>();
policyStrParts.add("algorithm=" + algName);
for (int p = 1; p <= processData.numPlayers; ++p)
{
policyStrParts.add
(
"policyweights" +
p +
"=/work/" +
userName +
"/SmallGames/Out/" +
cleanGameName + "_" + cleanRulesetName +
"/" + weightsFileName + p + "_00201.txt"
);
}
policyStrParts.add("friendly_name=" + s);
if (s.equals("TSPG"))
policyStrParts.add("boosted=true");
agentStr =
StringRoutines.join
(
";",
policyStrParts
);
}
else if (s.startsWith("LogitRegressionTree"))
{
agentStr =
StringRoutines.join
(
";",
"algorithm=SoftmaxPolicyLogitTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"work",
userName,
"SmallGames",
"Out",
"Trees",
cleanGameName + "_" + cleanRulesetName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
else
{
agentStr =
StringRoutines.join
(
";",
"algorithm=ProportionalPolicyClassificationTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"work",
userName,
"SmallGames",
"Out",
"Trees",
cleanGameName + "_" + cleanRulesetName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/SmallGames/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"--ruleset",
StringRoutines.quote(processData.rulesetName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(0),
"--game-length-cap",
String.valueOf(250),
"--out-dir",
StringRoutines.quote
(
"/work/" +
userName +
"/EvalSmallGames/Out/" +
processData.experimentType + "/" +
cleanGameName +
"_" +
cleanRulesetName
+
"/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
writer.println(javaCall);
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String rulesetName;
public final Object[] matchup;
public final String experimentType;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param rulesetName
* @param matchup
* @param experimentType
* @param numPlayers
*/
public ProcessData(final String gameName, final String rulesetName, final Object[] matchup, final String experimentType, final int numPlayers)
{
this.gameName = gameName;
this.rulesetName = rulesetName;
this.matchup = matchup;
this.experimentType = experimentType;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--project")
.help("Project for which to submit the job on cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,747 | 27.361538 | 144 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalDecisionTreesSmallGamesRWTH2.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs
*
* @author Dennis Soemers
*/
public class EvalDecisionTreesSmallGamesRWTH2
{
/** Memory to assign to JVM */
private static final String JVM_MEM = "4096";
/** Memory to assign per CPU, in MB */
private static final String MEM_PER_CPU = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 3000;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Num trials per matchup */
private static final int NUM_TRIALS = 50;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Tic-Tac-Toe.lud",
"Mu Torere.lud",
"Mu Torere.lud",
"Jeu Militaire.lud",
"Pong Hau K'i.lud",
"Akidada.lud",
"Alquerque de Tres.lud",
"Ho-Bag Gonu.lud",
"Madelinette.lud",
"Haretavl.lud",
"Kaooa.lud",
"Hat Diviyan Keliya.lud",
"Three Men's Morris.lud"
};
/** Rulesets we want to run */
private static final String[] RULESETS =
new String[]
{
"",
"Ruleset/Complete (Observed)",
"Ruleset/Simple (Suggested)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
};
private static final String[] TREE_TYPES =
new String[]
{
"BinaryClassificationTree_Playout",
"BinaryClassificationTree_TSPG",
"ImbalancedBinaryClassificationTree_Playout",
"ImbalancedBinaryClassificationTree_TSPG",
"ImbalancedBinaryClassificationTree2_Playout",
"ImbalancedBinaryClassificationTree2_TSPG",
"IQRTree_Playout",
"IQRTree_TSPG",
"LogitRegressionTree_Playout",
"LogitRegressionTree_TSPG"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
private static final String[] EXPERIMENT_TYPES = new String[] {"Greedy", "Sampling"};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalDecisionTreesSmallGamesRWTH2()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i], RULESETS[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i] + " " + RULESETS[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("Random");
algorithms.add("CE");
algorithms.add("TSPG");
algorithms.add("UCT");
for (final String treeType : TREE_TYPES)
{
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add(treeType + "_" + treeDepth);
}
}
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final String rulesetName = RULESETS[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(algorithms.toArray(), numPlayers));
// We already ran most matchups on another cluster, only still need to do the ones
// that contain at least one ImbalancedBinaryClassificationTree2 agent
for (final Object[] matchup : matchupsPerPlayerCount.get(numPlayers))
{
boolean keep = false;
for (final Object obj : matchup)
{
final String s = (String) obj;
if (s.contains("ImbalancedBinaryClassificationTree2"))
{
keep = true;
break;
}
}
if (keep)
{
for (final String experimentType : EXPERIMENT_TYPES)
{
processDataList.add(new ProcessData(gameName, rulesetName, matchup, experimentType, numPlayers));
}
}
}
}
for (int processIdx = 0; processIdx < processDataList.size(); ++processIdx)
{
// Start a new job script
final String jobScriptFilename = "EvalDecisionTrees_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final String cleanRulesetName = StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_");
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J Eval" + cleanGameName + cleanRulesetName);
writer.println("#SBATCH -o /work/" + userName + "/EvalSmallGames/Out/Out"
+ cleanGameName + cleanRulesetName + processData.matchup[0] + processData.matchup[1] + "_%J.out");
writer.println("#SBATCH -e /work/" + userName + "/EvalSmallGames/Out/Err"
+ cleanGameName + cleanRulesetName + processData.matchup[0] + processData.matchup[1] + "_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU);
writer.println("#SBATCH -A " + argParse.getValueString("--project"));
writer.println("unset JAVA_TOOL_OPTIONS");
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final String s = (String) agent;
final String agentStr;
if (s.equals("Random"))
{
agentStr = "Random";
}
else if (s.equals("UCT"))
{
agentStr = "UCT";
}
else if (s.equals("CE") || s.equals("TSPG"))
{
final String algName = (processData.experimentType.equals("Greedy")) ? "Greedy" : "Softmax";
final String weightsFileName = (s.equals("CE")) ? "PolicyWeightsPlayout_P" : "PolicyWeightsTSPG_P";
final List<String> policyStrParts = new ArrayList<String>();
policyStrParts.add("algorithm=" + algName);
for (int p = 1; p <= processData.numPlayers; ++p)
{
policyStrParts.add
(
"policyweights" +
p +
"=/work/" +
userName +
"/SmallGames/Out/" +
cleanGameName + "_" + cleanRulesetName +
"/" + weightsFileName + p + "_00201.txt"
);
}
policyStrParts.add("friendly_name=" + s);
if (s.equals("TSPG"))
policyStrParts.add("boosted=true");
agentStr =
StringRoutines.join
(
";",
policyStrParts
);
}
else if (s.startsWith("LogitRegressionTree"))
{
agentStr =
StringRoutines.join
(
";",
"algorithm=SoftmaxPolicyLogitTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"work",
userName,
"SmallGames",
"Out",
"Trees",
cleanGameName + "_" + cleanRulesetName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
else
{
agentStr =
StringRoutines.join
(
";",
"algorithm=ProportionalPolicyClassificationTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"work",
userName,
"SmallGames",
"Out",
"Trees",
cleanGameName + "_" + cleanRulesetName,
s + ".txt"
),
"friendly_name=" + s,
"greedy=" + ((processData.experimentType.equals("Greedy")) ? "true" : "false")
);
}
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/SmallGames2/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"--ruleset",
StringRoutines.quote(processData.rulesetName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(0),
"--game-length-cap",
String.valueOf(250),
"--out-dir",
StringRoutines.quote
(
"/work/" +
userName +
"/EvalSmallGames/Out/" +
processData.experimentType + "/" +
cleanGameName +
"_" +
cleanRulesetName
+
"/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
writer.println(javaCall);
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String rulesetName;
public final Object[] matchup;
public final String experimentType;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param rulesetName
* @param matchup
* @param experimentType
* @param numPlayers
*/
public ProcessData(final String gameName, final String rulesetName, final Object[] matchup, final String experimentType, final int numPlayers)
{
this.gameName = gameName;
this.rulesetName = rulesetName;
this.matchup = matchup;
this.experimentType = experimentType;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--project")
.help("Project for which to submit the job on cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,863 | 27.475096 | 144 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalMCTSDecisionTreesNormalGamesMulticlassSnellius.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of MCTS + decision trees (with multiclass instead of logit trees)
*
* @author Dennis Soemers
*/
public class EvalMCTSDecisionTreesNormalGamesMulticlassSnellius
{
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 100;
/** Num trials per matchup */
private static final int NUM_TRIALS = 150;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 224;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/** Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalMCTSDecisionTreesNormalGamesMulticlassSnellius()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("FullPolicy");
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add("Tree_" + treeDepth);
}
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
for (final String algorithm : algorithms)
{
processDataList.add(new ProcessData(gameName, algorithm, numPlayers));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalMCTSDecisionTreesMulticlass_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalMCTSDecisionTreesMulticlass");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalMCTSDecisionTreesMulticlass/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalMCTSDecisionTreesMulticlass/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
if (exclusive) // We're requesting full node anyway, might as well take all the cores
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
else
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G");
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// Load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final List<String> agentStrings = new ArrayList<String>();
final String evalAgent = processData.evalAgent;
// Build the agent to be evaluated
if (evalAgent.equals("FullPolicy"))
{
// MCTS with full policy
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=FullPolicy"
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
else
{
// MCTS with decision tree
final int treeDepth = Integer.parseInt(evalAgent.substring("Tree_".length()));
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=classificationtreepolicy");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"TrainFeaturesSnellius4",
"Out",
"Trees",
cleanGameName,
"IQRTree_Playout_" + treeDepth + ".txt"
)
+ "," +
"greedy=false"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=playout");
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection", // Noisy variant here because we're using playout policy in selection
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + evalAgent
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
// Evaluate everything against UCT
agentStrings.add(StringRoutines.quote("UCT"));
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalMCTSDecisionTreesMulticlass/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(30),
"--game-length-cap",
String.valueOf(1000),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalMCTSDecisionTreesMulticlass/Out/" +
cleanGameName +
"/" +
processData.evalAgent
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalMCTSDecisionTreesMulticlass/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String evalAgent;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param evalAgent
* @param numPlayers
*/
public ProcessData(final String gameName, final String evalAgent, final int numPlayers)
{
this.gameName = gameName;
this.evalAgent = evalAgent;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,690 | 29.569597 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalMCTSDecisionTreesNormalGamesSnellius.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of MCTS + decision trees
*
* @author Dennis Soemers
*/
public class EvalMCTSDecisionTreesNormalGamesSnellius
{
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 100;
/** Num trials per matchup */
private static final int NUM_TRIALS = 150;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/** Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalMCTSDecisionTreesNormalGamesSnellius()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("FullPolicy");
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add("Tree_" + treeDepth);
}
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
for (final String algorithm : algorithms)
{
processDataList.add(new ProcessData(gameName, algorithm, numPlayers));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalMCTSDecisionTrees_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalMCTSDecisionTrees");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalMCTSDecisionTrees/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalMCTSDecisionTrees/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
if (exclusive) // We're requesting full node anyway, might as well take all the cores
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
else
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final List<String> agentStrings = new ArrayList<String>();
final String evalAgent = processData.evalAgent;
// Build the agent to be evaluated
if (evalAgent.equals("FullPolicy"))
{
// MCTS with full policy
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=FullPolicy"
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
else
{
// MCTS with decision tree
final int treeDepth = Integer.parseInt(evalAgent.substring("Tree_".length()));
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmaxlogittree");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"TrainFeaturesSnellius4",
"Out",
"Trees",
cleanGameName,
"LogitRegressionTree_Playout_" + treeDepth + ".txt"
)
+ "," +
"greedy=false"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=playout");
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection", // noisy variant here because we're using playout policy in selection
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + evalAgent
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
// Evaluate everything against UCT
agentStrings.add(StringRoutines.quote("UCT"));
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalMCTSDecisionTrees/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(30),
"--game-length-cap",
String.valueOf(1000),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalMCTSDecisionTrees/Out/" +
cleanGameName +
"/" +
processData.evalAgent
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalMCTSDecisionTrees/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String evalAgent;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param evalAgent
* @param numPlayers
*/
public ProcessData(final String gameName, final String evalAgent, final int numPlayers)
{
this.gameName = gameName;
this.evalAgent = evalAgent;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,594 | 29.393773 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalMCTSDecisionTreesNormalGamesSnellius_50its.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of MCTS + decision trees
*
* @author Dennis Soemers
*/
public class EvalMCTSDecisionTreesNormalGamesSnellius_50its
{
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 100;
/** Num trials per matchup */
private static final int NUM_TRIALS = 150;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/** Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalMCTSDecisionTreesNormalGamesSnellius_50its()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("FullPolicy");
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add("Tree_" + treeDepth);
}
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
for (final String algorithm : algorithms)
{
processDataList.add(new ProcessData(gameName, algorithm, numPlayers));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalMCTSDecisionTrees50its_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalMCTSDecisionTrees50its");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalMCTSDecisionTrees50its/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalMCTSDecisionTrees50its/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
if (exclusive) // We're requesting full node anyway, might as well take all the cores
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
else
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final List<String> agentStrings = new ArrayList<String>();
final String evalAgent = processData.evalAgent;
// Build the agent to be evaluated
if (evalAgent.equals("FullPolicy"))
{
// MCTS with full policy
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=FullPolicy"
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
else
{
// MCTS with decision tree
final int treeDepth = Integer.parseInt(evalAgent.substring("Tree_".length()));
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmaxlogittree");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"TrainFeaturesSnellius4",
"Out",
"Trees",
cleanGameName,
"LogitRegressionTree_Playout_" + treeDepth + ".txt"
)
+ "," +
"greedy=false"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=playout");
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection", // noisy variant here because we're using playout policy in selection
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + evalAgent
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
// Evaluate everything against UCT
agentStrings.add(StringRoutines.quote("UCT"));
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalMCTSDecisionTrees50its/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time -1",
"--iteration-limit 50",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(30),
"--game-length-cap",
String.valueOf(1000),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalMCTSDecisionTrees50its/Out/" +
cleanGameName +
"/" +
processData.evalAgent
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalMCTSDecisionTrees50its/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String evalAgent;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param evalAgent
* @param numPlayers
*/
public ProcessData(final String gameName, final String evalAgent, final int numPlayers)
{
this.gameName = gameName;
this.evalAgent = evalAgent;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,674 | 29.484461 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalMCTSDecisionTreesVsSmallestSet.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of MCTS + decision trees against
* MCTS + "smallest set" of features
*
* @author Dennis Soemers
*/
public class EvalMCTSDecisionTreesVsSmallestSet
{
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 100;
/** Num trials per matchup */
private static final int NUM_TRIALS = 150;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/** Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
//"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
private static final int[] TREE_DEPTHS = new int[] {1, 2, 3, 4, 5, 10};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalMCTSDecisionTreesVsSmallestSet()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// All the "algorithms" we want to evaluate
final List<String> algorithms = new ArrayList<String>();
algorithms.add("FullPolicy");
algorithms.add("SmallestSet");
for (final int treeDepth : TREE_DEPTHS)
{
algorithms.add("Tree_" + treeDepth);
}
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
for (final String algorithm : algorithms)
{
processDataList.add(new ProcessData(gameName, algorithm, numPlayers));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalMCTSFeature_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalMCTSFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalMCTSFeatures/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalMCTSFeatures/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
if (exclusive) // We're requesting full node anyway, might as well take all the cores
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
else
writer.println("#SBATCH --cpus-per-task=" + CORES_PER_NODE);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String cleanGameName = StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""));
final List<String> agentStrings = new ArrayList<String>();
final String evalAgent = processData.evalAgent;
// Build the agent to be evaluated
if (evalAgent.equals("FullPolicy"))
{
// MCTS with full policy
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_Baseline" +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=FullPolicy"
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
else if (evalAgent.equals("SmallestSet"))
{
// MCTS with full policy
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
playoutStrParts.add
(
"featuresmetadata=/home/" +
userName +
"/IdentifyTopFeatures/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"/BestFeatures.txt"
);
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=playout");
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=SmallestSet"
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
else
{
// MCTS with decision tree
final int treeDepth = Integer.parseInt(evalAgent.substring("Tree_".length()));
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmaxlogittree");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
userName,
"TrainFeaturesSnellius4",
"Out",
"Trees",
cleanGameName,
"LogitRegressionTree_Playout_" + treeDepth + ".txt"
)
+ "," +
"greedy=false"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=playout");
final String evalAgentString =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection", // noisy variant here because we're using playout policy in selection
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + evalAgent
);
agentStrings.add(StringRoutines.quote(evalAgentString));
}
// Evaluate everything against UCT
agentStrings.add(StringRoutines.quote("UCT"));
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalMCTSFeatures/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--warming-up-secs",
String.valueOf(30),
"--game-length-cap",
String.valueOf(1000),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalMCTSFeatures/Out/" +
cleanGameName +
"/" +
processData.evalAgent
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalMCTSFeatures/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"2>",
"/home/" + userName + "/EvalMCTSFeatures/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String evalAgent;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param evalAgent
* @param numPlayers
*/
public ProcessData(final String gameName, final String evalAgent, final int numPlayers)
{
this.gameName = gameName;
this.evalAgent = evalAgent;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 17,962 | 29.342905 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesCorrConfIntervalsScriptsGen.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesCorrConfIntervalsScriptsGen
{
/** Memory to assign per CPU, in MB */
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */
private static final String JVM_MEM = "4096";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 1440;
/** We get 24 cores per job; we'll give 2 cores per process */
private static final int PROCESSES_PER_JOB = 12;
/** Only run on the Haswell nodes */
private static final String PROCESSOR = "haswell";
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Amazons.lud",
"ArdRi.lud",
"Breakthrough.lud",
"English Draughts.lud",
"Fanorona.lud",
"Gomoku.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Reversi.lud",
"Yavalath.lud"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesCorrConfIntervalsScriptsGen()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (final String gameName : GAMES)
{
// Sanity check: make sure game with this name loads correctly
System.out.println("gameName = " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName);
processDataList.add(new ProcessData(gameName));
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesCorrConfIntervals/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesCorrConfIntervals/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --constraint=" + PROCESSOR);
// load Java modules
writer.println("module load 2020");
writer.println("module load Java/1.8.0_261");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String agentToEval =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
"playout=softmax",
"policyweights1=/home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_With/PolicyWeightsCE_P1_00201.txt",
"policyweights2=/home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_With/PolicyWeightsCE_P2_00201.txt"
),
"tree_reuse=true",
"num_threads=2",
"final_move=robustchild",
"learned_selection_policy=playout",
"friendly_name=With"
);
final String opponent =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
"playout=softmax",
"policyweights1=/home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_Without/PolicyWeightsCE_P1_00201.txt",
"policyweights2=/home/" + userName + "/TrainFeaturesCorrConfIntervals/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_Without/PolicyWeightsCE_P2_00201.txt"
),
"tree_reuse=true",
"num_threads=2",
"final_move=robustchild",
"learned_selection_policy=playout",
"friendly_name=Without"
);
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesCorrConfIntervals/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n 150",
"--thinking-time 1",
"--agents",
StringRoutines.quote(agentToEval),
StringRoutines.quote(opponent),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesCorrConfIntervals/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/"
),
"--output-summary",
"--output-alpha-rank-data",
">",
"/home/" + userName + "/EvalFeaturesCorrConfIntervals/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
/**
* Constructor
* @param gameName
*/
public ProcessData(final String gameName)
{
this.gameName = gameName;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 9,848 | 29.586957 | 218 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesFeatureSetImpls.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs with different
* feature set implementations.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesFeatureSetImpls
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
//private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 100;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Kensington.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] FEATURE_SETS =
new String[]
{
"JITSPatterNet",
"SPatterNet",
"Tree",
"Naive"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesFeatureSetImpls()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
final int maxMatchupsPerGame = ListUtils.numCombinationsWithReplacement(FEATURE_SETS.length, 3);
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(FEATURE_SETS, numPlayers));
if (matchupsPerPlayerCount.get(numPlayers).length > maxMatchupsPerGame)
{
// Too many matchups: remove some of them
final TIntArrayList indicesToKeep = new TIntArrayList(matchupsPerPlayerCount.get(numPlayers).length);
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
indicesToKeep.add(i);
}
while (indicesToKeep.size() > maxMatchupsPerGame)
{
ListUtils.removeSwap(indicesToKeep, ThreadLocalRandom.current().nextInt(indicesToKeep.size()));
}
final Object[][] newMatchups = new Object[maxMatchupsPerGame][numPlayers];
for (int i = 0; i < newMatchups.length; ++i)
{
newMatchups[i] = matchupsPerPlayerCount.get(numPlayers)[indicesToKeep.getQuick(i)];
}
matchupsPerPlayerCount.set(numPlayers, newMatchups);
}
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
processDataList.add(new ProcessData(gameName, numPlayers, matchupsPerPlayerCount.get(numPlayers)[i]));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatureSetImpls_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatureSetImpls");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeatureSetImpls/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeatureSetImpls/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
//Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeatures/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"/PolicyWeightsCE_P" + p + "_00201.txt"
);
}
playoutStrParts.add("implementation=" + (String)agent);
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeatures/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"/PolicyWeightsCE_P" + p + "_00201.txt"
);
learnedSelectionStrParts.add("implementation=" + (String)agent);
}
final String agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=3",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + (String)agent
);
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 3), String.valueOf(numJobProcesses * 3 + 1), String.valueOf(numJobProcesses * 3 + 2)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeatureSetImpls/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeatureSetImpls/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeatureSetImpls/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"2>",
"/home/" + userName + "/EvalFeatureSetImpls/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final Object[] matchup;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param matchup
*/
public ProcessData(final String gameName, final int numPlayers, final Object[] matchup)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.matchup = matchup;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,280 | 30.923529 | 152 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesFinalStatesBuffersScriptsGen.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* --final-states-buffers.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesFinalStatesBuffersScriptsGen
{
/** Memory to assign per CPU, in MB */
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */
private static final String JVM_MEM = "4096";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 1440;
/** We get 24 cores per job; we'll give 2 cores per process */
private static final int PROCESSES_PER_JOB = 12;
/** Only run on the Haswell nodes */
private static final String PROCESSOR = "haswell";
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Amazons.lud",
"ArdRi.lud",
"Breakthrough.lud",
"English Draughts.lud",
"Fanorona.lud",
"Gomoku.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Reversi.lud",
"Yavalath.lud"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesFinalStatesBuffersScriptsGen()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (final String gameName : GAMES)
{
// Sanity check: make sure game with this name loads correctly
System.out.println("gameName = " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName);
processDataList.add(new ProcessData(gameName));
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesFinalStatesBuffers/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesFinalStatesBuffers/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --constraint=" + PROCESSOR);
// load Java modules
writer.println("module load 2020");
writer.println("module load Java/1.8.0_261");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final String agentToEval =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
"playout=softmax",
"policyweights1=/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_With/PolicyWeightsCE_P1_00201.txt",
"policyweights2=/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_With/PolicyWeightsCE_P2_00201.txt"
),
"tree_reuse=true",
"num_threads=2",
"final_move=robustchild",
"learned_selection_policy=playout",
"friendly_name=With"
);
final String opponent =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
"playout=softmax",
"policyweights1=/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_Without/PolicyWeightsCE_P1_00201.txt",
"policyweights2=/home/" + userName + "/TrainFeaturesFinalStatesBuffers/Out/" + StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "_Without/PolicyWeightsCE_P2_00201.txt"
),
"tree_reuse=true",
"num_threads=2",
"final_move=robustchild",
"learned_selection_policy=playout",
"friendly_name=Without"
);
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesFinalStatesBuffers/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n 150",
"--thinking-time 1",
"--agents",
StringRoutines.quote(agentToEval),
StringRoutines.quote(opponent),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesFinalStatesBuffers/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/"
),
"--output-summary",
"--output-alpha-rank-data",
">",
"/home/" + userName + "/EvalFeaturesFinalStatesBuffers/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
/**
* Constructor
* @param gameName
*/
public ProcessData(final String gameName)
{
this.gameName = gameName;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 9,829 | 29.52795 | 219 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesSnellius.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ListUtils;
import other.GameLoader;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesSnellius
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 100;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
"TournamentMode",
"Reinforce",
"ReinforceZero",
"ReinforceOne",
"SpecialMovesExpander",
"All"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesSnellius()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
final int maxMatchupsPerGame = ListUtils.numCombinationsWithReplacement(VARIANTS.length, 3);
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (final String gameName : GAMES)
{
// Sanity check: make sure game with this name loads correctly
System.out.println("gameName = " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName);
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(VARIANTS, numPlayers));
if (matchupsPerPlayerCount.get(numPlayers).length > maxMatchupsPerGame)
{
// Too many matchups: remove some of them
final TIntArrayList indicesToKeep = new TIntArrayList(matchupsPerPlayerCount.get(numPlayers).length);
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
indicesToKeep.add(i);
}
while (indicesToKeep.size() > maxMatchupsPerGame)
{
ListUtils.removeSwap(indicesToKeep, ThreadLocalRandom.current().nextInt(indicesToKeep.size()));
}
final Object[][] newMatchups = new Object[maxMatchupsPerGame][numPlayers];
for (int i = 0; i < newMatchups.length; ++i)
{
newMatchups[i] = matchupsPerPlayerCount.get(numPlayers)[indicesToKeep.getQuick(i)];
}
matchupsPerPlayerCount.set(numPlayers, newMatchups);
}
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
processDataList.add(new ProcessData(gameName, numPlayers, matchupsPerPlayerCount.get(numPlayers)[i]));
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesSnellius/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesSnellius/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=2",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + (String)agent
);
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesSnellius/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeaturesSnellius/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final Object[] matchup;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param matchup
*/
public ProcessData(final String gameName, final int numPlayers, final Object[] matchup)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.matchup = matchup;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,571 | 30.136752 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesSnellius2.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesSnellius2
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 100;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
"ReinforceGamma1",
"ReinforceGamma099",
"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
"SignCorrelationExpander",
"RandomExpander",
//"All"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesSnellius2()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
final int maxMatchupsPerGame = ListUtils.numCombinationsWithReplacement(VARIANTS.length, 3);
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(VARIANTS, numPlayers));
if (matchupsPerPlayerCount.get(numPlayers).length > maxMatchupsPerGame)
{
// Too many matchups: remove some of them
final TIntArrayList indicesToKeep = new TIntArrayList(matchupsPerPlayerCount.get(numPlayers).length);
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
indicesToKeep.add(i);
}
while (indicesToKeep.size() > maxMatchupsPerGame)
{
ListUtils.removeSwap(indicesToKeep, ThreadLocalRandom.current().nextInt(indicesToKeep.size()));
}
final Object[][] newMatchups = new Object[maxMatchupsPerGame][numPlayers];
for (int i = 0; i < newMatchups.length; ++i)
{
newMatchups[i] = matchupsPerPlayerCount.get(numPlayers)[indicesToKeep.getQuick(i)];
}
matchupsPerPlayerCount.set(numPlayers, newMatchups);
}
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
processDataList.add(new ProcessData(gameName, numPlayers, matchupsPerPlayerCount.get(numPlayers)[i]));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesSnellius/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesSnellius/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=2",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + (String)agent
);
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesSnellius/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeaturesSnellius/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final Object[] matchup;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param matchup
*/
public ProcessData(final String gameName, final int numPlayers, final Object[] matchup)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.matchup = matchup;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,099 | 30.445313 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesSnellius3.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesSnellius3
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 100;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
"ReinforceGamma1",
"ReinforceGamma099",
//"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
//"SignCorrelationExpander",
//"RandomExpander",
//"All"
"NoHandleAliasing",
"HandleAliasingPlayouts"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesSnellius3()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
final int maxMatchupsPerGame = ListUtils.numCombinationsWithReplacement(VARIANTS.length, 3);
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(VARIANTS, numPlayers));
if (matchupsPerPlayerCount.get(numPlayers).length > maxMatchupsPerGame)
{
// Too many matchups: remove some of them
final TIntArrayList indicesToKeep = new TIntArrayList(matchupsPerPlayerCount.get(numPlayers).length);
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
indicesToKeep.add(i);
}
while (indicesToKeep.size() > maxMatchupsPerGame)
{
ListUtils.removeSwap(indicesToKeep, ThreadLocalRandom.current().nextInt(indicesToKeep.size()));
}
final Object[][] newMatchups = new Object[maxMatchupsPerGame][numPlayers];
for (int i = 0; i < newMatchups.length; ++i)
{
newMatchups[i] = matchupsPerPlayerCount.get(numPlayers)[indicesToKeep.getQuick(i)];
}
matchupsPerPlayerCount.set(numPlayers, newMatchups);
}
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
processDataList.add(new ProcessData(gameName, numPlayers, matchupsPerPlayerCount.get(numPlayers)[i]));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesSnellius3/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesSnellius3/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius3/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius3/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=2",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + (String)agent
);
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesSnellius3/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesSnellius3/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeaturesSnellius3/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final Object[] matchup;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param matchup
*/
public ProcessData(final String gameName, final int numPlayers, final Object[] matchup)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.matchup = matchup;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,182 | 30.423301 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesSnellius4.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesSnellius4
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 100;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
//"ReinforceGamma1",
//"ReinforceGamma099",
//"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
//"SignCorrelationExpander",
//"RandomExpander",
//"All"
"NoHandleAliasing",
"HandleAliasingPlayouts",
"NoWED",
"NoPER"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesSnellius4()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
final int maxMatchupsPerGame = ListUtils.numCombinationsWithReplacement(VARIANTS.length, 3);
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(VARIANTS, numPlayers));
if (matchupsPerPlayerCount.get(numPlayers).length > maxMatchupsPerGame)
{
// Too many matchups: remove some of them
final TIntArrayList indicesToKeep = new TIntArrayList(matchupsPerPlayerCount.get(numPlayers).length);
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
indicesToKeep.add(i);
}
while (indicesToKeep.size() > maxMatchupsPerGame)
{
ListUtils.removeSwap(indicesToKeep, ThreadLocalRandom.current().nextInt(indicesToKeep.size()));
}
final Object[][] newMatchups = new Object[maxMatchupsPerGame][numPlayers];
for (int i = 0; i < newMatchups.length; ++i)
{
newMatchups[i] = matchupsPerPlayerCount.get(numPlayers)[indicesToKeep.getQuick(i)];
}
matchupsPerPlayerCount.set(numPlayers, newMatchups);
}
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
processDataList.add(new ProcessData(gameName, numPlayers, matchupsPerPlayerCount.get(numPlayers)[i]));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesSnellius4/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesSnellius4/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + (String)agent +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=2",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + (String)agent
);
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesSnellius4/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeaturesSnellius4/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final Object[] matchup;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param matchup
*/
public ProcessData(final String gameName, final int numPlayers, final Object[] matchup)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.matchup = matchup;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,213 | 30.361702 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesSnellius4Reinforce.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesSnellius4Reinforce
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 100;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
//"ReinforceGamma1",
//"ReinforceGamma099",
//"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
//"SignCorrelationExpander",
//"RandomExpander",
//"All"
"NoHandleAliasing",
"HandleAliasingPlayouts",
"NoWED",
"NoPER"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesSnellius4Reinforce()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
if (numPlayers != 2)
System.err.println("ERROR! Only expected 2-player games!");
for (final String opponent : VARIANTS)
{
processDataList.add(new ProcessData(gameName, numPlayers, opponent));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeaturesReinforce_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesSnellius4/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesSnellius4/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
final String[] matchup = new String[] {"ReinforceOnly", processData.opponent};
for (final String agent : matchup)
{
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + agent +
"/PolicyWeightsPlayout_P" + p + "_00201.txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + agent +
"/PolicyWeightsSelection_P" + p + "_00201.txt"
);
}
final String agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"use_score_bounds=true",
"num_threads=2",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + agent
);
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesSnellius4/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--thinking-time 1",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeaturesSnellius4/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitReinforceOnlyJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final String opponent;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param opponent
*/
public ProcessData(final String gameName, final int numPlayers, final String opponent)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.opponent = opponent;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,769 | 29.57971 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedFeaturesSnelliusImportanceSampling.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.collections.ListUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Script to generate scripts for evaluation of training runs with vs. without
* conf intervals on correlations for feature discovery.
*
* @author Dennis Soemers
*/
public class EvalTrainedFeaturesSnelliusImportanceSampling
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 2 cores per job, 4GB per job, use 3GB for JVM) */
private static final String JVM_MEM = "3072";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 4;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int NUM_TRIALS = 120;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Number of cores per Java call */
private static final int CORES_PER_PROCESS = 2;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Amazons.lud",
"ArdRi.lud",
"Breakthrough.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Gomoku.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
"Pentalath.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Tablut.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] AGENTS =
new String[]
{
"UCT",
"MC-GRAVE",
"MAST",
"NST",
"Biased-00000-None",
"Biased-00050-None",
"Biased-00100-None",
"Biased-00150-None",
"Biased-00199-None",
"Biased-00000-EpisodeDurations",
"Biased-00050-EpisodeDurations",
"Biased-00100-EpisodeDurations",
"Biased-00150-EpisodeDurations",
"Biased-00199-EpisodeDurations",
"Biased-00000-PER",
"Biased-00050-PER",
"Biased-00100-PER",
"Biased-00150-PER",
"Biased-00199-PER",
"Biased-00000-All",
"Biased-00050-All",
"Biased-00100-All",
"Biased-00150-All",
"Biased-00199-All"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedFeaturesSnelliusImportanceSampling()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
final List<Object[][]> matchupsPerPlayerCount = new ArrayList<Object[][]>();
final int maxMatchupsPerGame = ListUtils.numCombinationsWithReplacement(AGENTS.length, 3);
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
final int numPlayers = game.players().count();
// Check if we already have a matrix of matchup-lists for this player count
while (matchupsPerPlayerCount.size() <= numPlayers)
{
matchupsPerPlayerCount.add(null);
}
if (matchupsPerPlayerCount.get(numPlayers) == null)
matchupsPerPlayerCount.set(numPlayers, ListUtils.generateCombinationsWithReplacement(AGENTS, numPlayers));
if (matchupsPerPlayerCount.get(numPlayers).length > maxMatchupsPerGame)
{
// Too many matchups: remove some of them
final TIntArrayList indicesToKeep = new TIntArrayList(matchupsPerPlayerCount.get(numPlayers).length);
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
indicesToKeep.add(i);
}
while (indicesToKeep.size() > maxMatchupsPerGame)
{
ListUtils.removeSwap(indicesToKeep, ThreadLocalRandom.current().nextInt(indicesToKeep.size()));
}
final Object[][] newMatchups = new Object[maxMatchupsPerGame][numPlayers];
for (int i = 0; i < newMatchups.length; ++i)
{
newMatchups[i] = matchupsPerPlayerCount.get(numPlayers)[indicesToKeep.getQuick(i)];
}
matchupsPerPlayerCount.set(numPlayers, newMatchups);
}
for (int i = 0; i < matchupsPerPlayerCount.get(numPlayers).length; ++i)
{
processDataList.add(new ProcessData(gameName, numPlayers, matchupsPerPlayerCount.get(numPlayers)[i]));
}
}
long totalRequestedCoreHours = 0L;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "EvalFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J EvalFeaturesImportanceSampling");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/EvalFeaturesIS/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/EvalFeaturesIS/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
totalRequestedCoreHours += (CORES_PER_NODE * (MAX_WALL_TIME / 60));
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
final List<String> agentStrings = new ArrayList<String>();
for (final Object agent : processData.matchup)
{
final String agentAsStr = (String) agent;
final String agentStr;
if (agentAsStr.startsWith("Biased"))
{
final String[] agentStrSplit = agentAsStr.split(Pattern.quote("-"));
String checkpointStr = agentStrSplit[1];
if (checkpointStr.equals("00199"))
checkpointStr = "00201";
final String importanceSamplingType = agentStrSplit[2];
final List<String> playoutStrParts = new ArrayList<String>();
playoutStrParts.add("playout=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
playoutStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesIS/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + importanceSamplingType +
"/PolicyWeightsPlayout_P" + p + "_" + checkpointStr + ".txt"
);
}
final List<String> learnedSelectionStrParts = new ArrayList<String>();
learnedSelectionStrParts.add("learned_selection_policy=softmax");
for (int p = 1; p <= processData.numPlayers; ++p)
{
learnedSelectionStrParts.add
(
"policyweights" +
p +
"=/home/" +
userName +
"/TrainFeaturesIS/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) +
"_" + importanceSamplingType +
"/PolicyWeightsSelection_P" + p + "_" + checkpointStr + ".txt"
);
}
agentStr =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ag0selection",
StringRoutines.join
(
",",
playoutStrParts
),
"tree_reuse=true",
"num_threads=2",
"final_move=robustchild",
StringRoutines.join
(
",",
learnedSelectionStrParts
),
"friendly_name=" + (String)agent
);
}
else
{
agentStr = agentAsStr;
}
agentStrings.add(StringRoutines.quote(agentStr));
}
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific cores to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalFeaturesIS/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n " + NUM_TRIALS,
"--iteration-limit 800",
"--agents",
StringRoutines.join(" ", agentStrings),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/EvalFeaturesIS/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/" +
StringRoutines.join("_", processData.matchup)
),
"--output-summary",
"--output-alpha-rank-data",
"--game-length-cap 500",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/EvalFeaturesIS/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"2>",
"/home/" + userName + "/EvalFeaturesIS/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total requested core hours = " + totalRequestedCoreHours);
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final Object[] matchup;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param matchup
*/
public ProcessData(final String gameName, final int numPlayers, final Object[] matchup)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.matchup = matchup;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating eval job scripts."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,908 | 30.605607 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/EvalTrainedLudusScriptsGen.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Script to generate scripts for ExIt training runs for various
* Ludus Latrunculorum rulesets.
*
* @author Dennis Soemers
*/
public class EvalTrainedLudusScriptsGen
{
/** Memory to assign per CPU, in MB */
private static final String MEM_PER_CPU = "5120";
/** Memory to assign to JVM, in MB */
private static final String JVM_MEM = "4096";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 3600;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Games and rulesets we want to use */
private static final String[][] GAMES_RULESETS = new String[][]
{
{"/Ludus Latrunculorum.lud", "Ruleset/6x6 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/6x6 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/6x7 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/6x7 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/6x8 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/6x8 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/7x8 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/7x8 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/8x8 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/8x8 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/8x9 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/8x9 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/10x10 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/10x10 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/11x16 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/11x16 (Kharebga Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/9x10 (Seega Rules) (Suggested)"},
{"/Ludus Latrunculorum.lud", "Ruleset/9x10 (Kharebga Rules) (Suggested)"},
{"/Poprad Game.lud", "Ruleset/17x17 (Seega Rules) (Suggested)"},
{"/Poprad Game.lud", "Ruleset/17x17 (Kharebga Rules) (Suggested)"},
{"/Poprad Game.lud", "Ruleset/17x17 (Tablut Rules) (Suggested)"},
{"/Poprad Game.lud", "Ruleset/17x18 (Seega Rules) (Suggested)"},
{"/Poprad Game.lud", "Ruleset/17x18 (Kharebga Rules) (Suggested)"},
{"/Poprad Game.lud", "Ruleset/17x17 (Tablut Rules More Pieces) (Suggested)"},
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private EvalTrainedLudusScriptsGen()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
for (final String[] gameRulesetArray : GAMES_RULESETS)
{
final Game game = GameLoader.loadGameFromName(gameRulesetArray[0], gameRulesetArray[1]);
if (game == null)
System.err.println("ERROR! Failed to compile " + gameRulesetArray[0] + ", " + gameRulesetArray[1]);
final String filepathsGameName = StringRoutines.cleanGameName(gameRulesetArray[0].replaceAll(Pattern.quote("/"), ""));
final String filepathsRulesetName = StringRoutines.cleanRulesetName(gameRulesetArray[1].replaceAll(Pattern.quote("Ruleset/"), ""));
final String agentToEval =
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=noisyag0selection",
"playout=random,playoutturnlimit=0",
"tree_reuse=true",
StringRoutines.join
(
",",
"learned_selection_policy=softmax",
"policyweights1=/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/PolicyWeightsCE_P1_00201.txt",
"policyweights2=/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/PolicyWeightsCE_P2_00201.txt"
),
"heuristics=value-func-dir-/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/",
"friendly_name=Trained"
);
final List<String> opponentAgents = new ArrayList<String>();
final List<String> opponentAgentShortNames = new ArrayList<String>();
opponentAgents.add("UCT");
opponentAgentShortNames.add("UCT");
opponentAgents.add
(
StringRoutines.join
(
";",
"algorithm=AlphaBeta",
"heuristics=value-func-dir-/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/"
)
);
opponentAgentShortNames.add("AlphaBeta");
opponentAgents.add
(
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ucb1",
"playout=random,playoutturnlimit=0",
"tree_reuse=true",
"heuristics=/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/ValueFunction_00000.txt",
"friendly_name=AlphaBeta"
)
);
opponentAgentShortNames.add("Untrained");
opponentAgents.add
(
StringRoutines.join
(
";",
"algorithm=MCTS",
"selection=ucb1",
"playout=random,playoutturnlimit=0",
"tree_reuse=true",
"heuristics=value-func-dir-/work/" + userName + "/TrainLudus/" + filepathsGameName + filepathsRulesetName + "/",
"friendly_name=Untrained"
)
);
opponentAgentShortNames.add("NoFeatures");
for (int oppIdx = 0; oppIdx < opponentAgents.size(); ++oppIdx)
{
final String jobScriptFilename =
"EvalTrainedLudus" + filepathsGameName + filepathsRulesetName +
"_vs_" + opponentAgentShortNames.get(oppIdx) + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J EvalTrainedLudus_" + filepathsGameName + filepathsRulesetName);
writer.println("#SBATCH -o /work/" + userName + "/EvalTrainedLudus/Out"
+ filepathsGameName + filepathsRulesetName + "_vs_" + opponentAgentShortNames.get(oppIdx) + "_%J.out");
writer.println("#SBATCH -e /work/" + userName + "/EvalTrainedLudus/Err"
+ filepathsGameName + filepathsRulesetName + "_vs_" + opponentAgentShortNames.get(oppIdx) + "_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU);
writer.println("#SBATCH -A " + argParse.getValueString("--project"));
writer.println("unset JAVA_TOOL_OPTIONS");
final String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/EvalTrainedLudus/Ludii.jar"),
"--eval-agents",
"--game",
StringRoutines.quote(gameRulesetArray[0]),
"--ruleset",
StringRoutines.quote(gameRulesetArray[1]),
"--agents",
StringRoutines.quote(agentToEval),
StringRoutines.quote(opponentAgents.get(oppIdx)),
"-n 100",
"--thinking-time 1.1",
"--out-dir",
StringRoutines.quote
(
"/work/" +
userName +
"/EvalTrainedLudus/" +
filepathsGameName + filepathsRulesetName + "_vs_" + opponentAgentShortNames.get(oppIdx) + "/"
),
"--output-summary",
"--output-alpha-rank-data"
);
writer.println(javaCall);
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates heuristic optimisation scripts for Ludus Latrunculorum / Poprad Game rulesets"
);
argParse.addOption(new ArgOption()
.withNames("--project")
.help("Project for which to submit the job on cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 10,925 | 33.250784 | 136 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGen.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
import search.minimax.AlphaBetaSearch;
/**
* Script to generate scripts for ExIt training runs on cluster for all rulesets of all games.
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGen
{
/** Memory to assign per CPU, in MB */
private static final String MEM_PER_CPU = "5120";
/** Memory to assign to JVM, in MB */
private static final String JVM_MEM = "4096";
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 3000;
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGen()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
//final BestBaseAgents bestBaseAgents = BestBaseAgents.loadData();
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
if (game.isStacking())
continue;
if (game.hiddenInformation())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final String jobScriptFilename = "ExIt" + filepathsGameName + filepathsRulesetName + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J ExIt_" + filepathsGameName + filepathsRulesetName);
writer.println("#SBATCH -o /work/" + userName + "/ExIt/Out"
+ filepathsGameName + filepathsRulesetName + "_%J.out");
writer.println("#SBATCH -e /work/" + userName + "/ExIt/Err"
+ filepathsGameName + filepathsRulesetName + "_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --mem-per-cpu=" + MEM_PER_CPU);
writer.println("#SBATCH -A " + argParse.getValueString("--project"));
writer.println("unset JAVA_TOOL_OPTIONS");
String javaCall = StringRoutines.join
(
" ",
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/ExIt/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote(gameName + ".lud"),
"--ruleset",
StringRoutines.quote(fullRulesetName),
"--best-agents-data-dir",
StringRoutines.quote("/home/" + userName + "/BestAgentsData/" + filepathsGameName + filepathsRulesetName),
"-n 100",
"--game-length-cap 1000",
"--thinking-time 1",
"--is-episode-durations",
"--prioritized-experience-replay",
"--wis",
"--handle-aliasing",
"--playout-features-epsilon 0.5",
"--checkpoint-freq 10",
"--out-dir",
StringRoutines.quote
(
"/work/" +
userName +
"/ExIt/" +
filepathsGameName + filepathsRulesetName + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
if (!new AlphaBetaSearch().supportsGame(game))
javaCall += " --no-value-learning";
writer.println(javaCall);
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates self-play training scripts for all games, all game options."
);
argParse.addOption(new ArgOption()
.withNames("--project")
.help("Project for which to submit the job on cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 9,097 | 29.945578 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenCartesius.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Cartesius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenCartesius
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (64 GB per node, 24 cores per node --> 2.6GB per core, we take 2 cores) */
private static final String JVM_MEM = "4096";
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 1440;
/** We get 24 cores per job; we'll give 2 cores per process */
private static final int PROCESSES_PER_JOB = 12;
/** Only run on the Haswell nodes */
private static final String PROCESSOR = "haswell";
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Kensington.lud",
"Knightthrough.lud",
"Konane.lud",
"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenCartesius()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (final String gameName : GAMES)
{
// Sanity check: make sure game with this name loads correctly
System.out.println("gameName = " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName);
processDataList.add(new ProcessData(gameName));
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeatures/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeatures/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH --constraint=" + PROCESSOR);
// load Java modules
writer.println("module load 2020");
writer.println("module load Java/1.8.0_261");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < PROCESSES_PER_JOB && processIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(processIdx);
// Write Java call for this process
final String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join(",", String.valueOf(numJobProcesses * 2), String.valueOf(numJobProcesses * 2 + 1)),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeatures/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--is-episode-durations",
"--prioritized-experience-replay",
"--wis",
"--handle-aliasing",
"--playout-features-epsilon 0.5",
" --no-value-learning",
"--checkpoint-freq 5",
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeatures/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), "")) + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME),
">",
"/home/" + userName + "/TrainFeatures/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
/**
* Constructor
* @param gameName
*/
public ProcessData(final String gameName)
{
this.gameName = gameName;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating timing job scripts for playouts with atomic feature sets."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 8,856 | 27.11746 | 118 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnellius.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnellius
{
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
"TournamentMode",
"Reinforce",
"ReinforceZero",
"ReinforceOne",
"SpecialMovesExpander",
"All"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnellius()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (final String gameName : GAMES)
{
// Sanity check: make sure game with this name loads correctly
System.out.println("gameName = " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + gameName);
for (final String variant : VARIANTS)
{
processDataList.add(new ProcessData(gameName, game.players().count(), variant));
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnellius/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnellius/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnellius/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--is-episode-durations",
"--prioritized-experience-replay",
"--wis",
"--handle-aliasing",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 5",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-policy-gradient-threads",
String.valueOf(numPlayingThreads),
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
processData.trainingVariant + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
if (processData.trainingVariant.equals("TournamentMode") || processData.trainingVariant.equals("All"))
javaCall += " --tournament-mode";
if (processData.trainingVariant.equals("Reinforce") || processData.trainingVariant.equals("All"))
{
javaCall += " --num-policy-gradient-epochs 100";
}
else if (processData.trainingVariant.equals("ReinforceZero"))
{
javaCall += " --num-policy-gradient-epochs 100";
javaCall += " --post-pg-weight-scalar 0.0";
}
else if (processData.trainingVariant.equals("ReinforceOne"))
{
javaCall += " --num-policy-gradient-epochs 100";
javaCall += " --post-pg-weight-scalar 1.0";
}
if (processData.trainingVariant.equals("SpecialMovesExpander") || processData.trainingVariant.equals("All"))
javaCall += " --special-moves-expander";
javaCall += " " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnellius/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final String trainingVariant;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param trainingVariant
*/
public ProcessData(final String gameName, final int numPlayers, final String trainingVariant)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.trainingVariant = trainingVariant;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 12,959 | 30.004785 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnellius2.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnellius2
{
//-------------------------------------------------------------------------
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
"ReinforceGamma1",
"ReinforceGamma099",
"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
"SignCorrelationExpander",
"RandomExpander",
//"All"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnellius2()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
for (final String variant : VARIANTS)
{
processDataList.add(new ProcessData(gameName, game.players().count(), variant));
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnellius/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnellius/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnellius/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--is-episode-durations",
"--prioritized-experience-replay",
"--wis",
"--handle-aliasing",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 5",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-policy-gradient-threads",
String.valueOf(numPlayingThreads),
" --post-pg-weight-scalar 0.0",
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnellius/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
processData.trainingVariant + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
if (processData.trainingVariant.contains("Reinforce"))
{
javaCall += " --num-policy-gradient-epochs 100";
if (processData.trainingVariant.equals("ReinforceGamma1"))
javaCall += " --pg-gamma 1";
else if (processData.trainingVariant.equals("ReinforceGamma099"))
javaCall += " --pg-gamma 0.99";
else if (processData.trainingVariant.equals("ReinforceGamma09"))
javaCall += " --pg-gamma 0.9";
}
if (processData.trainingVariant.equals("SpecialMovesExpander"))
javaCall += " --special-moves-expander";
else if (processData.trainingVariant.equals("SpecialMovesExpanderSplit"))
javaCall += " --special-moves-expander-split";
else if (processData.trainingVariant.equals("SignCorrelationExpander"))
javaCall += " --expander-type CorrelationErrorSignExpander";
else if (processData.trainingVariant.equals("RandomExpander"))
javaCall += " --expander-type Random";
javaCall += " " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnellius/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final String trainingVariant;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param trainingVariant
*/
public ProcessData(final String gameName, final int numPlayers, final String trainingVariant)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.trainingVariant = trainingVariant;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,523 | 30.642702 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnellius3.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnellius3
{
//-------------------------------------------------------------------------
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
"ReinforceGamma1",
"ReinforceGamma099",
//"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
//"SignCorrelationExpander",
//"RandomExpander",
//"All"
"NoHandleAliasing",
"HandleAliasingPlayouts"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnellius3()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
for (final String variant : VARIANTS)
{
processDataList.add(new ProcessData(gameName, game.players().count(), variant));
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnellius3/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnellius3/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnellius3/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--is-episode-durations",
"--prioritized-experience-replay",
"--wis",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 5",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-policy-gradient-threads",
String.valueOf(numPlayingThreads),
" --post-pg-weight-scalar 0.0",
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnellius3/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
processData.trainingVariant + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
if (processData.trainingVariant.contains("Reinforce"))
{
javaCall += " --num-policy-gradient-epochs 100";
if (processData.trainingVariant.equals("ReinforceGamma1"))
javaCall += " --pg-gamma 1";
else if (processData.trainingVariant.equals("ReinforceGamma099"))
javaCall += " --pg-gamma 0.99";
else if (processData.trainingVariant.equals("ReinforceGamma09"))
javaCall += " --pg-gamma 0.9";
}
if (processData.trainingVariant.equals("SpecialMovesExpander"))
javaCall += " --special-moves-expander";
else if (processData.trainingVariant.equals("SpecialMovesExpanderSplit"))
javaCall += " --special-moves-expander-split";
else if (processData.trainingVariant.equals("SignCorrelationExpander"))
javaCall += " --expander-type CorrelationErrorSignExpander";
else if (processData.trainingVariant.equals("RandomExpander"))
javaCall += " --expander-type Random";
if (!processData.trainingVariant.equals("NoHandleAliasing"))
javaCall += " --handle-aliasing";
if (processData.trainingVariant.equals("HandleAliasingPlayouts"))
javaCall += " --handle-aliasing-playouts";
javaCall += " " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnellius3/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final String trainingVariant;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param trainingVariant
*/
public ProcessData(final String gameName, final int numPlayers, final String trainingVariant)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.trainingVariant = trainingVariant;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,813 | 30.721627 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnellius4.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnellius4
{
//-------------------------------------------------------------------------
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"Baseline",
//"TournamentMode",
//"ReinforceGamma1",
//"ReinforceGamma099",
//"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
//"SignCorrelationExpander",
//"RandomExpander",
//"All"
"NoHandleAliasing",
"HandleAliasingPlayouts",
"NoWED",
"NoPER"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnellius4()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
for (final String variant : VARIANTS)
{
processDataList.add(new ProcessData(gameName, game.players().count(), variant));
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnellius4/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnellius4/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnellius4/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--wis",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 5",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-policy-gradient-threads",
String.valueOf(numPlayingThreads),
" --post-pg-weight-scalar 0.0",
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
processData.trainingVariant + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
if (processData.trainingVariant.equals("SpecialMovesExpander"))
javaCall += " --special-moves-expander";
else if (processData.trainingVariant.equals("SpecialMovesExpanderSplit"))
javaCall += " --special-moves-expander-split";
if (!processData.trainingVariant.equals("NoHandleAliasing"))
javaCall += " --handle-aliasing";
if (!processData.trainingVariant.equals("NoWED"))
javaCall += " --is-episode-durations";
if (!processData.trainingVariant.equals("NoPER"))
javaCall += " --prioritized-experience-replay";
if (processData.trainingVariant.equals("HandleAliasingPlayouts"))
javaCall += " --handle-aliasing-playouts";
javaCall += " " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnellius4/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final String trainingVariant;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param trainingVariant
*/
public ProcessData(final String gameName, final int numPlayers, final String trainingVariant)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.trainingVariant = trainingVariant;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 14,267 | 30.221007 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnellius4Reinforce.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnellius4Reinforce
{
//-------------------------------------------------------------------------
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 0;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnellius4Reinforce()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
processDataList.add(new ProcessData(gameName, game.players().count()));
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeaturesReinforce_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnellius4/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnellius4/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnellius4/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--wis",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 5",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-policy-gradient-threads",
String.valueOf(numPlayingThreads),
"--post-pg-weight-scalar 1.0",
"--num-policy-gradient-epochs 1000",
"--pg-gamma 1",
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnellius4/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
"ReinforceOnly/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
javaCall += " " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnellius4/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitReinforceJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param numPlayers
*/
public ProcessData(final String gameName, final int numPlayers)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 12,980 | 30.279518 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnellius5.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnellius5
{
//-------------------------------------------------------------------------
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 234;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 2880;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/** Games we want to run */
private static final String[] GAMES =
new String[]
{
"Alquerque.lud",
"Amazons.lud",
"ArdRi.lud",
"Arimaa.lud",
"Ataxx.lud",
"Bao Ki Arabu (Zanzibar 1).lud",
"Bizingo.lud",
"Breakthrough.lud",
"Chess.lud",
//"Chinese Checkers.lud",
"English Draughts.lud",
"Fanorona.lud",
"Fox and Geese.lud",
"Go.lud",
"Gomoku.lud",
"Gonnect.lud",
"Havannah.lud",
"Hex.lud",
"Knightthrough.lud",
"Konane.lud",
//"Level Chess.lud",
"Lines of Action.lud",
"Omega.lud",
"Pentalath.lud",
"Pretwa.lud",
"Reversi.lud",
"Royal Game of Ur.lud",
"Surakarta.lud",
"Shobu.lud",
"Tablut.lud",
//"Triad.lud",
"XII Scripta.lud",
"Yavalath.lud"
};
/** Descriptors of several variants we want to test */
private static final String[] VARIANTS =
new String[]
{
"BaselineNoIS",
"Baseline",
//"ReinforceGamma1",
//"ReinforceGamma099",
//"ReinforceGamma09",
"SpecialMovesExpander",
"SpecialMovesExpanderSplit",
"NoHandleAliasing",
"HandleAliasingPlayouts",
"NoWED",
"NoPER",
"ReinforceOnly",
"Reinforce",
"SignCorrelationExpander",
"RandomExpander",
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnellius5()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final Game[] compiledGames = new Game[GAMES.length];
final double[] expectedTrialDurations = new double[GAMES.length];
for (int i = 0; i < compiledGames.length; ++i)
{
final Game game = GameLoader.loadGameFromName(GAMES[i]);
if (game == null)
throw new IllegalArgumentException("Cannot load game: " + GAMES[i]);
compiledGames[i] = game;
expectedTrialDurations[i] = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
System.out.println("expected duration per trial for " + GAMES[i] + " = " + expectedTrialDurations[i]);
}
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(GAMES.length, new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations[i2.intValue()] - expectedTrialDurations[i1.intValue()];
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
final Game game = compiledGames[idx];
final String gameName = GAMES[idx];
for (final String variant : VARIANTS)
{
processDataList.add(new ProcessData(gameName, game.players().count(), variant));
}
}
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnellius5/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnellius5/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnellius5/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote("/" + processData.gameName),
"-n",
String.valueOf(processData.trainingVariant.equals("ReinforceOnly") ? 0 : MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--wis",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 5",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-policy-gradient-threads",
String.valueOf(numPlayingThreads),
"--post-pg-weight-scalar",
String.valueOf(processData.trainingVariant.equals("ReinforceOnly") ? 1.0 : 0.0),
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnellius5/Out/" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
processData.trainingVariant + "/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
if (processData.trainingVariant.equals("SpecialMovesExpander"))
javaCall += " --special-moves-expander";
else if (processData.trainingVariant.equals("SpecialMovesExpanderSplit"))
javaCall += " --special-moves-expander-split";
else if (processData.trainingVariant.equals("SignCorrelationExpander"))
javaCall += " --expander-type CorrelationErrorSignExpander";
else if (processData.trainingVariant.equals("RandomExpander"))
javaCall += " --expander-type Random";
if (!processData.trainingVariant.equals("NoHandleAliasing"))
javaCall += " --handle-aliasing";
if (!processData.trainingVariant.equals("NoWED") && !processData.trainingVariant.equals("BaselineNoIS"))
javaCall += " --is-episode-durations";
if (!processData.trainingVariant.equals("NoPER") && !processData.trainingVariant.equals("BaselineNoIS"))
javaCall += " --prioritized-experience-replay";
if (processData.trainingVariant.equals("HandleAliasingPlayouts"))
javaCall += " --handle-aliasing-playouts";
if (processData.trainingVariant.equals("ReinforceOnly") || processData.trainingVariant.equals("Reinforce"))
{
javaCall += " --num-policy-gradient-epochs 1000";
javaCall += " --pg-gamma 1";
}
javaCall +=
" " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnellius5/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"2>",
"/home/" + userName + "/TrainFeaturesSnellius5/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final int numPlayers;
public final String trainingVariant;
/**
* Constructor
* @param gameName
* @param numPlayers
* @param trainingVariant
*/
public ProcessData(final String gameName, final int numPlayers, final String trainingVariant)
{
this.gameName = gameName;
this.numPlayers = numPlayers;
this.trainingVariant = trainingVariant;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 15,150 | 31.099576 | 135 |
java
|
Ludii
|
Ludii-master/Player/src/supplementary/experiments/scripts/ExItTrainingScriptsGenSnelliusAllGames.java
|
package supplementary.experiments.scripts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import features.spatial.Walk;
import game.Game;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ArrayUtils;
import main.options.Ruleset;
import other.GameLoader;
import supplementary.experiments.analysis.RulesetConceptsUCT;
import utils.RulesetNames;
/**
* Generates job scripts to submit to SLURM for running ExIt training runs
*
* Script generation currently made for Snellius cluster (not RWTH Aachen)
*
* @author Dennis Soemers
*/
public class ExItTrainingScriptsGenSnelliusAllGames
{
//-------------------------------------------------------------------------
/** Don't submit more than this number of jobs at a single time */
private static final int MAX_JOBS_PER_BATCH = 800;
/** Memory to assign to JVM, in MB (2 GB per core --> we take 3 cores per job, 6GB per job, use 5GB for JVM) */
private static final String JVM_MEM = "5120";
/** Memory to assign per process (in GB) */
private static final int MEM_PER_PROCESS = 6;
/** Memory available per node in GB (this is for Thin nodes on Snellius) */
private static final int MEM_PER_NODE = 256;
/** Cluster doesn't seem to let us request more memory than this for any single job (on a single node) */
private static final int MAX_REQUEST_MEM = 224;
/** Max number of self-play trials */
private static final int MAX_SELFPLAY_TRIALS = 200;
/** Max wall time (in minutes) */
private static final int MAX_WALL_TIME = 1445;
/** Number of cores per node (this is for Thin nodes on Snellius) */
private static final int CORES_PER_NODE = 128;
/** Two cores is not enough since we want at least 5GB memory per job, so we take 3 cores (and 6GB memory) per job */
private static final int CORES_PER_PROCESS = 3;
/** If we request more cores than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_CORES_THRESHOLD = 96;
/** If we have more processes than this in a job, we get billed for the entire node anyway, so should request exclusive */
private static final int EXCLUSIVE_PROCESSES_THRESHOLD = EXCLUSIVE_CORES_THRESHOLD / CORES_PER_PROCESS;
/**Number of processes we can put in a single job (on a single node) */
private static final int PROCESSES_PER_JOB = CORES_PER_NODE / CORES_PER_PROCESS;
/**
* Games we should skip since they never end anyway (in practice), but do
* take a long time.
*/
private static final String[] SKIP_GAMES = new String[]
{
"Chinese Checkers.lud",
"Li'b al-'Aqil.lud",
"Li'b al-Ghashim.lud",
"Mini Wars.lud",
"Pagade Kayi Ata (Sixteen-handed).lud",
"Taikyoku Shogi.lud"
};
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private ExItTrainingScriptsGenSnelliusAllGames()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our scripts
* @param argParse
*/
private static void generateScripts(final CommandLineArgParse argParse)
{
final List<String> jobScriptNames = new ArrayList<String>();
String scriptsDir = argParse.getValueString("--scripts-dir");
scriptsDir = scriptsDir.replaceAll(Pattern.quote("\\"), "/");
if (!scriptsDir.endsWith("/"))
scriptsDir += "/";
final String userName = argParse.getValueString("--user-name");
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<String> gameNames = new ArrayList<String>();
final List<String> rulesetNames = new ArrayList<String>();
final TDoubleArrayList expectedTrialDurations = new TDoubleArrayList();
final TIntArrayList playerCounts = new TIntArrayList();
for (final String gameName : allGameNames)
{
final String[] gameNameSplit = gameName.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String shortGameName = gameNameSplit[gameNameSplit.length - 1];
boolean skipGame = false;
for (final String game : SKIP_GAMES)
{
if (shortGameName.endsWith(game))
{
skipGame = true;
break;
}
}
if (skipGame)
continue;
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName);
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName, fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.hasSubgames())
continue;
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.isStacking())
continue;
if (game.isBoardless())
continue;
if (game.hiddenInformation())
continue;
if (Walk.allGameRotations(game).length == 0)
continue;
if (game.players().count() == 0)
continue;
if (game.isSimultaneousMoveGame())
continue;
double expectedTrialDuration = RulesetConceptsUCT.getValue(RulesetNames.gameRulesetName(game), "DurationMoves");
if (Double.isNaN(expectedTrialDuration))
expectedTrialDuration = Double.MAX_VALUE;
gameNames.add("/" + shortGameName);
rulesetNames.add(fullRulesetName);
expectedTrialDurations.add(expectedTrialDuration);
playerCounts.add(game.players().count());
}
}
// Sort games in decreasing order of expected duration (in moves per trial)
// This ensures that we start with the slow games, and that games of similar
// durations are likely to end up in the same job script (and therefore run
// on the same node at the same time).
final List<Integer> sortedGameIndices = ArrayUtils.sortedIndices(gameNames.size(), new Comparator<Integer>()
{
@Override
public int compare(final Integer i1, final Integer i2)
{
final double delta = expectedTrialDurations.getQuick(i2.intValue()) - expectedTrialDurations.getQuick(i1.intValue());
if (delta < 0.0)
return -1;
if (delta > 0.0)
return 1;
return 0;
}
});
// First create list with data for every process we want to run
final List<ProcessData> processDataList = new ArrayList<ProcessData>();
for (int idx : sortedGameIndices)
{
processDataList.add(new ProcessData(gameNames.get(idx), rulesetNames.get(idx), playerCounts.getQuick(idx)));
}
double totalCoreHoursRequested = 0.0;
int processIdx = 0;
while (processIdx < processDataList.size())
{
// Start a new job script
final String jobScriptFilename = "TrainFeatures_" + jobScriptNames.size() + ".sh";
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + jobScriptFilename), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J TrainFeatures");
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + userName + "/TrainFeaturesSnelliusAllGames/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + userName + "/TrainFeaturesSnelliusAllGames/Out/Err_%J.err");
writer.println("#SBATCH -t " + MAX_WALL_TIME);
writer.println("#SBATCH -N 1"); // 1 node, no MPI/OpenMP/etc
// Compute memory and core requirements
final int numProcessesThisJob = Math.min(processDataList.size() - processIdx, PROCESSES_PER_JOB);
final boolean exclusive = (numProcessesThisJob > EXCLUSIVE_PROCESSES_THRESHOLD);
final int jobMemRequestGB;
if (exclusive)
jobMemRequestGB = Math.min(MEM_PER_NODE, MAX_REQUEST_MEM); // We're requesting full node anyway, might as well take all the memory
else
jobMemRequestGB = Math.min(numProcessesThisJob * MEM_PER_PROCESS, MAX_REQUEST_MEM);
totalCoreHoursRequested += (CORES_PER_NODE * (MAX_WALL_TIME / 60.0));
writer.println("#SBATCH --cpus-per-task=" + numProcessesThisJob * CORES_PER_PROCESS);
writer.println("#SBATCH --mem=" + jobMemRequestGB + "G"); // 1 node, no MPI/OpenMP/etc
if (exclusive)
writer.println("#SBATCH --exclusive");
else
writer.println("#SBATCH --exclusive"); // Just making always exclusive for now because otherwise taskset doesn't work
// load Java modules
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
// Put up to PROCESSES_PER_JOB processes in this job
int numJobProcesses = 0;
while (numJobProcesses < numProcessesThisJob)
{
final ProcessData processData = processDataList.get(processIdx);
final int numFeatureDiscoveryThreads = Math.min(processData.numPlayers, CORES_PER_PROCESS);
final int numPlayingThreads = CORES_PER_PROCESS;
// Write Java call for this process
String javaCall = StringRoutines.join
(
" ",
"taskset", // Assign specific core to each process
"-c",
StringRoutines.join
(
",",
String.valueOf(numJobProcesses * 3),
String.valueOf(numJobProcesses * 3 + 1),
String.valueOf(numJobProcesses * 3 + 2)
),
"java",
"-Xms" + JVM_MEM + "M",
"-Xmx" + JVM_MEM + "M",
"-XX:+HeapDumpOnOutOfMemoryError",
"-da",
"-dsa",
"-XX:+UseStringDeduplication",
"-jar",
StringRoutines.quote("/home/" + userName + "/TrainFeaturesSnelliusAllGames/Ludii.jar"),
"--expert-iteration",
"--game",
StringRoutines.quote(processData.gameName),
"--ruleset",
StringRoutines.quote(processData.rulesetName),
"-n",
String.valueOf(MAX_SELFPLAY_TRIALS),
"--game-length-cap 1000",
"--thinking-time 1",
"--iteration-limit 12000",
"--wis",
"--playout-features-epsilon 0.5",
"--no-value-learning",
"--train-tspg",
"--checkpoint-freq 20",
"--num-agent-threads",
String.valueOf(numPlayingThreads),
"--num-feature-discovery-threads",
String.valueOf(numFeatureDiscoveryThreads),
"--out-dir",
StringRoutines.quote
(
"/home/" +
userName +
"/TrainFeaturesSnelliusAllGames/Out" +
StringRoutines.cleanGameName(processData.gameName.replaceAll(Pattern.quote(".lud"), ""))
+
"_"
+
StringRoutines.cleanRulesetName(processData.rulesetName).replaceAll(Pattern.quote("/"), "_")
+
"/"
),
"--no-logging",
"--max-wall-time",
String.valueOf(MAX_WALL_TIME)
);
javaCall += " --special-moves-expander-split";
javaCall += " --handle-aliasing";
javaCall += " --is-episode-durations";
javaCall += " --prioritized-experience-replay";
javaCall += " " + StringRoutines.join
(
" ",
">",
"/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out/Out_${SLURM_JOB_ID}_" + numJobProcesses + ".out",
"2>",
"/home/" + userName + "/TrainFeaturesSnelliusAllGames/Out/Err_${SLURM_JOB_ID}_" + numJobProcesses + ".err",
"&" // Run processes in parallel
);
writer.println(javaCall);
++processIdx;
++numJobProcesses;
}
writer.println("wait"); // Wait for all the parallel processes to finish
jobScriptNames.add(jobScriptFilename);
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final List<List<String>> jobScriptsLists = new ArrayList<List<String>>();
List<String> remainingJobScriptNames = jobScriptNames;
while (remainingJobScriptNames.size() > 0)
{
if (remainingJobScriptNames.size() > MAX_JOBS_PER_BATCH)
{
final List<String> subList = new ArrayList<String>();
for (int i = 0; i < MAX_JOBS_PER_BATCH; ++i)
{
subList.add(remainingJobScriptNames.get(i));
}
jobScriptsLists.add(subList);
remainingJobScriptNames = remainingJobScriptNames.subList(MAX_JOBS_PER_BATCH, remainingJobScriptNames.size());
}
else
{
jobScriptsLists.add(remainingJobScriptNames);
remainingJobScriptNames = new ArrayList<String>();
}
}
for (int i = 0; i < jobScriptsLists.size(); ++i)
{
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptsDir + "SubmitJobs_Part" + i + ".sh"), "UTF-8"))
{
for (final String jobScriptName : jobScriptsLists.get(i))
{
writer.println("sbatch " + jobScriptName);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("Total core hours requested = " + totalCoreHoursRequested);
}
//-------------------------------------------------------------------------
/**
* Wrapper around data for a single process (multiple processes per job)
*
* @author Dennis Soemers
*/
private static class ProcessData
{
public final String gameName;
public final String rulesetName;
public final int numPlayers;
/**
* Constructor
* @param gameName
* @param rulesetName
* @param numPlayers
*/
public ProcessData(final String gameName, final String rulesetName, final int numPlayers)
{
this.gameName = gameName;
this.rulesetName = rulesetName;
this.numPlayers = numPlayers;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
*/
public static void main(final String[] args)
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Creating feature training job scripts for Snellius cluster."
);
argParse.addOption(new ArgOption()
.withNames("--user-name")
.help("Username on the cluster.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--scripts-dir")
.help("Directory in which to store generated scripts.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateScripts(argParse);
}
//-------------------------------------------------------------------------
}
| 16,065 | 31.132 | 135 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.