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 |
---|---|---|---|---|---|---|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/main/java/org/deepspeech/libdeepspeech_doc/DeepSpeech_Error_Codes.java
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.deepspeech.libdeepspeech;
public enum DeepSpeech_Error_Codes {
ERR_OK(0x0000),
ERR_NO_MODEL(0x1000),
ERR_INVALID_ALPHABET(0x2000),
ERR_INVALID_SHAPE(0x2001),
ERR_INVALID_SCORER(0x2002),
ERR_MODEL_INCOMPATIBLE(0x2003),
ERR_SCORER_NOT_ENABLED(0x2004),
ERR_SCORER_UNREADABLE(0x2005),
ERR_SCORER_INVALID_LM(0x2006),
ERR_SCORER_NO_TRIE(0x2007),
ERR_SCORER_INVALID_TRIE(0x2008),
ERR_SCORER_VERSION_MISMATCH(0x2009),
ERR_FAIL_INIT_MMAP(0x3000),
ERR_FAIL_INIT_SESS(0x3001),
ERR_FAIL_INTERPRETER(0x3002),
ERR_FAIL_RUN_SESS(0x3003),
ERR_FAIL_CREATE_STREAM(0x3004),
ERR_FAIL_READ_PROTOBUF(0x3005),
ERR_FAIL_CREATE_SESS(0x3006),
ERR_FAIL_CREATE_MODEL(0x3007),
ERR_FAIL_INSERT_HOTWORD(0x3008),
ERR_FAIL_CLEAR_HOTWORD(0x3009),
ERR_FAIL_ERASE_HOTWORD(0x3010);
public final int swigValue() {
return swigValue;
}
public static DeepSpeech_Error_Codes swigToEnum(int swigValue) {
DeepSpeech_Error_Codes[] swigValues = DeepSpeech_Error_Codes.class.getEnumConstants();
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (DeepSpeech_Error_Codes swigEnum : swigValues)
if (swigEnum.swigValue == swigValue)
return swigEnum;
throw new IllegalArgumentException("No enum " + DeepSpeech_Error_Codes.class + " with value " + swigValue);
}
@SuppressWarnings("unused")
private DeepSpeech_Error_Codes() {
this.swigValue = SwigNext.next++;
}
@SuppressWarnings("unused")
private DeepSpeech_Error_Codes(int swigValue) {
this.swigValue = swigValue;
SwigNext.next = swigValue+1;
}
@SuppressWarnings("unused")
private DeepSpeech_Error_Codes(DeepSpeech_Error_Codes swigEnum) {
this.swigValue = swigEnum.swigValue;
SwigNext.next = this.swigValue+1;
}
private final int swigValue;
private static class SwigNext {
private static int next = 0;
}
}
| 2,324 | 30.418919 | 111 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/main/java/org/deepspeech/libdeepspeech_doc/Metadata.java
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.deepspeech.libdeepspeech;
/**
* An array of CandidateTranscript objects computed by the model.
*/
public class Metadata {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected Metadata(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(Metadata obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@SuppressWarnings("deprecation")
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
implJNI.delete_Metadata(swigCPtr);
}
swigCPtr = 0;
}
}
/**
* Size of the transcripts array
*/
public long getNumTranscripts() {
return implJNI.Metadata_NumTranscripts_get(swigCPtr, this);
}
/**
* Retrieve one CandidateTranscript element<br>
* <br>
* @param i Array index of the CandidateTranscript to get<br>
* <br>
* @return The CandidateTranscript requested or null
*/
public CandidateTranscript getTranscript(int i) {
return new CandidateTranscript(implJNI.Metadata_getTranscript(swigCPtr, this, i), false);
}
}
| 1,587 | 25.032787 | 93 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/main/java/org/deepspeech/libdeepspeech_doc/TokenMetadata.java
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.deepspeech.libdeepspeech;
/**
* Stores text of an individual token, along with its timing information
*/
public class TokenMetadata {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected TokenMetadata(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(TokenMetadata obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
throw new UnsupportedOperationException("C++ destructor does not have public access");
}
swigCPtr = 0;
}
}
/**
* The text corresponding to this token
*/
public String getText() {
return implJNI.TokenMetadata_Text_get(swigCPtr, this);
}
/**
* Position of the token in units of 20ms
*/
public long getTimestep() {
return implJNI.TokenMetadata_Timestep_get(swigCPtr, this);
}
/**
* Position of the token in seconds
*/
public float getStartTime() {
return implJNI.TokenMetadata_StartTime_get(swigCPtr, this);
}
}
| 1,528 | 24.915254 | 94 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/test/java/org/deepspeech/libdeepspeech/ExampleUnitTest.java
|
package org.deepspeech.libdeepspeech;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
| 389 | 21.941176 | 81 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/ArmsRace.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Return an instance of a discretized Arms Race game using
* user specified functions. For now it is left to the user
* to make sure that the C function is smooth and the B
* function is smooth and concave.
*
* Although the arms races game could be extended to more
* that two players, we will limit it at two as is the general
* case that is studied in economics.
*
*/
public class ArmsRace extends Game
{
private Function cFunc;
private Function bFunc;
private boolean randomize;
// -----------------------------------------------------
// Parameters: The Arms Race game is parameterized by
// specifying the function classes and function params for
// the C and B functions, as well as the range of actions
// allowed with the number of actions equal to
// 1 + high_act - low_act.
//
private static Parameters.ParamInfo pCFunc;
private static Parameters.ParamInfo pBFunc;
private static Parameters.ParamInfo pCArgs;
private static Parameters.ParamInfo pBArgs;
private static Parameters.ParamInfo pActLow;
private static Parameters.ParamInfo[] arParam;
static {
pCFunc = new Parameters.ParamInfo("c_func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the cost function C. The function supplied should be SMOOTH in order to stick to the strict definition of an Arms Race.");
pCArgs = new Parameters.ParamInfo("c_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the cost function C, must be enclosed in [].");
pBFunc = new Parameters.ParamInfo("b_func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the B function. The function supplied should be SMOOTH AND CONCAVE in order to stick to the strict definition of an Arms Race.");
pBArgs = new Parameters.ParamInfo("b_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the B function, must be enclosed in [].");
pActLow = new Parameters.ParamInfo("low_act", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(1000), "lower bound on the players' action range. Must be > 0 and <= 1000. The upper bound on the players' action range will be low_act + actions - 1.");
arParam = new Parameters.ParamInfo[]
{Game.symActions, pCFunc, pCArgs, pBFunc, pBArgs, pActLow};
Global.registerParams(ArmsRace.class, arParam);
}
// -------------------------------------------------------
public ArmsRace()
throws Exception
{
super();
}
/**
* Set the parameters for the game itself -- the parameters for
* the functions will be parsed in initialize().
*/
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize = randomize;
}
public void initialize()
throws Exception
{
super.initialize();
// The number of players will always be 2 in the arms race.
setNumPlayers(2);
parseSameNumberActions();
// Get the types of the C and B functions, create the
// function objects, and parse the function parameters
String cFuncName = parameters.getStringParameter(pCFunc.name);
ParamParser cParams = parameters.getParserParameter(pCArgs.name);
cFunc = (Function) Global.getObjectOrDie(cFuncName, Global.FUNC);
cFunc.setDomain(getLongParameter(pActLow.name), getNumActions(0) + getLongParameter(pActLow.name));
try {
cFunc.setParameters(cParams, randomize);
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(cFunc.getHelp());
Global.handleError(e, "Error parsing C function params");
}
String bFuncName = parameters.getStringParameter(pBFunc.name);
ParamParser bParams = parameters.getParserParameter(pBArgs.name);
bFunc = (Function) Global.getObjectOrDie(bFuncName, Global.FUNC);
bFunc.setDomain(-getNumActions(0), +getNumActions(0));
try {
bFunc.setParameters(bParams, randomize);
} catch (Exception e) {
System.err.println(bFunc.getHelp());
Global.handleError(e, "Error parsing B function params");
}
// Initialize all functions
cFunc.initialize();
bFunc.initialize();
}
/**
* Randomize the low action bound and functions
*/
public void randomizeParameters()
{
parameters.randomizeParameter(pActLow.name);
try {
if(!parameters.setByUser(pCFunc.name))
parameters.setParameter(pCFunc.name,
Global.getRandomClass(Global.FUNC));
if(!parameters.setByUser(pBFunc.name))
parameters.setParameter(pBFunc.name,
Global.getRandomClass(Global.FUNC,
"ConcaveFunction"));
} catch (Exception e) {
Global.handleError(e, "Randomizing Functions!");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
/**
* Make sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(pActLow.name) < 0)
throw new Exception ("low_act < 0");
}
protected String getGameHelp()
{
return "Create an instance of an Arms Race game. Payoffs " +
"in this game are symmetric and calculated by using the " +
"formula -C(x)+B(x-y) where x is the level of arms the " +
"player in question has chosen, y is the level of arms " +
"his opponent has chosen, and C and B are user-specified " +
"functions.\n\n" +
"Please note that in order for the game to meet the " +
"definition of an Arms Race common in economics literature " +
"it must be the case that B is smooth and concave and C is " +
"at least smooth. Choose your functions accordingly.";
}
/**
* Returns the payoff for the given player in the given outcome.
* If x is the level of arms the player has chosen and y is the
* level the opponent has chosen then the payoff for the
* player is:
*
* -C(x) + B(x-y)
*
* Note that since our actions always begin at 1, the y values
* are really the action + the low action value - 1.
*/
public double getPayoff(int[] outcome, int player)
{
int offset = (int) getLongParameter(pActLow.name) - 1;
int x[] = new int[2];
for (int i = 0; i < 2; i++)
x[i] = outcome[i] + offset;
double payoff = (double) ((-(cFunc.eval(x[player]))) +
(bFunc.eval(x[player] - x[1-player])));
return payoff;
}
/**
* Generates the functions.
*/
public void doGenerate()
{
setDescription("Two Player Arms Race Game\n" + getDescription());
setName("Arms Race");
cFunc.doGenerate();
bFunc.doGenerate();
}
}
| 7,465 | 29.85124 | 265 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/BattleOfTheSexes.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a version of the Battle of the Sexes game
*/
public class BattleOfTheSexes extends MatrixGame
{
// Parameters: Battle of the Sexes does not take parameters.
private static Parameters.ParamInfo[] bosParam;
static {
bosParam = new Parameters.ParamInfo[] {};
Global.registerParams(BattleOfTheSexes.class, bosParam);
}
// ----------------------------------------------
public BattleOfTheSexes()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 2;
setNumActions(numActions);
initMatrix();
}
protected void checkParameters() throws Exception
{
}
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates a 2x2 Battle of the Sexes Game" +
getRangeHelp();
}
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
setDescription("Battle of the Sexes\n"
+ getDescription());
setName("Battle of the Sexes");
SortedAndRandomSet payoffValues = new SortedAndRandomSet();
// Generate three payoff values in the range from
// payoff_low to payoff_high. Make sure that the
// three payoffs are distinct.
for (int i = 0; i < 3; i++) {
Double randomPayoffAsDouble;
do {
double randomPayoff = Global.randomDouble(low, high);
randomPayoffAsDouble = new Double(randomPayoff);
} while (!(payoffValues.add(randomPayoffAsDouble)));
}
Double c = (Double) payoffValues.removeSmallest();
Double a = (Double) payoffValues.removeRandom();
Double b = (Double) payoffValues.removeRandom();
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
outcome.reset();
setPayoff(outcome.getOutcome(), 0, a.doubleValue());
setPayoff(outcome.getOutcome(), 1, b.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, c.doubleValue());
setPayoff(outcome.getOutcome(), 1, c.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, c.doubleValue());
setPayoff(outcome.getOutcome(), 1, c.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, b.doubleValue());
setPayoff(outcome.getOutcome(), 1, a.doubleValue());
}
}
| 3,034 | 22.897638 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/BertrandOligopoly.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Returns an instance of the Bertrand Oligopoly. Set-up is
* similar to that of the Timing Games, but functions used to
* determine payoffs are arbitrarily more complicated.
*/
public class BertrandOligopoly extends Game
{
// == ARBITRARY Normalization constant
private static final double NORM_CONST=10000.0;
private Function costFunc;
private Function demandFunc;
private boolean randomize=false;
private double costAdd, demandAdd;
private double costMult, demandMult;
// -----------------------------------------------------
// Parameters: The Bertrand Oligopoly is parameterized by
// the number of players, number of actions (which should
// be the same for all players), and two functions for
// cost and demand with their parameters.
//
private static Parameters.ParamInfo pCostFunc;
private static Parameters.ParamInfo pDemFunc;
private static Parameters.ParamInfo pCostFuncArgs;
private static Parameters.ParamInfo pDemFuncArgs;
private static Parameters.ParamInfo[] bertParam;
static {
pCostFunc = new Parameters.ParamInfo("cost_func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the cost function.");
pCostFuncArgs = new Parameters.ParamInfo("cost_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the cost function, must be enclosed in [].");
pDemFunc = new Parameters.ParamInfo("demand_func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the demand function.");
pDemFuncArgs = new Parameters.ParamInfo("demand_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the demand function, must be enclosed in [].");
bertParam = new Parameters.ParamInfo[]
{Game.players, Game.symActions, pCostFunc,
pCostFuncArgs, pDemFunc, pDemFuncArgs};
Global.registerParams(BertrandOligopoly.class, bertParam);
}
// -------------------------------------------------------
public BertrandOligopoly()
throws Exception
{
super();
}
/**
* Sets the parameters for the game itself, and parse and
* set the parameters for the cost and demand functions
* and set those respectively.
*/
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
// Can parse the players and actions as usual, making sure
// there are the same number of actions for each player
parsePlayersSameNumberActions();
}
public void initialize()
throws Exception
{
super.initialize();
// Initialize the cost and demand functions
// Now get the type of the demand function, create its
// function object, and parse its parameters
String dFuncName = parameters.getStringParameter(pDemFunc.name);
ParamParser dFuncParams = parameters.getParserParameter(pDemFuncArgs.name);
demandFunc = (Function) Global.getObjectOrDie(dFuncName,
Global.FUNC);
demandFunc.setDomain(0, getNumActions(0));
try {
demandFunc.setParameters(dFuncParams, randomize);
demandFunc.initialize();
demandFunc.doGenerate();
// demand >=0
double demandMin = demandFunc.eval(demandFunc.getDMax());
demandAdd = (demandMin < 0 ? - demandMin : 0);
double demandMax = demandFunc.eval(demandFunc.getDMin())+demandAdd;
demandMult = NORM_CONST / demandMax;
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(demandFunc.getHelp());
Global.handleError(e, "Error parsing demand function params");
}
// Get the type of the cost function, create the function
// object, and parse its parameters
String cFuncName = parameters.getStringParameter(pCostFunc.name);
ParamParser cFuncParams = parameters.getParserParameter(pCostFuncArgs.name);
costFunc = (Function) Global.getObjectOrDie(cFuncName,
Global.FUNC);
// -- assuming demand is decreasing
costFunc.setDomain(evalDemand(getNumActions(0)) / getNumPlayers(),
evalDemand(0));
try {
costFunc.setParameters(cFuncParams, randomize);
costFunc.initialize();
costFunc.doGenerate();
// -- cost must be non-neg
double costMin = costFunc.eval(costFunc.getDMin());
costAdd = (costMin < 0 ? -costMin : 0);
double costMax = costFunc.eval(costFunc.getDMax()) + costAdd;
costMult = NORM_CONST / costMax;
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(costFunc.getHelp());
Global.handleError(e, "Error parsing cost function params");
}
}
public void randomizeParameters() {
try {
if(!parameters.setByUser(pCostFunc.name))
parameters.setParameter(pCostFunc.name,
Global.getRandomClass(Global.FUNC, "SlowlyIncreasingFunction"));
if(!parameters.setByUser(pDemFunc.name))
parameters.setParameter(pDemFunc.name,
Global.getRandomClass(Global.FUNC, "DecreasingFunction"));
} catch (Exception e) {
Global.handleError(e, "Randomizing Function");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
//
// Make sure that the parameters are in the proper range
//
protected void checkParameters() throws Exception
{
if(!Global.isPartOf(Global.FUNC, getStringParameter(pDemFunc.name),
"DecreasingFunction"))
throw new Exception("Demand must be decreasing!");
if(!Global.isPartOf(Global.FUNC, getStringParameter(pCostFunc.name),
"IncreasingFunction"))
throw new Exception("Cost must be increasing!");
}
protected String getGameHelp()
{
return "Creates an instance of a Bertrand Oligopoly using " +
"arbitrary cost and demand functions.\n\n" +
"In the Bertrand Oligopoly, each player offering " +
"the object at the lowest price p will receive a " +
"payoff of \n\n" +
" p*(D(p)/m) - C(D(p)/m) \n\n" +
"where D is the demand function, C is the cost function, " +
"and m is the number of players who offered the object " +
"at this price.\n\n" +
"Please note that the demand function should " +
"be non-negative and decreasing.";
}
/**
* Evaluates demand.
*/
double evalDemand(double x)
{
return demandMult*(demandFunc.eval(x)+demandAdd);
}
/**
* Evaluates cost.
*/
double evalCost(double x)
{
return costMult*(costFunc.eval(x)+costAdd);
}
/**
* Return the payoff for the given player in the given
* outcome using the parameterized cost and demand functions.
* If a firm is one of the m firms with the lowest price (action)
* then payoff is given by
*
* p * (D(p)/m) - C(D(p)/m)
*
* Otherwise the payoff is 0.
*
*/
public double getPayoff(int[] outcome, int player)
{
long lowAction = outcome[0];
long m = 0;
for (int i = 0; i < getNumPlayers(); i++) {
if (outcome[i] < lowAction) {
lowAction = outcome[i];
m = 1;
} else if (outcome[i] == lowAction) {
m++;
}
}
// If player does not offer the item at the lowest
// price of everyone, immediately return 0 for the payoff.
if (outcome[player] > lowAction)
return 0;
double demandOfP = evalDemand(lowAction);
if (demandOfP < 0) demandOfP = 0;
// Otherwise return p * (D(p)/m) - C(D(p)/m)
return (((double) lowAction * demandOfP / (double) m) -
evalCost(demandOfP / (double) m));
}
/**
* Generates the demand and cost functions which are
* needed to determine payoffs.
*/
public void doGenerate()
{
setName("Bertrand Oligopoly");
setDescription("Bertrand Oligopoly\n" +
getDescription() +
"\nDemand Func: " + demandFunc.getDescription() +
"\nCost Func: " + costFunc.getDescription());
/* demandFunc.doGenerate();
costFunc.doGenerate();
*/
}
}
| 8,712 | 28.140468 | 186 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/BidirectionalLEG.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Generate a Local Effect Game with a given graphical
* structure and a given function structure such that
* the function stored on an edge a to b is the same as
* the function stored on an edge b to a.
*
* Very similar to RandomLEG except for the generation
* function.
*/
public class BidirectionalLEG extends RandomLEG
{
// --------------------------------------------------
// Parameters: Parameters carry over from RandomLEG
// and from the graph and function being used. No new
// parameters are introduced here.
//
static {
Global.registerParams(BidirectionalLEG.class, rlegParam);
}
// -------------------------------------------------------
public BidirectionalLEG()
throws Exception
{
super();
}
protected String getGameHelp()
{
return "Creates a Bidirectional Local-Effect Game using the " +
"specified graph class and specified function class.\n\n" +
"A Bidirectional Local-Effect Game is a LEG with a graphical " +
"structure in which every edge from b to a has the same " +
"local-effect function as the edge from a to b.\n\n" +
"Please note " +
"that you should be careful when you choose the graph " +
"class and set the graph parameters here. The graph " +
"chosen should be symmetric (i.e. whenever there is an " +
"edge from a to b there is also an edge from b to a) and " +
"should not have reflexive edges. (Each node will have a " +
"local effect on itself, but this is handled outside of the " +
"graph.) Set the parameters for the graph accordingly!";
}
/**
* Generate the graph and for each node and edge of the graph,
* a function, making sure that functions are the same on every
* edge from a to b as they are on the edge from b to a.
*/
public void doGenerate()
{
setDescription("Bidirectional Local-Effect Game\n" +
getDescription());
setName("Bidirectional Local-Effect Game");
// Generate the graph for the game.
graph.doGenerate();
setDescription(getDescription() + "\nGraph Params:\n" + graph.getDescription());
String funcName = parameters.getStringParameter("func");
ParamParser funcParams = parameters.getParserParameter("func_params");
// Add a function of the appropriate type to each edge
// of the graph and to each node of the graph
for (int i = 0; i < graph.getNNodes(); i++) {
Function fNode = (Function) Global.getObjectOrDie(funcName,
Global.FUNC);
try {
fNode.setDomain(0, getNumPlayers());
fNode.setParameters(funcParams, randomize);
fNode.initialize();
fNode.doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(fNode.getHelp());
Global.handleError(e, "Error initializing function");
}
graph.setNodeData(i, fNode);
Iterator edgeIter = graph.getEdges(i);
while (edgeIter.hasNext()) {
Edge edge = (Edge) edgeIter.next();
// Make sure we only generate one function for each
// edge pair and use it for both -- shouldn't have any
// reflexive edges in the graph, but handle it anyway
if (i <= edge.getDest()) {
Function fEdge = (Function)
Global.getObjectOrDie(funcName, Global.FUNC);
try {
fEdge.setDomain(0, getNumPlayers());
fEdge.setParameters(funcParams, randomize);
fEdge.initialize();
fEdge.doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(fEdge.getHelp());
Global.handleError(e, "Error initializing function");
}
edge.setData(fEdge);
if (i != edge.getDest()) {
Edge reverse = graph.getEdge(edge.getDest(), i);
reverse.setData(fEdge);
}
}
}
}
}
}
| 4,585 | 29.778523 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/Chicken.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a version of the two player Chicken game.
*/
public class Chicken extends MatrixGame
{
// Parameters: Takes no parameters
private static Parameters.ParamInfo[] chParam;
static {
chParam = new Parameters.ParamInfo[] {};
Global.registerParams(Chicken.class, chParam);
}
// ----------------------------------------------
public Chicken()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 2;
setNumActions(numActions);
initMatrix();
}
protected void checkParameters() throws Exception
{
}
protected String getGameHelp()
{
return "Creates a 2x2 Chicken Game" + getRangeHelp();
}
public void randomizeParameters()
{
}
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
setDescription("Chicken\n"
+ getDescription());
setName("Chicken");
SortedAndRandomSet payoffValues = new SortedAndRandomSet();
// Generate four payoff values in the range from
// payoff_low to payoff_high. Make sure the four values
// are distinct.
for (int i = 0; i < 4; i++) {
Double randomPayoffAsDouble;
do {
double randomPayoff = Global.randomDouble(low, high);
randomPayoffAsDouble = new Double(randomPayoff);
} while (!(payoffValues.add(randomPayoffAsDouble)));
}
Double a = (Double) payoffValues.removeLargest();
Double b = (Double) payoffValues.removeLargest();
Double c = (Double) payoffValues.removeLargest();
Double d = (Double) payoffValues.removeLargest();
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
outcome.reset();
setPayoff(outcome.getOutcome(), 0, b.doubleValue());
setPayoff(outcome.getOutcome(), 1, b.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, a.doubleValue());
setPayoff(outcome.getOutcome(), 1, c.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, c.doubleValue());
setPayoff(outcome.getOutcome(), 1, a.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, d.doubleValue());
setPayoff(outcome.getOutcome(), 1, d.doubleValue());
}
}
| 2,977 | 23.016129 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/CollaborationGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return an instance of a collaboration game.
*
* Note that our definition of a regular coordination games
* allows for the values of different equilibria to be
* Pareto-ordered but not necessarily all the same. In contrast,
* the Collaboration Game demands that all equilibria yield the
* same payoff.
*
* Both the coordination game and the collaboration game
* are common payoff.
*/
public class CollaborationGame extends CoordinationGame
{
// Parameters: The collaboration game uses the same
// parameters as the coordination game.
static {
Global.registerParams(CollaborationGame.class, cgParam);
}
// ----------------------------------------------
public CollaborationGame()
throws Exception
{
super();
}
protected String getGameHelp()
{
return "Creates a collaboration game.\n\nBy our definition, " +
"both coordination and collaboration games are common payoff " +
"yet not always symmetric. The highest payoffs are for " +
"all outcomes in which every player chooses the same " +
"action. In the collaboration game (unlike in the general " +
"coordiation game) these outcomes will all yield the same " +
"payoff.\n\n" +
"By default, payoffs will be in the range [-100, 100] with " +
"all coordinated payoffs set to 100 for each player. " +
"To change this range, use the normalization or " +
"integer payoff options.";
}
/**
* Generates one payoff for every outcome, making sure that
* all of the equilibrium outcomes (those on the diagonal
* of the matrix) are higher than all of the non-equilibrium
* outcomes and all equal.
*/
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
double lowEq = (high - low) / 2.0;
setDescription("Collaboration Game\n" + getDescription());
setName("Collaboration Game");
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
// Choose the payoff for all equilibria in advance since
// this will always be the same.
double eqPay = Global.randomDouble(lowEq, high);
for (outcome.reset(); outcome.hasMoreOutcomes();
outcome.nextOutcome()) {
int[] actions = outcome.getOutcome();
boolean isEquilib = true;
double pay;
for (int i = 1; i < getNumPlayers(); i++) {
if (actions[0] != actions[i]) {
isEquilib = false;
break;
}
}
if (isEquilib) {
pay = eqPay;
} else {
pay = Global.randomDouble(low, lowEq - 1);
}
setPayoff(outcome.getOutcome(), pay);
}
}
}
| 3,292 | 27.145299 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/CompoundGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import edu.stanford.multiagent.gamer.graphs.*;
/**
* Class implements any compound game. Can be extended to
* generate N-player version of any symmetric 2x2 game.
*/
public abstract class CompoundGame extends GraphicalGame
{
/**
* Construct a new Compound game.
*/
public CompoundGame()
throws Exception
{
super();
}
/**
* Sets the number of players from the command line parameter,
* sets the number of actions to 2 for each player, and
* initializes the graph. All child classes should call
* this function for initialization.
*
* @throws Exception if, for example, there is a problem
* initializing the graph
*/
public void initialize()
throws Exception
{
super.initialize();
// The number of players is extensible but the number
// of actions must always be 2
int players = (int) getLongParameter(Game.players.name);
setNumPlayers(players);
int numActions[];
numActions = new int[players];
for (int i = 0; i < players; i++)
numActions[i] = 2;
setNumActions(numActions);
initGraph();
}
/**
* Initializes a complete graph with the number of nodes
* equal to the number of players in the game.
*/
protected void initGraph() {
try {
graph = new CompleteGraph(getNumPlayers(), false);
graph.initialize();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(graph.getHelp());
Global.handleError(e, "Error initializing graph:");
}
}
/**
* Sets up the compound game as a graphical game (polymatrix,
* really) with each submatrix being in the form
* R, R S, T
* T, S P, P
* for whatever values of R, S, T, and P are passed in.
*
* @param R
* @param S
* @param T
* @param P
*/
protected void generatePolymatrixGame(double R, double S,
double T, double P) {
// Generate the complete graph.
graph.doGenerate();
// The same DoubleTensor will be used for all subgames
// in the polymatrix game
int[] dimensions = new int[2];
int[] indices = new int[2];
dimensions[0] = dimensions[1] = 2;
// Create a new DoubleTensor to hold the symmetric matrix
// and fill in the values of R, S, T, and P in the
// appropriate spots
DoubleTensor symMatrix = new DoubleTensor(dimensions);
indices[0] = 1;
indices[1] = 1;
symMatrix.setValue(R, indices);
indices[0] = 1;
indices[1] = 2;
symMatrix.setValue(S, indices);
indices[0] = 2;
indices[1] = 1;
symMatrix.setValue(T, indices);
indices[0] = 2;
indices[1] = 2;
symMatrix.setValue(P, indices);
// Now add edges to the graph for the game between each
// pair of distinct players in each direction using the
// symmetric matrix as the edge object
for (int i = 0; i < getNumPlayers(); i++) {
for (int j = 0; j < getNumPlayers(); j++) {
if (i != j) {
try {
graph.setEdgeData(i, j, symMatrix);
} catch (Exception e) {
System.out.println("Error setting graph values");
e.printStackTrace();
System.exit(1);
}
}
}
}
}
}
| 3,817 | 24.118421 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/CongestionGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Class implements a congestion game in which there
* is a set of "facilities" and each player chooses some
* subset of these. The payoffs for players are based only
* on which facilities they have chosen and how many other
* players have chosen the same facilities.
*
*/
public class CongestionGame extends Game
{
// Need to store functions for each player for each
// facility
private Function[][] payFuncs;
private boolean randomize;
//-----------------------------------------------------
// Parameters: The congestion game is parameterized by
// the number of players, the number of facilities,
// the function type (should be nonincreasing) and
// parameters, and a symmetric boolean indicating
// whether or not all players should have the same
// payoff functions.
private static Parameters.ParamInfo pFacilities;
private static Parameters.ParamInfo pFunc;
private static Parameters.ParamInfo pFuncArgs;
private static Parameters.ParamInfo pSym;
private static Parameters.ParamInfo[] cgParam;
static {
pFacilities = new Parameters.ParamInfo("facilities", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(5), "number of facilities in set. Since each player chooses a subset of the facilities, the number of actions available to each player is 2 to the number of facilities. A maximum of five facilities is allowed because of this extremely fast growth in matrix size.");
pFunc = new Parameters.ParamInfo("func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the payoff functions. Should either be a class which always creates decreasing functions, or a class which can be parameterized to create decreasing functions.");
pFuncArgs = new Parameters.ParamInfo("func_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the function, must be enclosed in []. If the function class in use does not always create decreasing functions, the parameters should be set so that the function is decreasing.");
pSym = new Parameters.ParamInfo("sym_funcs", Parameters.ParamInfo.BOOLEAN_PARAM, null, null, "should be true if it is desired that all players have the same set of payoff functions.");
cgParam = new Parameters.ParamInfo[] {Game.players, pFacilities,
pFunc, pFuncArgs, pSym};
Global.registerParams(CongestionGame.class, cgParam);
}
public CongestionGame()
throws Exception
{
super();
}
/**
* Set the parameters for the game itself. The parameters for
* the payoff functions will be set later.
*/
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
}
public void initialize()
throws Exception
{
super.initialize();
// The number of players is specified by the user
int players = (int) getLongParameter(Game.players.name);
setNumPlayers(players);
// The number of actions for each player is equal to
// (2 to the number of facilities) - 1
int facilities = (int) getLongParameter(pFacilities.name);
setNumActions((int) Math.pow(2, facilities) - 1);
// Create and initialize the appropriate number of
// functions in the function array
initializeFunctionArray();
}
/**
* Create the array of functions and initialize them
* all with the appropriate parameters.
*/
protected void initializeFunctionArray() {
String funcName = parameters.getStringParameter(pFunc.name);
ParamParser funcParams = parameters.getParserParameter(pFuncArgs.name);
int facs = (int) getLongParameter(pFacilities.name);
// If all players have the same set of utility
// functions, only need to create one for each
// facility. Otherwise need to create players * facs
// functions total.
if (getBooleanParameter(pSym.name)) {
payFuncs = new Function[1][facs];
for (int i = 0; i < facs; i++) {
payFuncs[0][i] = (Function)
Global.getObjectOrDie(funcName, Global.FUNC);
try {
payFuncs[0][i].setDomain(0, getNumPlayers());
payFuncs[0][i].setParameters(funcParams, randomize);
payFuncs[0][i].initialize();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(payFuncs[0][i].getHelp());
Global.handleError(e, "Couldn't initialize functions.");
}
}
} else {
int players = getNumPlayers();
payFuncs = new Function[players][facs];
for (int j = 0; j < players; j++) {
for (int i = 0; i < facs; i++) {
payFuncs[j][i] = (Function)
Global.getObjectOrDie(funcName, Global.FUNC);
try {
payFuncs[j][i].setDomain(0, getNumPlayers());
payFuncs[j][i].setParameters(funcParams, randomize);
payFuncs[j][i].initialize();
} catch (Exception e) {
Global.handleError(e, "Couldn't initialize functions");
}
}
}
}
}
protected void checkParameters() throws Exception
{
if(!Global.isPartOf(Global.FUNC, getStringParameter(pFunc.name), "DecreasingFunction"))
throw new Exception ("Function must be decreasing!");
}
public void randomizeParameters() {
super.randomizeParameters();
try {
if(!parameters.isParamSet(pFunc.name))
parameters.setParameter(pFunc.name,
Global.getRandomClass(Global.FUNC, "DecreasingFunction"));
parameters.setParameter(pFuncArgs.name, new ParamParser());
} catch (Exception e) {
Global.handleError(e, "Randomizing Params");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
protected String getGameHelp()
{
return "Creates a congestion game.\n\n" +
"In the congestion game, each " +
"player chooses a subset from the set of all facilities. " +
"Each player then receives a payoff which is the sum " +
"of payoff functions for each facility in the chosen " +
"subset. Each payoff function depends only on the " +
"number of other players who have chosen the facility.\n\n" +
"Functions used with this generator should always be " +
"decreasing in order for the resulting game to meet the " +
"criteria for being considered a congestion game.";
}
/**
* Returns true if facility fac is selected for action act.
* Treats numbers as if they are in binary and the digits
* set to 1 are facitilies, only is off by 1 since it is not
* legal for an action to consist of the empty set.
*/
protected boolean didChooseFac(long action, int fac) {
if ((((int) action) % ((int) Math.pow(2, fac+1))) >=
(int) Math.pow(2, fac))
return true;
return false;
}
/**
* Return the payoff for a given player at a given outcome. This
* payoff is based on the facilities in the subset the player has
* chosen and the number of other players who have chosen each
* of these facilities.
*/
public double getPayoff(int[] outcome, int player) {
int players = getNumPlayers();
int facs = (int) getLongParameter(pFacilities.name);
int[] numChosen = new int[facs];
// Get a count of how many players chose each facility
for (int i = 0; i < facs; i++) {
numChosen[i] = 0;
for (int j = 0; j < players; j++) {
if (didChooseFac(outcome[j], i)) {
numChosen[i]++;
}
}
}
// Sum the functions for all of the facilities chosen
// by player to get the payoff
double payoff = 0;
for (int i = 0; i < facs; i++) {
if (didChooseFac(outcome[player], i)) {
if (getBooleanParameter(pSym.name)) {
payoff += payFuncs[0][i].eval(numChosen[i]);
} else {
payoff += payFuncs[player][i].eval(numChosen[i]);
}
}
}
return payoff;
}
/**
* It is more efficient to calculate all payoffs for all players
* in a given outcome at once since the number of players who
* have chosen each facility will only have to be calculated once.
*/
public Vector getPayoff(int[] outcome) {
int players = getNumPlayers();
int facs = (int) getLongParameter(pFacilities.name);
int[] numChosen = new int[facs];
// Get a count of how many players chose each facility
for (int i = 0; i < facs; i++) {
numChosen[i] = 0;
for (int j = 0; j < players; j++) {
if (didChooseFac(outcome[j], i)) {
numChosen[i]++;
}
}
}
// For each player, sum the functions for all of the
// facilities chosen by player to get the payoff
Vector payoffs = new Vector();
for (int player = 0; player < players; player++) {
double payoff = 0;
for (int i = 0; i < facs; i++) {
if (didChooseFac(outcome[player], i)) {
if (getBooleanParameter(pSym.name)) {
payoff += payFuncs[0][i].eval(numChosen[i]);
} else {
payoff += payFuncs[player][i].eval(numChosen[i]);
}
}
}
payoffs.add(new Double(payoff));
}
return payoffs;
}
/**
* Generate all of the payoff functions for each player
* for each facility
*/
public void doGenerate() {
setName("Congestion Game");
int players = getNumPlayers();
int facs = (int) getLongParameter(pFacilities.name);
if (getBooleanParameter(pSym.name)) {
for (int i = 0; i < facs; i++) {
payFuncs[0][i].doGenerate();
}
} else {
for (int j = 0; j < players; j++) {
for (int i = 0; i < facs; i++) {
payFuncs[j][i].doGenerate();
}
}
}
}
}
| 10,198 | 29.085546 | 376 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/CoordinationGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return an instance of a coordination game.
*
* Note that our definition of coordination games allows
* for the values of different equilibria to be Pareto-ordered
* but not necessarily all the same. If it is desired that
* all equilibria yield the same payoff, the collaboration
* game should be used.
*
* Both the coordination game and the collaboration game
* are common payoff.
*/
public class CoordinationGame extends PureCoordinationMatrix
{
// Parameters: Just the number of players
protected static Parameters.ParamInfo[] cgParam;
static {
cgParam = new Parameters.ParamInfo[] {Game.players};
Global.registerParams(CoordinationGame.class, cgParam);
}
// ----------------------------------------------
public CoordinationGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// Set the number of players
if(!parameters.isParamSet(Game.players.name))
Global.handleError("Required parameter missing: players");
setNumPlayers((int)getLongParameter(Game.players.name));
// The number of actions for each player will always
// be equal to the number of players
int numActions[];
numActions = new int[getNumPlayers()];
for (int i = 0; i < getNumPlayers(); i++)
numActions[i] = getNumPlayers();
setNumActions(numActions);
// Must be called for all subclasses of
// PureCoordinationMatrix
initMatrix();
}
protected void checkParameters() throws Exception
{
}
public void randomizeParameters() {
}
protected String getGameHelp()
{
return "Creates a Coordination Game.\n\nBy our definition, " +
"coordination games are common payoff yet not always " +
"symmetric. The highest payoffs are for all outcomes " +
"in which every player chooses the same action, although " +
"it is not always the case that all of these outcomes " +
"yield the same payoffs. (See collaboration games.)\n\n" +
"By default, payoffs will be in the range [-100, 100] with " +
"coordinated payoffs positive and uncoordinated payoffs " +
"negative. To change this range, use the normalization or " +
"integer payoff options.";
}
/**
* Generate one payoff for every outcome, making sure that
* all of the equilibrium outcomes (those on the diagonal
* of the matrix) are higher than all of the non-equilibrium
* outcomes.
*/
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
double lowEq = high - ((high - low) / 2.0);
setDescription("Coordination Game\n" + getDescription());
setName("Coordination Game");
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
for (outcome.reset(); outcome.hasMoreOutcomes();
outcome.nextOutcome()) {
int[] actions = outcome.getOutcome();
boolean isEquilib = true;
double pay;
for (int i = 1; i < getNumPlayers(); i++) {
if (actions[0] != actions[i]) {
isEquilib = false;
break;
}
}
if (isEquilib) {
pay = Global.randomDouble(lowEq, high);
} else {
pay = Global.randomDouble(low, lowEq);
}
setPayoff(outcome.getOutcome(), pay);
}
}
}
| 3,948 | 26.047945 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/CournotDuopoly.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Return an instance of the Cournot Duopoly using user
* specified functions for the cost and inverse demand.
* Allows the cost functions for both players to be
* parameterized separately.
*
* Note that although the Cournot Duopoly could be extended
* in a somewhat straight forward way to more than two
* players, this game is not generally studied in economics.
* Therefore we limit the duopoly to a two player game.
*/
public class CournotDuopoly extends Game
{
private Function[] costFuncs;
private Function pFunc;
private boolean randomize=false;
// -----------------------------------------------------
// Parameters: The Cournot Duopoly is parameterized by
// specifying the function classes and function params for
// both players' cost functions and the inverse demand
// function as well as the range of actions allowed.
//
private static Parameters.ParamInfo pCostFunc1;
private static Parameters.ParamInfo pCostFunc2;
private static Parameters.ParamInfo pCostArgs1;
private static Parameters.ParamInfo pCostArgs2;
private static Parameters.ParamInfo pPFunc;
private static Parameters.ParamInfo pPArgs;
private static Parameters.ParamInfo[] courParam;
static {
pCostFunc1 = new Parameters.ParamInfo("cost_func1", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the cost function for the first player.");
pCostArgs1 = new Parameters.ParamInfo("cost_params1", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the cost function for player 1, must be enclosed in [].");
pCostFunc2 = new Parameters.ParamInfo("cost_func2", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the cost function for the second player.");
pCostArgs2 = new Parameters.ParamInfo("cost_params2", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the cost function for player 2, must be enclosed in [].");
pPFunc = new Parameters.ParamInfo("p_func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use for the inverse demand function P.");
pPArgs = new Parameters.ParamInfo("p_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the inverse demand function, must be enclosed in [].");
courParam = new Parameters.ParamInfo[]
{Game.symActions, pCostFunc1, pCostArgs1, pCostFunc2, pCostArgs2,
pPFunc, pPArgs};
Global.registerParams(CournotDuopoly.class, courParam);
}
// -------------------------------------------------------
public CournotDuopoly()
throws Exception
{
super();
}
/**
* Set the parameters for the game itself, and parse and
* set the parameters for the cost and inverse demand
* functions.
*/
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
}
public void initialize()
throws Exception
{
super.initialize();
// The number of players will always be 2 in the duopoly.
setNumPlayers(2);
parseSameNumberActions();
// Get the type of the cost functions and the inverse
// demand function, create the three function objects,
// and parse the function parameters
costFuncs = new Function[2];
String costName1 = parameters.getStringParameter(pCostFunc1.name);
ParamParser costParams1 = parameters.getParserParameter(pCostArgs1.name);
costFuncs[0] = (Function) Global.getObjectOrDie(costName1,
Global.FUNC);
try {
costFuncs[0].setDomain(1, getNumActions(0));
costFuncs[0].setParameters(costParams1, randomize);
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(costFuncs[0].getHelp());
Global.handleError(e, "Error parsing cost function params");
}
String costName2 = parameters.getStringParameter(pCostFunc2.name);
ParamParser costParams2 = parameters.getParserParameter(pCostArgs2.name);
costFuncs[1] = (Function) Global.getObjectOrDie(costName2,
Global.FUNC);
try {
costFuncs[1].setDomain(1, getNumActions(0));
costFuncs[1].setParameters(costParams2, randomize);
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(costFuncs[1].getHelp());
Global.handleError(e, "Error parsing cost function params");
}
String pName = parameters.getStringParameter(pPFunc.name);
ParamParser pParams = parameters.getParserParameter(pPArgs.name);
pFunc = (Function) Global.getObjectOrDie(pName, Global.FUNC);
try {
pFunc.setDomain(2, 2 * getNumActions(0));
pFunc.setParameters(pParams, randomize);
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(pFunc.getHelp());
Global.handleError(e, "Error parsing p function params");
}
// Initialize all functions
costFuncs[0].initialize();
costFuncs[1].initialize();
pFunc.initialize();
}
protected void checkParameters() throws Exception
{
if (!Global.isPartOf(Global.FUNC,
getStringParameter(pCostFunc1.name),
"IncreasingFunction") ||
!Global.isPartOf(Global.FUNC,
getStringParameter(pCostFunc2.name),
"IncreasingFunction"))
throw new Exception("Cost functions must be increasing!");
}
public void randomizeParameters()
{
try {
if(!parameters.setByUser(pCostFunc1.name))
parameters.setParameter(pCostFunc1.name,
Global.getRandomClass(Global.FUNC,"IncreasingFunction"));
if(!parameters.setByUser(pCostFunc2.name))
parameters.setParameter(pCostFunc2.name,
Global.getRandomClass(Global.FUNC, "IncreasingFunction"));
if(!parameters.setByUser(pPFunc.name))
parameters.setParameter(pPFunc.name,
Global.getRandomClass(Global.FUNC, "IncreasingFunction"));
} catch (Exception e) {
Global.handleError(e, "Randomizing Functions");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
protected String getGameHelp()
{
return "Create an instance of the Cournot Duopoly using " +
"arbitrary cost and inverse demand functions.\n\nIn " +
"order for the problem to make sense, the cost " +
"functions used should be increasing. If C1 and C2 " +
"are cost functions and P is the inverse demand function " +
"then if player 1 plays y1 and player 2 plays y2, the " +
"payoff to player 1 will be \n P(y1+y2)y1-C1(y1)\nand the " +
"payoff to player 2 will be \n P(y1+y2)y2-C2(y2)\n\n" +
"Although this formulation could be extended to more " +
"than two players, this is generally not done in " +
"practice so we limit the players to 2.";
}
/**
* Return the payoff for the given player in the given outcome.
* If Ci is a cost function for player i and P is the inverse
* demand function and each player j chooses action yj then
* the payoff for player i is
*
* P(y1+y2)yi - Ci(yi)
*/
public double getPayoff(int[] outcome, int player)
{
int y[] = new int[2];
for (int i = 0; i < 2; i++)
y[i] = outcome[i];
double payoff = (double) (pFunc.eval(y[0] + y[1]) * y[player] -
costFuncs[player].eval(y[player]));
return payoff;
}
/**
* Generate the inverse demand and cost functions.
*/
public void doGenerate()
{
setDescription("Cournot Duopoly\n" + getDescription());
setName("Cournot Duopoly");
pFunc.doGenerate();
costFuncs[0].doGenerate();
costFuncs[1].doGenerate();
}
}
| 8,388 | 30.776515 | 193 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/CovariantGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import Jama.*;
/**
* Return a game, where payoffs for players are drawn from
* a multi-normal with covariance r.
*/
public class CovariantGame extends MatrixGame
{
// -- Parameters:
// number of players and the number of actions
// covariance r
private static Parameters.ParamInfo[] cvgParam;
private static Parameters.ParamInfo rParam;
static {
rParam = new Parameters.ParamInfo("r", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1), new Double(1), "covariance of any two player's payoffs in the same action profile. Must be between -1/(#players-1) and 1.", false, new Double(0.5));
cvgParam = new Parameters.ParamInfo[] {Game.players, Game.actions, rParam};
Global.registerParams(CovariantGame.class, cvgParam);
}
// ----------------------------------------------
/**
* Construct a new game
*/
public CovariantGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
parsePlayersActions();
initMatrix();
}
protected void checkParameters() throws Exception
{
int n = (int)getLongParameter(Game.players.name);
double r = getDoubleParameter(rParam.name);
if(r < -1.0/ (double)(n-1))
throw new Exception("Correlation must be >= -1/(n-1)");
}
public void randomizeParameters() {
int n = (int)getLongParameter(Game.players.name);
rParam.low = new Double(-1.0/(double)(n-1));
parameters.randomizeParameter(rParam.name);
}
/**
* Returns the help screen
*/
protected String getGameHelp()
{
return "Creates a game with the given number of players " +
"with payoffs distributed normally(0,1) with covariance r." +
getRangeHelp();
}
/**
* Fills in the payoffs
*/
public void doGenerate()
{
setDescription("A Game With Normal Covariant Random Payoffs\n"
+ getDescription());
setName("Random Normal-Covariant Matrix Game");
double r = getDoubleParameter(rParam.name);
// double a = Math.sqrt(r);
// double b = Math.sqrt(1-r);
double[][] a = new double[getNumPlayers()][getNumPlayers()];
for(int i=0; i<getNumPlayers(); i++)
for(int j=0; j<getNumPlayers(); j++)
a[i][j]= (i==j ? 1 : r);
Matrix sigma=new Matrix(a, getNumPlayers(), getNumPlayers());
CholeskyDecomposition chol = sigma.chol();
if(!chol.isSPD())
System.err.println("WARNING: SIGMA is not SPD!");
Matrix lMat = chol.getL();
double[][] z=new double[getNumPlayers()][1];
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
for(outcome.reset(); outcome.hasMoreOutcomes(); outcome.nextOutcome())
{
// double x=Global.rand.nextGaussian();
// for(int i=0; i<getNumPlayers(); i++)
// {
// double y = Global.rand.nextGaussian();
// setPayoff(outcome.getOutcome(), i, a*x+b*y);
// }
for(int i=0; i<z.length; i++)
z[i][0]=Global.rand.nextGaussian();
Matrix m = new Matrix(z, z.length, 1);
Matrix x = lMat.times(m);
for(int i=0; i<getNumPlayers(); i++)
setPayoff(outcome.getOutcome(), i, x.get(i,0));
}
}
}
| 3,862 | 25.278912 | 242 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/DispersionGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Class implements a specific kind of dispersion game:
* both action symmetric and agent symmetric as defined in
* the dispersion games literature, also strong,
* and common payoff.
*
* It is not required that the number of players be
* equal to the number of actions.
*
* The dispersion ordering used is a full ordering where
* one outcome is more dispersed than another if the entropy
* is higher. (Other implementations could have been used,
* such as keeping the partial ordering or using standard
* deviation, but the entropy-based ordering is easy to
* implement and equally valid.)
*/
public class DispersionGame extends Game
{
// Need a data structure to map entropy values to payoffs
private HashMap payoffs;
//-----------------------------------------------
// Parameters: The dispersion game is parameterized
// by the number of players and the number of actions.
//
private static Parameters.ParamInfo[] dgParam;
static {
dgParam = new Parameters.ParamInfo[] {Game.players, Game.symActions};
Global.registerParams(DispersionGame.class, dgParam);
}
// ---------------------------------------------------------
public DispersionGame()
throws Exception
{
super();
}
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
}
/**
* Initialize the dispersion game by setting the number
* of players and the number of actions and creating the
* hashmap for storing entropy/payoff pairs.
*/
public void initialize()
throws Exception
{
super.initialize();
parsePlayersSameNumberActions();
payoffs = new HashMap();
}
/**
* Return the entropy of the given array assuming that
* the values in the array add up to total
*/
private double getEntropy(int[] a, long total) {
double entropy = 0;
for (int i = 0; i < a.length; i++) {
double prob = (double) a[i] / (double) total;
if (prob != 0) {
double logBase2 = Math.log(prob) / Math.log(2);
entropy -= logBase2 * prob;
}
}
// Round to the nearest 0.00001 so that doubles which
// are off by a very small amount will be treated as
// the same
entropy = Math.round(entropy / 0.00001) * 0.00001;
return entropy;
}
/**
* The payoff will be the same for each player, based
* on how dispersed the actions are as a whole.
*/
public double getPayoff(int[] outcome, int player)
{
// Make an array which holds the number of players
// who chose each action
int actions = getNumActions(0);
int[] actionDist = new int[actions];
for (int i = 0; i < actions; i++) actionDist[i] = 0;
for (int i = 0; i < getNumPlayers(); i++) {
int chosen = outcome[i] - 1;
actionDist[chosen]++;
}
double entropy = getEntropy(actionDist, getNumPlayers());
Double entDoub = new Double(entropy);
if (!payoffs.containsKey(entDoub))
Global.handleError("Payoff not found for given entropy");
Double payDouble = (Double) payoffs.get(entDoub);
return payDouble.doubleValue();
}
/**
* Since the game is common payoff, it is much more
* efficient to get all payoffs at once.
*/
public Vector getPayoff(int[] outcome)
{
Vector payVector = new Vector();
// Make an array which holds the number of players
// who chose each action
int actions = getNumActions(0);
int[] actionDist = new int[actions];
for (int i = 0; i < actions; i++) actionDist[i] = 0;
for (int i = 0; i < getNumPlayers(); i++) {
int chosen = outcome[i] - 1;
actionDist[chosen]++;
}
double entropy = getEntropy(actionDist, getNumPlayers());
Double entDoub = new Double(entropy);
if (!payoffs.containsKey(entDoub))
Global.handleError("Payoff not found for given entropy");
Double payDouble = (Double) payoffs.get(entDoub);
for (int i = 0; i < getNumPlayers(); i++) {
payVector.add(payDouble);
}
return payVector;
}
//
// None to check
//
protected void checkParameters() throws Exception
{
}
//
// Nothing to randomize
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Returns a strong dispersion game which is both " +
"action and player symmetric as well as common payoff. " +
"An entropy calculation is used in order to determine " +
"when one outcome is more dispersed than another, " +
"although this could easily be replaced by standard " +
"deviation or a similar test." +
getRangeHelp();
}
/**
* Generate all groupings of outcomes that will have the
* same entropy with the given number of players and number
* of actions. Generate a list of payoffs of length equal
* to the number of groups. Sort the groups by entropy
* and assign payoffs, always assigning higher payoffs to
* groups with higher entropies.
*/
public void doGenerate()
{
setDescription("Dispersion Game\n" + getDescription());
setName("Dispersion Game");
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
SortedAndRandomSet entropies = new SortedAndRandomSet();
int actions = getNumActions(0);
int players = getNumPlayers();
// Fill in the entropies vector by generating
// the sequence of possible unique outcomes and
// calculating the entropy for each.
//
// For example, the sequence of ways that 9 symmetric
// players can disperse over 5 outcomes is
//
// 90000, 81000, 72000, 71100, 63000, 62100, 61110,
// 54000, 53100, 52200, 52110, 51111, 44100, 43200,
// 43110, 42210, 42111, 33300, 33210, 33111, 32220,
// 32211, 22221
int[] outcome = new int[actions];
outcome[0] = players;
for (int i = 1; i < actions; i++) outcome[i] = 0;
// Store the initial entropy before looping through
// the rest of the sequence
Double ent = new Double(getEntropy (outcome, players));
entropies.add(ent);
int remainder = 0;
while (outcome[0] != 1) {
int i = actions - 1;
// Search for the last spot in the array which is
// not 0 or 1. Add all of the 1s to remainder.
while (outcome[i] <= 1) {
remainder += outcome[i];
i--;
}
// When an spot is found that has a value of 2 or
// more, subtract one and split the remainder over
// the rest of the array making sure that no spot
// has a higher value than the one before.
outcome[i]--;
remainder++;
for (int j = i+1; j < actions; j++) {
outcome[j] = Global.min(remainder, outcome[i]);
remainder -= outcome[j];
}
// If there is no remainder left then there were
// enough actions available to fit the players in this
// particular step of the sequence. Add it to the
// list. Otherwise, do not add to the sequence and
// keep the remainder set to add back in.
//
// For example, in the sequence described above for
// 9 players and 5 actions, 22221 should be added but
// 22211 which is generated next should not.
if (remainder == 0) {
ent = new Double(getEntropy (outcome, players));
entropies.add(ent);
}
}
int numPayoffs = entropies.size();
// Use a SortedAndRandomSet for the payoff values since
// it does not allow repeats of values and keeps the
// values sorted
SortedAndRandomSet payoffValues = new SortedAndRandomSet();
for (int i = 0; i < numPayoffs; i++) {
Double randomPayoffAsDouble;
do {
double randomPayoff = Global.randomDouble(low, high);
randomPayoffAsDouble = new Double(randomPayoff);
} while (!(payoffValues.add(randomPayoffAsDouble)));
}
// Now match each payoff with an entropy value and
// add each pair to the hashmap
for (int i = 0; i < numPayoffs; i++) {
Double nextPayoff = (Double) payoffValues.removeSmallest();
Double entDoub = (Double) entropies.removeSmallest();
payoffs.put(entDoub, nextPayoff);
}
}
}
| 8,680 | 26.128125 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/DoubleOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* Outputs a game in the gambit and gametracer output formats
* Separated by SEP
*/
public class DoubleOutput extends GameOutput
{
public static final String SEP = "========================================";
public void writeGame(PrintWriter out, Game g)
throws Exception
{
GambitOutput nfg = new GambitOutput();
GTOutput gam = new GTOutput();
nfg.writeGame(out, g);
out.println(SEP);
gam.writeGame(out, g);
}
}
| 1,163 | 25.454545 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/DoubleTensor.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* The DoubleTensor class can be used to store matrices
* of any dimension.
*/
public class DoubleTensor {
private int numDimensions;
private int[] dimensionSize;
private double values[];
/**
* Constructor
*
* @param dimSize an array holding the size of the tensor
* in each dimension.
*/
public DoubleTensor(int[] dimSize) {
int valueArraySize = 1;
numDimensions = dimSize.length;
dimensionSize = new int[numDimensions];
for (int i = 0; i < numDimensions; i++) {
dimensionSize[i] = dimSize[i];
valueArraySize *= dimensionSize[i];
}
values = new double[valueArraySize];
}
/**
* Translate an array of indices in the tensor into
* an index of the underlying values array. Assumes
* that each index in the array is between 1 and the size
* of that dimension.
*/
private int translateIndices(int[] indices) {
int valueIndex = 0;
for (int i = 0; i + 1 < numDimensions; i++) {
valueIndex += indices[i] - 1;
valueIndex *= dimensionSize[i+1];
}
valueIndex += indices[numDimensions-1] - 1;
return valueIndex;
}
/**
* Set the value stored at the indexed spot in the tensor
*/
public void setValue(double value, int[] indices) {
int valueIndex = translateIndices(indices);
values[valueIndex] = value;
}
/**
* Get the value stored at the indexed spot in the tensor
*/
public double getValue(int[] indices) {
int valueIndex = translateIndices(indices);
return values[valueIndex];
}
public int getNumDimensions() {
return numDimensions;
}
public int getSizeOfDim(int dim) {
return dimensionSize[dim];
}
public int[] getSizeOfDim() {
return dimensionSize;
}
/**
* Probably won't use this much, but occasionally may be
* useful to get all values returned in one array.
*/
public double[] getValues() {
return values;
}
}
| 2,654 | 23.357798 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GTOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* Outputs a game in the Gametracer .gam file format.
*
* Note, unfortunately this format doesn't have comments,
* So it's best to use this output only in conjunction with something else,
* so that comments aren't lost
*/
public class GTOutput extends GameOutput
{
public void writeGame(PrintWriter out, Game g)
throws Exception
{
// -- number of players
out.println(g.getNumPlayers());
// -- actions for each player
for(int i=0; i<g.getNumPlayers(); i++)
out.print(g.getNumActions(i) + " ");
// That's it for the first line..
out.println();
out.println();
// Now print the payoffs in a row
Outcome o = new Outcome(g.getNumPlayers(), g.getNumActions());
for(int i=0; i<g.getNumPlayers(); i++)
{
for(o.reset(); o.hasMoreOutcomes(); o.nextOutcome())
out.print(g.getOutputPayoff(o.getOutcome(), i) + " ");
out.println();
}
}
}
| 1,608 | 26.271186 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GambitOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* Outputs a game in the Gambit .nfg file format.
*
* The format works with Gambit version 0.97.0.3 which is the
* current version. Could eventually need to be updated to work
* with later versions of gambit if the file format is modified.
*/
public class GambitOutput extends GameOutput
{
public void writeGame(PrintWriter out, Game g)
throws Exception
{
// The first line of every .nfg file starts with NFG 1
out.print("NFG 1 ");
// R for rational (I think?). If we allow games to have
// decimal payoffs, we will need to change this to D.
boolean intFlag = Global.params.getBooleanParameter(Game.intPayoffs.name);
if(intFlag)
out.print("R ");
else
out.print("D ");
// Next comes the name of the game, which will be the
// name of the class used to generate plus a generated
// by blurb, for now
//String gName = g.getName() + ", " + GAMER_STRING;
String gName = GAMER_STRING + "\n" +
g.getDescription();
out.print("\"" + gName + "\" ");
// Next print the players in a format like
// { "Player1", "Player2", "Player3" }
out.print("{ ");
for (int i = 1; i <= g.getNumPlayers(); i++)
out.print("\"Player" + i + "\" ");
out.print("} ");
// Still on the first line, print out the number of
// actions for each player in a format like
// {2, 3, 4}
out.print("{ ");
for(int i=0; i<g.getNumPlayers(); i++)
out.print(g.getNumActions(i) + " ");
out.print("} ");
// That's it for the first line..
out.println();
out.println();
// Now print the payoffs in a row
Outcome o = new Outcome(g.getNumPlayers(), g.getNumActions());
for(o.reset(); o.hasMoreOutcomes(); o.nextOutcome())
for(int i=0; i<g.getNumPlayers(); i++)
out.print(g.getOutputPayoff(o.getOutcome(), i) + " ");
out.println();
}
}
| 2,517 | 26.977778 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/Game.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import java.io.*;
/**
* Abstract class that describes the basic game entity.
*/
public abstract class Game extends ParameterizedObject
{
// ------------------------------------------------
// Things related to game data
private int nPlayers;
private int[] nActions;
private String description;
private String gameName;
// For normalization
private boolean minAndMaxSet = false;
private double oldMax;
private double oldMin;
protected static final double DEFAULT_LOW = -100;
protected static final double DEFAULT_HIGH = 100;
/**
* Returns Game Description (Name, Params, etc)
*/
public String getDescription()
{
return description;
}
/**
* Sets the description string for the game which will be
* output as part of the help string.
*
* @param description a description of the game
*/
protected void setDescription(String description)
{
this.description=description;
}
/**
* Returns just the name of the game. Should not have
* any line breaks.
*/
public String getName()
{
return gameName;
}
/**
* Sets the name of the game.
*
* @param name the name of the class of games generated by
* a given game class
*/
protected void setName(String name)
{
this.gameName = name;
}
/**
* Returns the number of players in this game
*/
public int getNumPlayers()
{
return nPlayers;
}
/**
* Sets the number of players in the game.
*
* @param nPlayers the number of players
*/
protected void setNumPlayers(int nPlayers)
{
this.nPlayers=nPlayers;
}
/**
* Returns the number of actions of the given player
* or a vector of Integers with the numbers of actions.
*
* @param player the index of the player whose actions should
* be returned
*/
public int getNumActions(int player)
{
return nActions[player];
}
/**
* Returns an array containing the number of actions that each
* player has.
*/
public int[] getNumActions()
{
return nActions;
}
/**
* Sets same number of actions for each player. The number
* of players in the game must have been set before calling this.
*
* @param nActions the number of actions each player has
*/
protected void setNumActions(int nActions)
throws Exception
{
int players = getNumPlayers();
int val[] = new int[players];
for(int i = 0; i < players; i++)
val[i] = nActions;
setNumActions(val);
}
/**
* Sets the number of actions for each player when each player
* may have a different number of actions.
*
* @param nActions an array containing the number of actions each
* player has
* @throws Exception
*/
protected void setNumActions(int[] nActions)
throws Exception
{
if(nActions.length!=nPlayers)
Global.handleError("Action profile length <> nPlayers!");
this.nActions = nActions;
}
/**
* Writes output in the format specific to this game.
*
* @param out a PrintWriter to which output can be written
* @throws UnsupportedOperationException if the given game subclass
* does not support proprietary output
*/
public void writeGame(PrintWriter out) throws UnsupportedOperationException
{
throw new UnsupportedOperationException("This game does not support proprietary output!");
}
/**
* The consctructor. Must be called by all subclasses.
*
* @throws Exception
*/
protected Game()
throws Exception
{
super();
this.description="";
this.gameName = "";
}
/**
* Initializes using preset parameter values
*
* @throws Exception
*/
public void initialize()
throws Exception
{
super.initialize();
}
/**
* Returns the help screen
*/
public String getHelp()
{
StringBuffer buff=new StringBuffer();
buff.append(Global.wrap(getGameHelp(), 70));
buff.append("\n\nGame Parameters:\n");
buff.append(Global.wrap(parameters.getPrintableInfo(), 70));
return buff.toString();
}
/**
* Adds range help information to games which use the range
* DEFAULT_LOW through DEFAULT_HIGH.
*/
public String getRangeHelp()
{
return "\n\nBy default, all payoffs will fall in the range " +
"[" + (int) DEFAULT_LOW + ", " + (int) DEFAULT_HIGH +
"]. This range can be altered by setting the " +
"normalization options or using integer payoffs.";
}
/**
* The generate interface. Calls the game specific doGenerate
* function.
*/
public void generate() throws Exception
{
StringBuffer buff = new StringBuffer();
buff.append("Game Parameter Values:\n");
buff.append("Random seed:\t" + Global.randSeed + "\n");
buff.append("Cmd Line:\t" + GameOutput.arrayToString(Global.gArgs, " ") + "\n");
buff.append("Players:\t" + nPlayers + "\n");
buff.append("Actions:\t");
for(int i=0; i<nPlayers; i++)
buff.append(nActions[i] + (i==nPlayers - 1 ? "\n" : " "));
buff.append(getParamDescription("\n"));
setDescription(getDescription() + buff.toString());
minAndMaxSet = false;
doGenerate();
}
// ----------------------------------------------------------------
// The following four functions are used for parsing the parameters
// for number of players and numbers of actions under different
// cicumstances.
/**
* Parses only the parameter for the number of actions,
* allowing either the same number for all players, or
* different numbers for each.
*
* @throws Exception
*/
protected void parseActions()
throws Exception
{
int val[] = Global.parseIntArray((Vector)getParameter(Game.actions.name));
if(val.length==1)
{
int[] a=new int[getNumPlayers()];
for(int i=0; i<a.length; i++)
a[i]=val[0];
val=a;
}
else if (val.length!=getNumPlayers())
Global.handleError("Must have one #actions for every player!");
setNumActions(val);
}
/**
* Parses action/player parameters and sets them.
*
* @throws Exception
*/
protected void parsePlayersActions()
throws Exception
{
if(!parameters.isParamSet(Game.players.name))
Global.handleError("Required parameter missing: players");
if(!parameters.isParamSet(Game.actions.name))
Global.handleError("Required parameter missing: actions");
setNumPlayers((int)getLongParameter(Game.players.name));
parseActions();
}
/**
* Parses only the parameter for number of actions. Requires
* that all players have the same number of actions, in other
* words, number of actions is set by a single integer.
*
* @throws Exception if it is not the case that all players have the
* same number of actions
*/
protected void parseSameNumberActions()
throws Exception
{
int val[] = Global.parseIntArray((Vector)getParameter(Game.actions.name));
if(val.length==1) {
int[] a=new int[getNumPlayers()];
for(int i=0; i<a.length; i++)
a[i]=val[0];
val=a;
}
else {
if (val.length != getNumPlayers())
Global.handleError("Must have one #actions for every player!");
int value = val[0];
for (int i = 1; i < getNumPlayers(); i++) {
if (val[i] != value)
Global.handleError("All players must have equal number of actions.");
}
}
setNumActions(val);
}
/**
* Parses action/player parameters and sets them. Requires that all
* players have the same number of actions.
*
* @throws Exception if it is not the case that all players have the
* same number of actions
*/
protected void parsePlayersSameNumberActions()
throws Exception
{
if(!parameters.isParamSet(Game.players.name)) {
System.err.println("ERROR: Required parameter missing: players");
System.err.println(Global.getHelp());
System.err.println(getHelp());
System.exit(1);
}
if(!parameters.isParamSet(Game.symActions.name)) {
System.err.println("ERROR: Required parameter missing: actions");
System.err.println(Global.getHelp());
System.err.println(getHelp());
System.exit(1);
}
setNumPlayers((int)getLongParameter(Game.players.name));
parseSameNumberActions();
}
/**
* Collects payoffs into a vector. Should be used with caution.
* Can be overwritten in subclasses if it is more efficient
* to get all payoffs for each outcome at once.
*
* @param outcome an array containing the action choices of
* all players at the given outcome
*/
public Vector getPayoff(int[] outcome)
{
int players = getNumPlayers();
Vector payoffVector = new Vector(players);
for (int i = 0; i < players; i++) {
Double payoff = new Double(getPayoff(outcome, i));
payoffVector.add(i, payoff);
}
return payoffVector;
}
/**
* Collects all payoffs (one at a time) and figures out the
* min and max. These will later be used for normalization.
* This is very inefficient since it goes through every payoff
* in the game. Should be overwritten in subclasses when
* normalization can be handled more efficiently.
* <p>
* Note that only base double max and min values are calculated
* here, not the converted integer max and min.
*/
public void setNormMinAndMax()
{
int players = getNumPlayers();
Outcome o = new Outcome(getNumPlayers(), getNumActions());
o.reset();
// Initialize the min and max to the first payoff given.
oldMax = getPayoff(o.getOutcome(), 0);
oldMin = getPayoff(o.getOutcome(), 0);
for(o.reset(); o.hasMoreOutcomes(); o.nextOutcome()) {
for (int i = 0; i < getNumPlayers(); i++) {
double nextPay = getPayoff(o.getOutcome(), i);
if (nextPay > oldMax) {
oldMax = nextPay;
} else if (nextPay < oldMin) {
oldMin = nextPay;
}
}
}
minAndMaxSet = true;
}
/**
* Formats and outputs the payoff according to set flags.
*
* @param outcome an array containing all players' action
* choices at the given outcome
* @param player tha player whose payoff should be returned
* @throws Exception
*/
public String getOutputPayoff(int[] outcome, int player)
throws Exception
{
return getOutputPayoff(getPayoff(outcome, player));
}
/**
* Formats and outputs a payoff value according to set flags.
*
* @param payoff the value of the payoff to be formatted
* @throws Exception
*/
public String getOutputPayoff(double payoff)
throws Exception
{
boolean intFlag = Global.params.getBooleanParameter(intPayoffs.name);
boolean normFlag = Global.params.getBooleanParameter(pNormalize.name);
double newMin, newMax;
// If we are using normalization, call the default function
// which will set up Global parameters oldMin and oldMax
// which hold the unnormalized min and max. If these can be
// set more efficiently in another way by some class then
// setNormMinAndMax() can be overwritten.
if (normFlag) {
if (!minAndMaxSet)
setNormMinAndMax();
newMin = Global.params.getDoubleParameter(pMinPayoff.name);
newMax = Global.params.getDoubleParameter(pMaxPayoff.name);
if (oldMax - oldMin == 0.0) {
Global.handleError("Tried to normalize with " +
"oldMax = oldMin");
}
payoff = ((payoff - oldMin) * ((newMax - newMin) /
(oldMax - oldMin))) + newMin;
}
if(intFlag)
{
// Note that if the payoff has already been normalized,
// it is the normalized value that will be further
// converted to integer form. (It would not make sense
// to do this in reverse order as the values would no
// longer be integers. (Here they are no longer in the
// normalized range, but it makes MORE sense.))
long mult = Global.params.getLongParameter("int_mult");
if(Math.abs(payoff)* mult >= Long.MAX_VALUE / mult)
Global.handleError("Payoffs are too big for int output!");
long p=Math.round(mult*payoff);
return String.valueOf(p);
}
else
{
return String.valueOf(payoff);
}
}
/**
* Formats and outputs the payoff after normalization according
* to set flags.
*
* @param outcome an array containing all players' action
* choices at the given outcome
* @param player tha player whose payoff should be returned
*/
public double getNormPayoff(int[] outcome, int player)
{
boolean intFlag = Global.params.getBooleanParameter(intPayoffs.name);
boolean normFlag = Global.params.getBooleanParameter(pNormalize.name);
double newMin, newMax;
double payoff = getPayoff(outcome, player);
// If we are using normalization, call the default function
// which will set up Global parameters oldMin and oldMax
// which hold the unnormalized min and max. If these can be
// set more efficiently in another way by some class then
// setNormMinAndMax() can be overwritten.
if (normFlag) {
if (!minAndMaxSet)
setNormMinAndMax();
newMin = Global.params.getDoubleParameter(pMinPayoff.name);
newMax = Global.params.getDoubleParameter(pMaxPayoff.name);
if (oldMax - oldMin == 0.0) {
Global.handleError("Tried to normalize with " +
"oldMax = oldMin");
}
payoff = ((payoff - oldMin) * (newMax - newMin) /
(oldMax - oldMin)) + newMin;
}
return payoff;
}
/**
* Formats automatically to normalization between 0
* and 1 with double payoffs, regardless of parameters.
*
* @param outcome an array containing all players' action
* choices at the given outcome
* @param player tha player whose payoff should be returned
*/
public double getAutoNormPayoff(int[] outcome, int player)
{
double newMin, newMax;
double payoff = getPayoff(outcome, player);
if (!minAndMaxSet)
setNormMinAndMax();
newMin = -1.0;
newMax = 1.0;
// deal with this case later
if (oldMax - oldMin != 0.0) {
payoff = ((payoff - oldMin) * (newMax - newMin) /
(oldMax - oldMin)) + newMin;
}
return payoff;
}
// ---------------------------------------------------------------
// --------------------------------------------
// -- Abstract things to be done in subclasses
// --------------------------------------------
/**
* Returns a payoff for a given player.
*
* @param outcome array of integers representing which actions
* have been chosen by each player
* @param player the player whose payoff to return
*/
public abstract double getPayoff(int[] outcome, int player);
/**
* Return help screen information about the given game class.
*/
protected abstract String getGameHelp();
//---------------------------------------------
// -- Static stuff
//---------------------------------------------
protected static Parameters.ParamInfo players;
protected static Parameters.ParamInfo actions;
protected static Parameters.ParamInfo symActions;
protected static Parameters.ParamInfo intPayoffs;
protected static Parameters.ParamInfo intMult;
protected static Parameters.ParamInfo pMinPayoff;
protected static Parameters.ParamInfo pMaxPayoff;
protected static Parameters.ParamInfo pNormalize;
static {
players = new Parameters.ParamInfo("players", Parameters.ParamInfo.LONG_PARAM, new Long(2), new Long(100), "the number of players. Must be >= 2 and <= 100.", true,null);
actions = new Parameters.ParamInfo("actions", Parameters.ParamInfo.VECTOR_PARAM, new Long(1), new Long(500), "number of actions. Can be a single number, or a list of numbers - one for each player. Must be >= 1 and may be as large as 500, but note that using large numbers of actions will result in exponentially large games. For most games, the number of actions should be much smaller.", true, null);
// Alternate option for actions parameter, displays message
// that all players must have the same number of actions
symActions = new Parameters.ParamInfo("actions", Parameters.ParamInfo.VECTOR_PARAM, new Long(1), new Long(500), "number of actions. All players must have the same number of actions in this game. Must be >= 1 and may be as large as 500, but note that using large numbers of actions will result in exponentially large games. For most games, the number of actions should be much smaller.", true, null);
// Options for output payoff handling
intPayoffs = new Parameters.ParamInfo("int_payoffs", Parameters.ParamInfo.BOOLEAN_PARAM, null, null, "generate integral payoffs.", false, Boolean.FALSE);
intMult = new Parameters.ParamInfo("int_mult", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(1000000000000L), "a multiplier used before converting payoffs to integers. Defaults to 10000.",false, new Long(10000));
pNormalize = new Parameters.ParamInfo("normalize", Parameters.ParamInfo.BOOLEAN_PARAM, null, null, "use normalization. Note that normalization can result in some error in the last digit of the decimal payoff.", false, Boolean.FALSE);
pMinPayoff = new Parameters.ParamInfo("min_payoff", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-Double.MAX_VALUE), new Double(Double.MAX_VALUE), "minimum payoff in matrix, set if normalization is desired.", false);
pMaxPayoff = new Parameters.ParamInfo("max_payoff", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-Double.MAX_VALUE), new Double(Double.MAX_VALUE), "maximum payoff in matrix, set if normalization is desired.", false);
}
}
| 18,521 | 27.716279 | 405 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GameOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* Super class for all game outputters.
*/
public abstract class GameOutput
{
protected final String GAMER_STRING = "Generated by " + Global.VERSION_STRING;
/**
* Writes the game to the specified PrintWriter. Must be implemented
* by every subclass.
*
* @param out the PrintWriter to which the game should be written
* @param g the Game
*
* @throws Exception if unable to write the game
*/
public abstract void writeGame(PrintWriter out, Game g) throws Exception;
/**
* Properly adds and formats comments to the output in the comment
* format specified.
*
* @param str the string to add comments to
* @param comment the string to use as a comment marker at the
* beginning of a line
*/
public static String commentString(String str, String comment)
{
return comment + str.replaceAll("\n", "\n" + comment);
}
/**
* Converts an array of Strings into one long String in which
* each element of the array is separated from the next by
* the specified seperator.
*
* @param args the array of Strings to convert
* @param sep the separator
*/
public static String arrayToString(String[] args, String sep)
{
StringBuffer buff=new StringBuffer();
for(int i=0; i<args.length; i++) {
buff.append(args[i]);
if (i!=args.length-1)
buff.append(sep);
}
return buff.toString();
}
}
| 2,180 | 27.697368 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GeometricGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Class implements shared details of Geometric Games.
*
* It is assumed that all Geometric Games have two players, and
* that each chooses a subset of elements from a set S as their
* action. There may be limits on the max number of elements from S
* which each may choose, but otherwise choices are unrestricted.
*
* The payoff will always be calculated based on the set which the
* the first ("red") player chooses from S, the set which the second
* ("blue") player chooses from S, and the intersection of these sets.
*
* The payoff function is abstract and must be filled in by each
* subclass of Geometric Game.
*
*/
public abstract class GeometricGame extends Game
{
// Size of the set S
private long setSize;
// Max number of elements players are allowed to choose
private long maxInSubset[];
/**
* Constructor for new geometric games.
*/
public GeometricGame()
throws Exception
{
super();
}
/**
* Initializes all variables common to geometric games.
*
* @param sizeOfSet the total number of items in the set from which
* players will choose
* @param maxInR the maximum number of items that the first player
* will be able to choose from the set
* @param maxInB the maximum number of items that the second player
* will be able to choose from the set
*/
public void initVariables(long sizeOfSet, long maxInR, long maxInB)
{
setSize = sizeOfSet;
// Set the maximum numbers of elements each player is
// allowed to select from his set of choices
maxInSubset = new long[2];
maxInSubset[0] = maxInR;
maxInSubset[1] = maxInB;
}
/**
* Returns the payoff for the given player at the given
* outcome, which must first be translated into subsets of
* the elements which are chosen by each player.
*
* @param outcome an array holding the actions chosen by
* each player
* @param player the player whose payoff to return
*/
public double getPayoff(int[] outcome, int player) {
// First get the sets chosen by each player
BitSet R = actionToSubset(outcome[0], maxInSubset[0]);
BitSet B = actionToSubset(outcome[1], maxInSubset[1]);
// Get a set containing the intersection of the
// sets chosen by the two players
BitSet intersection = (BitSet) R.clone();
intersection.and(B);
double payoff = calculatePayoff(player, R, B, intersection);
return payoff;
}
/**
* Calculates the payoff for a player based on the set chosen
* by player one, the set chosen by player 2, and the intersection
* of these two sets. This function must be overwritten by
* every child class.
*
* @param player the player whose payoff should be returned
* @param R the set chosen by player 1
* @param B the set chosen by player 2
* @param intersection the intersection of the sets chosen by
* players 1 and 2
*/
public abstract double calculatePayoff(int player, BitSet R, BitSet B,
BitSet intersection);
/**
* Translates an integer action number into a subset of S
* containing at most maxElements elements
*
* @param action the integer index of the action
* @param maxElements the maximum number of elements that the
* player who has chosen the given action is allowed to choose
* from the set
*/
private BitSet actionToSubset(int action, long maxElements)
{
BitSet chosenSet = new BitSet((int) setSize);
int actionCounter = action;
int numElements = 1;
// first figure out how many elements should be in the
// set based on the action number
try {
while (actionCounter > Global.NChooseM(setSize, numElements)) {
actionCounter -= Global.NChooseM(setSize, numElements);
numElements++;
}
} catch (Exception e) {
System.out.println("Error in actionToSubset");
chosenSet.clear();
return chosenSet;
}
chosenSet.set(0, numElements, true);
// Cycle through the different possible sets with
// numElements elements selected until we reach the
// proper action counter index
while (actionCounter > 1) {
actionCounter--;
boolean foundClear = false;
int toReset = 0;
int index = 0;
while (!foundClear) {
index = chosenSet.nextSetBit(index) + 1;
if (index < setSize) {
if (!chosenSet.get(index)) {
foundClear = true;
} else {
toReset++;
}
} else {
System.out.println("Error in actionToSubset!!");
chosenSet.clear();
return chosenSet;
}
}
chosenSet.set(0, index, false);
chosenSet.set(0, toReset, true);
chosenSet.set(index, true);
}
return chosenSet;
}
/**
* Returns the number of possible actions for a player choosing
* a set of maximum size maxSize from a set of size fullSetSize.
*
* @param fullSetSize size of the full set
* @param maxSize the maximum number of items that can be chosen
*/
public long getGeoNumActions(long fullSetSize, long maxSize)
throws Exception
{
long totalActions = 0;
for (long i = 1; i <= maxSize; i++)
totalActions += Global.NChooseM(fullSetSize, i);
return totalActions;
}
}
| 5,942 | 28.420792 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/Global.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.jar.*;
import edu.stanford.multiagent.gamer.graphs.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* A Class to hold global parameters, utilities, etc.
*/
public class Global
{
// == NOTE: All static members must be initialized somewhere
// == NOTE: In the main class, or here.
public static String VERSION_STRING = "GAMUT v1.0.1";
// -- Global Random Number Generator
public static Random rand;
public static long randSeed;
// -- Constants used for creating/randomizing objects
public static final int GAME = 0;
public static final int GRAPH = 1;
public static final int FUNC = 2;
public static final int OUTPUT = 3;
// Constant directory names which can be passed to
// getObjectOrDie
private static final String[] DIRS={"gamer", "gamer.graphs",
"gamer.functions", "gamer"};
// -- Constant file names that will store lists of objects
// -- Used for randomization, etc
private static final String[] FILES = {"games.txt",
"graphs.txt",
"functions.txt",
"outputters.txt"};
private static final Class[] BASES = {Game.class, Graph.class, Function.class, GameOutput.class};
// -- Properties To hold those
private static Properties[] props = new Properties[4];
// -- Global Parameters
public static Parameters params;
// -- Original command line
public static String[] gArgs;
/**
* Convert array of strings into array of ints
*/
public static int[] parseIntArray(Vector v)
throws NumberFormatException
{
int n=v.size();
int[] nInts=new int[n];
for(int i=0; i<n; i++)
nInts[i]=Integer.parseInt((String)v.get(i));
return nInts;
}
//
// Convert array of strings into array of doubles
//
public static double[] parseDoubleArray(Vector v)
throws NumberFormatException
{
int n=v.size();
double[] nDoubles=new double[n];
for(int i=0; i<n; i++)
nDoubles[i]=Double.parseDouble((String)v.get(i));
return nDoubles;
}
//
// Return a random long value in the range from low to high
// inclusively
//
public static long randomLong(long low, long high) {
// For some reason, % yields negative numbers sometimes,
// so have to remember to take the absolute value
long nextlong = Global.rand.nextLong();
return (low + (Math.abs(nextlong) % (high-low+1)));
}
// -- same for int
public static int randomInt(int low, int high) {
// For some reason, % yields negative numbers sometimes,
// so have to remember to take the absolute value
int next = Global.rand.nextInt();
return (low + (Math.abs(next) % (high-low+1)));
}
// -- Same as above but for double
public static double randomDouble(double low, double high) {
double nd = Global.rand.nextDouble();
return low + nd * (high-low);
}
public static double randomDouble()
{
return Global.rand.nextDouble();
}
//
// Return false or true with equal likeliness
//
public static boolean randomBoolean() {
long randomlong = Global.rand.nextLong();
if ((Math.abs(randomlong) % 2) == 0)
return false;
return true;
}
//
// Recursively compute factorial. Used by NChooseM() function.
//
public static long factorial(long x)
{
if (x <= 1)
return 1;
else
return (x * factorial(x-1));
}
//
// Return n choose m
//
public static long NChooseM(long n, long m)
throws Exception
{
if (n < m)
throw new Exception("In NChooseM, n < m.");
return (Global.factorial(n) /
(Global.factorial(m) * Global.factorial(n-m)));
}
//
// Return the maximum (double, int, long) value
//
public static double max(double x, double y)
{
if (x > y) return x;
else return y;
}
public static int max(int x, int y)
{
if (x > y) return x;
else return y;
}
public static long max(long x, long y)
{
if (x > y) return x;
else return y;
}
//
// Return the minimum (double, int, long) value
//
public static double min(double x, double y)
{
if (x < y) return x;
else return y;
}
public static int min(int x, int y)
{
if (x < y) return x;
else return y;
}
public static long min(long x, long y)
{
if (x < y) return x;
else return y;
}
//
// Prints out an error message and exception stack trace
// and then dies. Separating this into its own function
// so that if we decide to handle errors differently, it
// will be easy to change
//
public static void handleError(Exception e, String s)
{
System.err.println();
System.err.println("FATAL ERROR: " + s);
System.err.println(e.toString());
System.err.println();
System.exit(1);
}
//
// Same but with no explicit Exception
//
public static void handleError(String s)
{
System.err.println();
System.err.println("FATAL ERROR: " + s);
System.err.println();
System.exit(1);
}
//
// Instantiate a class given its name and the name of
// the directory
//
public static Object getObjectOrDie(String name, int type)
{
try {
// -- First, make sure it's ground
if(isKnown(type, name) && !isGround(type, name))
name = getRandomClass(type, name);
// -- if it has parameters, then try to parse them
ParamParser pars=null;
if ( hasPresets(type, name) )
{
// -- First, remove []
String val = getPresetParams(type, name);
val=val.substring(1,val.length()-1).trim();
String[] tmp = val.split("\\p{Space}+");
// -- name is now the first one there
name = tmp[0];
String[] cmdLine=new String[tmp.length-1];
for(int i=0; i<cmdLine.length; i++)
cmdLine[i]=tmp[i+1];
pars=new ParamParser(cmdLine);
}
// -- Then try to instantiate it;
Class cl=Class.forName("edu.stanford.multiagent." + DIRS[type] +
"." + name);
Object obj=cl.newInstance();
// -- this should be a parameterized object now,
// -- i.e. not an output, so can do parameters
if(pars!=null)
((ParameterizedObject)obj).setParameters(pars, false);
// -- If it's not known, we'll add it, unless we're sealed in jar
if(!runningFromJar && !isKnown(type, name))
{
if(!BASES[type].isInstance(obj))
throw new Exception(name + " has wrong class");
props[type].setProperty(name, ""); // -- it's ground
props[type].store(new FileOutputStream(FILES[type]),
VERSION_STRING);
}
return obj;
} catch (ClassNotFoundException e) {
System.err.println("ERROR: " + name +
" is not a recognized class in " + DIRS[type]);
String help=getHelp() +"\n\n" + "Known classes are:\n" + getClassList(type);
System.err.println(help);
System.exit(1);
} catch (Exception e) {
System.err.println("ERROR Instantiating " + name);
System.err.println("Specified class could not be instantiated.");
System.err.println (getHelp() + "\n\n" + "Known classes are:\n" + getClassList(type));;
System.exit(1);
}
return null;
}
//
// Return the generic help screen
//
public static String getHelp()
{
StringBuffer buff=new StringBuffer();
buff.append("\n" + VERSION_STRING + "\n");
buff.append("Eugene Nudelman, Jennifer Wortman, " +
"Kevin Leyton-Brown, Yoav Shoham\n" +
"Stanford University\n");
buff.append("================================================" +
"==================\n\n");
buff.append("Global Parameters:\n");
for(int i=0; i< Main.globalParamInfo.length; i++)
buff.append("-" + Main.globalParamInfo[i].name + ":\t"
+ Main.globalParamInfo[i].help + "\n");
return buff.toString();
}
//
// Found this wrapping function at
// http://www.reed.edu/~mcphailb/applets/other/src
// /shakespeare/IOStream.java
// It is useful for printing out help screens in a more
// readable format.
//
public static String wrap(String s, int width) {
StringBuffer text = new StringBuffer();
StringBuffer line = new StringBuffer();
StringBuffer word = new StringBuffer();
for (int i=0, li = 0; i < s.length(); i++, li++) {
switch (s.charAt(i)) {
case ' ':
line.append(word + " ");
word = new StringBuffer();
break;
case '\n':
line.append(word);
text.append(line + "\n");
word = new StringBuffer();
line = new StringBuffer();
li = 0;
break;
case '\t':
line.append(word + " ");
word = new StringBuffer();
break;
default:
word.append(s.charAt(i));
break;
}
if (li > width) {
text.append(line + "\n");
line = new StringBuffer();
li = 0;
}
}
if (!line.toString().endsWith((word + "\n").toString())) {
line.append(word);
text.append(line);
}
return text.toString();
}
// --------------------------------------------------------
private static HashMap paramRegistry=new HashMap();
/**
*Function must be called by every class to register its parameters
*/
public static final void registerParams(Class cl, Parameters.ParamInfo[] pi)
{
paramRegistry.put(cl, pi);
}
/**
*Returns the parameter info array for a given class name
*/
public static final Parameters.ParamInfo[] getClassParamInfo(Class cl)
throws Exception
{
if(!paramRegistry.containsKey(cl))
throw new Exception("No parameters found for class: " + cl.getName());
return (Parameters.ParamInfo[])paramRegistry.get(cl);
}
public static final Parameters.ParamInfo[] getClassParamInfo(String name)
throws Exception
{
Class cl=Class.forName(name);
return getClassParamInfo(cl);
}
// --Deal with function/graph randomization
/**
* Check whether name corresponds to a ground classs
*/
public static boolean isGround(int type, String name)
{
String val=props[type].getProperty(name);
if(val==null)
return false;
return (val.length()==0) || (val.startsWith("[") && val.endsWith("]"));
}
/**
*Check whether has preset Params
*/
public static boolean hasPresets(int type, String name)
{
String val=props[type].getProperty(name);
if(val==null)
return false;
return (val.startsWith("[") && val.endsWith("]"));
}
/**
*Get the preset parameter values
*/
public static String getPresetParams(int type, String name)
{
if(hasPresets(type, name))
return props[type].getProperty(name);
return null;
}
/**
* Check whether it's known
*/
public static boolean isKnown(int type, String name)
{
return props[type].getProperty(name)!=null;
}
/**
* Construct a list of ground classes that are subsets of a given typ
* Puts them into v
*/
public static void getGroundClasses(int type, String name, Set v)
{
if(!isKnown(type, name))
return;
if(isGround(type, name))
{
// -- ground class
v.add(name.trim());
return;
}
String val=props[type].getProperty(name);
// -- Otherwise it better be a comma separated list
StringTokenizer st=new StringTokenizer(val,", ");
while(st.hasMoreTokens())
getGroundClasses(type, st.nextToken().trim(), v);
}
public static void getGroundClasses(int type, Set v)
{
Enumeration e = props[type].propertyNames();
while(e.hasMoreElements())
getGroundClasses(type, (String)(e.nextElement()), v);
}
/**
*Return a help string listing all known ground/non-ground classes
*/
public static String getClassList(int type)
{
StringBuffer buff=new StringBuffer();
Enumeration e=props[type].propertyNames();
while(e.hasMoreElements())
{
buff.append((String)e.nextElement()).append("\n");
}
return buff.toString();
}
/**
*Check whether one class of objects is a subtype of another
* (i.e. a is in b)
*/
public static boolean isPartOf(int type, String a, String b)
{
Set bSet=new TreeSet();
getGroundClasses(type, b, bSet);
Set aSet=new TreeSet();
getGroundClasses(type, a, aSet);
return bSet.containsAll(aSet);
}
/**
*Return a random ground subclass
*/
public static String getRandomClass(int type, String ancestor)
{
try {
Set s=new TreeSet();
if(ancestor==null)
getGroundClasses(type, s);
else
getGroundClasses(type, ancestor, s);
int n=s.size();
if(n==0)
throw new Exception("ERROR: Nothing to Randomize From!");
int r=(int)randomLong(1, n);
int i=1;
for(Iterator it = s.iterator(); it.hasNext(); i++)
{
String cl=(String)it.next();
if(i==r)
return cl;
}
// -- mustn't get here
throw new Exception("FATAL: Internal Error in Random Class!");
} catch (Exception e) {
handleError(e, "Getting random class!");
}
return null; // -- This is really a runtime exception
}
/**
*Return a random ground subclass from an intersection
*/
public static String getRandomClassInt(int type, Vector ancestors)
{
try {
Set[] s=new TreeSet[ancestors.size()];
for(int i=0; i<s.length; i++)
{
s[i] = new TreeSet();
getGroundClasses(type, (String)(ancestors.elementAt(i)), s[i]);
}
// -- get intersection
for(int i=1; i<s.length; i++)
s[0].retainAll(s[i]);
int n=s[0].size();
if(n==0)
throw new Exception("ERROR: Nothing to Randomize From!");
int r=(int)randomLong(1, n);
int i=1;
for(Iterator it = s[0].iterator(); it.hasNext(); i++)
{
String cl=(String)it.next();
if(i==r)
return cl;
}
// -- mustn't get here
throw new Exception("FATAL: Internal Error in Random Class!");
} catch (Exception e) {
handleError(e, "Getting random Class!");
}
return null; // -- This is really a runtime exception
}
public static String getRandomClass(int type)
{
return getRandomClass(type, null);
}
// -------------------------------------------------------------
/**
*Return the name of the currently executing jar file
*/
private static String getJarFileName ()
{
// String myClassName = theClass.getName() + ".class";
String myClassName = "edu/stanford/multiagent/gamer/Global.class";
URL urlJar =
Global.class.getClassLoader().getResource(myClassName);
// Global.class.getClassLoader().getSystemResource(myClassName);
String urlStr = urlJar.toString();
if(!urlStr.startsWith("jar:file:"))
return null;
int from = "jar:file:".length();
int to = urlStr.indexOf("!/");
return urlStr.substring(from, to);
}
/**
*Return an input stream for reading from jar file
*/
private static InputStream getJarInputStream(String fName)
throws IOException
{
JarFile jf=new JarFile(getJarFileName());
JarEntry jr=jf.getJarEntry(fName);
return jf.getInputStream(jr);
}
/**
*Field indicating whether we're running from a jar file
*/
private static boolean runningFromJar=true;
// -------------------------------------------------------------
// -- Static constructor
static {
//-- Initialize random here, can be reset later in main
Global.randSeed = System.currentTimeMillis();
Global.rand=new Random(Global.randSeed);
// -- Initialize file properties
runningFromJar = (getJarFileName()!=null);
// see if user has alternative path
String path=System.getProperty("gamer.class.path");
for(int i=0; i<props.length; i++)
{
props[i] = new Properties();
try {
InputStream fIn;
if(path!=null) // -- takes precedence
fIn = new FileInputStream(path + FILES[i]);
else if (runningFromJar)
fIn = getJarInputStream("edu/stanford/multiagent/gamer/" +
FILES[i]);
else
fIn = new FileInputStream(FILES[i]); // -- last resort
props[i].load(fIn);
} catch (Exception e) {
System.err.println("ERROR: Failed to read property file!");
System.err.println("WARNING: Randomization might not work correctly!");
System.err.println(e.getMessage());
}
}
}
}
| 16,958 | 22.785414 | 101 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GrabTheDollar.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a version of the game Grab the Dollar
*/
public class GrabTheDollar extends TimingGame
{
// Parameters: Grab the dollar is parameterized on the number
// of actions (i.e. highest number of time steps)
private static Parameters.ParamInfo[] gtdParam;
static {
gtdParam = new Parameters.ParamInfo[] {Game.symActions};
Global.registerParams(GrabTheDollar.class, gtdParam);
}
// ----------------------------------------------
public GrabTheDollar()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// The number of players must always be two, but the number
// of actions is extensible
setNumPlayers(2);
parseSameNumberActions();
}
//
// None to check
//
protected void checkParameters() throws Exception
{
}
//
// None which can be randomized
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates an instance of game Grab the Dollar.\n\n" +
"In this game, there is a prize (or \"dollar\") that both " +
"players are free to grab at any time, where actions represent " +
"the chosen times. If both players grab for it at " +
"the same time, they will rip the price and both will receive " +
"the low payoff. If one chooses a time earlier than " +
"the other (i.e. chooses a strictly lower action number " +
"number) then he will receive the price (and thus the high " +
"payoff) and the opposing player will receive a payoff " +
"somewhere between the high and the low." +
getRangeHelp();
}
public void doGenerate()
{
double lowPay = DEFAULT_LOW;
double highPay = DEFAULT_HIGH;
setDescription("Grab the Dollar\n" + getDescription());
setName("Grab the Dollar");
int players = getNumPlayers();
SortedAndRandomSet payoffValues = new SortedAndRandomSet();
// Generate unique payoffs a, b, and c in the range from
// lowPay to highPay
for (int i = 0; i < 3; i++) {
Double randomPayoffAsDouble;
do {
double randomPayoff = Global.randomDouble(lowPay, highPay);
randomPayoffAsDouble = new Double(randomPayoff);
} while (!(payoffValues.add(randomPayoffAsDouble)));
}
Double a = (Double) payoffValues.removeLargest();
Double b = (Double) payoffValues.removeLargest();
Double c = (Double) payoffValues.removeLargest();
// Create TimingGameParams objects which will be
// necessary to hold the function parameters for each player
TimingGameParams low[] = new TimingGameParams[players];
TimingGameParams notLow[] = new TimingGameParams[players];
TimingGameParams tie[] = new TimingGameParams[players];
// Both players will always receive a for uniquely choosing
// the lowest time, b for choosing the highest time, and c
// if they both choose the same, with a > b > c
for (int i = 0; i < players; i++) {
// Set up function parameters for when player chooses
// lowest time
low[i] = new TimingGameParams(0, 0, a.doubleValue());
// Function params for when player ties for low time
tie[i] = new TimingGameParams(0, 0, c.doubleValue());
// Function params for when player does not have low time
notLow[i] = new TimingGameParams(0, 0, b.doubleValue());
}
// Finally, set these parameters so that the payoff can be
// calculated using the timing game class
setParamsWithTie(low, tie, notLow);
}
}
| 4,163 | 27.717241 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GraphicalGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
/**
* Abstract class implements the basic common features of
* graphical games.
*
* The graphical game may have data stored at either edges or at the
* nodes. If data is at the nodes, this data would be in the form of
* a matrix of payoffs for one players based on actions of all connected
* players. If the data is at the edges it would be in the form of 2
* person games which are added to the node data to get the payoff.
*/
public abstract class GraphicalGame extends Game
{
protected ALGraph graph;
// ----------------------------------------------------
/**
* Constructor for new graphical games.
*/
public GraphicalGame()
throws Exception
{
super();
}
/**
* Adds an edge from player1 to player2 but leaves the data
* for the edge set to null. Use this to add edges if the
* graphical game being created uses matrices at the nodes
* instead of at the egdes
*
* @param player1 the player node at which the edge should originate
* @param player2 the player node at which the edge should end
*/
protected void addEdge(int player1, int player2)
throws Exception
{
// Make sure players are valid and that the edge does
// not already exist and that the players in question do
// not already have node data matrices of a certain size
// set for them
if ((player1 < 0) || (player1 >= getNumPlayers()) ||
(player2 < 0) || (player2 >= getNumPlayers()) ||
(player1 == player2) || (graph.getNodeData(player1) != null) ||
(graph.getNodeData(player2) != null))
throw new Exception("Attempt to add edge with " +
"invalid players in GraphicalGame");
if (graph.areNeighbours(player1, player2))
throw new Exception("Attempt to create edge that " +
"already exists in GraphicalGame");
// Add the edge to the graph
graph.addEdge(player1, player2);
}
/**
* Adds an edge from player1 to player2 if the player numbers
* are valid, and sets the matrix at the edge to the one given.
*
* @param player1 the player node at which the edge should originate
* @param player2 the player node at which the edge should end
* @param matrix the tensor to store on the edge
*
* @throws Exception if the tensor is invalid, if an edge from
* player1 to player2 already exists, or if the player numbers are
* invalid
*/
protected void addEdge(int player1, int player2, DoubleTensor matrix)
throws Exception
{
// Make sure players are valid and that the edge does
// not already exist and that the players in question do
// not already have node data matrices of a certain size
// set for them
if ((player1 < 0) || (player1 >= getNumPlayers()) ||
(player2 < 0) || (player2 >= getNumPlayers()) ||
(player1 == player2) || (graph.getNodeData(player1) != null) ||
(graph.getNodeData(player2) != null))
throw new Exception("Attempt to add edge with " +
"invalid players in GraphicalGame");
if (graph.areNeighbours(player1, player2))
throw new Exception("Attempt to create edge that " +
"already exists in GraphicalGame");
// Make sure the DoubleTensor is of the right dimensions
if ((matrix.getNumDimensions() != 2) ||
(matrix.getSizeOfDim(0) != getNumActions(player1)) ||
(matrix.getSizeOfDim(1) != getNumActions(player2)))
throw new Exception("Invalid DoubleTensor in GraphicalGame");
// If all is well, add the edge
graph.addEdge(player1, player2, matrix);
}
/**
* Sets the matrix for the player's node if using the version
* of the graphical game representation in which the payoffs
* are stored in matrices at the nodes (as opposed to only
* on edges). The appropriate number of edges must have
* already been added to the graph. After this, no more
* edges can be added to or from this player.
*
* @param player the player whose node the data should be
* stored at
* @param matrix the tensor to store at this node
*/
public void setNodeMatrix(int player, DoubleTensor matrix)
{
// First make sure the number of edges connected to the
// player in the graph corresponds with the number of
// dimensions in the matrix.
int numEdges = matrix.getNumDimensions() - 1;
Iterator edgeIter = graph.getEdges(player);
int count = 0;
while (edgeIter.hasNext()) {
edgeIter.next();
count++;
}
try {
if (count != numEdges)
throw new Exception("Node matrix is of the wrong size");
} catch (Exception e) {
Global.handleError (e, "Error setting node data for " +
"graphical game");
}
// If the Tensor is the right size, set the node data
graph.setNodeData(player, matrix);
}
/**
* Figures out payoff for a certain outcome by adding up
*
* a) the payoff from the matrix that is stored at the
* player's node if one exists
*
* b) payoffs from all of the matrices which are connected
* by edges to the node of a certain player, if any of
* those exist
*
* @param outcome an array containing the actions chosen by
* each player
* @param player the player whose payoff should be returned
*/
public double getPayoff(int[] outcome, int player)
{
Iterator edgeIter;
double payoff = 0;
// First see if there is matrix data stored at the
// node for the player, in which case calculate the
// payoff for the player based on the actions of all
// connected players and this payoff matrix
if (graph.getNodeData(player) != null) {
DoubleTensor matrix = (DoubleTensor) graph.getNodeData(player);
int numEdges = matrix.getNumDimensions() - 1;
// Iterate through the edges getting the actions of
// each player involved in the matrix game.
edgeIter = graph.getEdges(player);
int[] nodeGameOutcome = new int[numEdges + 1];
nodeGameOutcome[0] = outcome[player];
int count = 1;
try {
while (edgeIter.hasNext()) {
Edge e = (Edge) edgeIter.next();
if (count > numEdges) {
throw new Exception("Incorrect node matrix in " +
"graphical game: too many edges");
}
int otherPlayer = e.getDest();
nodeGameOutcome[count] = outcome[otherPlayer];
count++;
}
if (count != numEdges + 1) {
throw new Exception("Incorrect node matrix in " +
"graphical game: not enough edges");
}
} catch (Exception e) {
Global.handleError(e, "Error getting graphical payoff");
}
// Finally get the payoff for the player based on
// the his actions and the actions of the others
payoff += matrix.getValue(nodeGameOutcome);
}
int[] miniGameOutcome = new int[2];
miniGameOutcome[0] = outcome[player];
edgeIter = graph.getEdges(player);
while (edgeIter.hasNext()) {
Edge e = (Edge) edgeIter.next();
// See if there is matrix data stored at the edge
// and if so add the payoff from this matrix
if (e.getData() != null) {
DoubleTensor matrix = (DoubleTensor) e.getData();
int otherPlayer = e.getDest();
miniGameOutcome[1] = outcome[otherPlayer];
payoff += matrix.getValue(miniGameOutcome);
}
}
return payoff;
}
/**
* Creates and initializes a graph of the correct type. Must
* be implemented by each subclass and called in the initialize
* method after all parameters have been set in place.
*/
protected abstract void initGraph()
throws Exception;
/**
* Writes output as a graphical game. The format of this output
* is subject to change with future versions of GAMUT.
*
* @param out the PrintWriter to which the output should be written
*/
public void writeGame(PrintWriter out)
{
out.println("# This is an ad-hoc graphical game output format.");
out.println("# It may change with future versions of GAMUT.\n");
out.println("graph {");
for(int i=0; i<graph.getNNodes(); i++)
{
Iterator it = graph.getNeighbours(i);
while(it.hasNext())
{
int to = ((Integer)it.next()).intValue();
if(to > i)
out.println("Node_" + i + " -- Node_" + to);
}
}
out.println("}\n");
out.println("#Payoff Section: ");
for(int i=0; i<getNumPlayers(); i++)
{
out.println("Player: " + i);
out.println("Actions: " + getNumActions(i));
DoubleTensor p=(DoubleTensor)graph.getNodeData(i);
Outcome outcome=new Outcome(p.getNumDimensions(),
p.getSizeOfDim());
outcome.reset();
while(outcome.hasMoreOutcomes())
{
try {
out.print(getOutputPayoff(p.getValue(outcome.getOutcome()))
+ "\t");
} catch (Exception e) {
Global.handleError(e, "Failed to format output!");
}
outcome.nextOutcome();
}
out.println("\n\n");
}
}
}
| 9,632 | 29.388013 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GreedyGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Return a version of the Greedy Game
*/
public class GreedyGame extends GeometricGame
{
// --------------------------------------------------------
// Parameters: Geometric games must always have two players
// and a number of actions based on the available subsets which
// can be chosen. Thus the Greedy Game is parameterized
// first on the number of elements in the set S and the max number
// of elements which red may choose. The number of actions for
// each player is (|S| choose max number) + (|S| choose max number - 1)
// + ... + (|S| choose 1) where the max number for blue is the
// size of S.
private static Parameters.ParamInfo sizeOfSet;
private static Parameters.ParamInfo maxForR;
private static Parameters.ParamInfo[] ggParam;
static {
// When randomizing the size of the set, limit it to
// a max of 8 so that the number of actions does not
// get too absurdly out of hand.
sizeOfSet = new Parameters.ParamInfo("set_size", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(8), "number of elements in set S from which the players choose elements. Must be > 0 and <= 8 for the sake of keeping the number of actions reasonable.");
maxForR = new Parameters.ParamInfo("max_r", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(8), "maximum number of elements which player one (the \"red\" player) can choose from S. Must be > 0 and <= set_size.");
ggParam = new Parameters.ParamInfo[] {sizeOfSet, maxForR};
Global.registerParams(GreedyGame.class, ggParam);
}
// ----------------------------------------------
public GreedyGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// All geometric games have two players
setNumPlayers(2);
// Figure out how many actions each player has and
// set these numbers
int numActions[];
numActions = new int[2];
// Red player has a limit on the size of the subset which
// can be chosen, but blue player does not.
numActions[0] = (int)getGeoNumActions(getLongParameter(sizeOfSet.name),
getLongParameter(maxForR.name));
numActions[1] = (int)getGeoNumActions(getLongParameter(sizeOfSet.name),
getLongParameter(sizeOfSet.name));
setNumActions(numActions);
}
protected void checkParameters() throws Exception
{
if (getLongParameter(sizeOfSet.name) <= 0)
throw new Exception("set_size <= 0");
if (getLongParameter(maxForR.name) <= 0)
throw new Exception("max_r <= 0");
if (getLongParameter(maxForR.name) > getLongParameter(sizeOfSet.name))
throw new Exception("max_r > set_size");
}
public void randomizeParameters()
{
if (parameters.setByUser(maxForR.name)) {
if (!(parameters.setByUser(sizeOfSet.name))) {
// reset range on the set size and randomize it
sizeOfSet.low = new Long(getLongParameter(maxForR.name));
parameters.randomizeParameter(sizeOfSet.name);
}
} else {
if (parameters.setByUser(sizeOfSet.name)) {
// resent the range on the max r and randomize it
maxForR.high = new Long(getLongParameter(sizeOfSet.name));
parameters.randomizeParameter(maxForR.name);
} else {
// if neither have been set in advance, randomize
// max r, then resent the range on set size and randomize
parameters.randomizeParameter(maxForR.name);
sizeOfSet.low = new Long(getLongParameter(maxForR.name));
parameters.randomizeParameter(sizeOfSet.name);
}
}
}
protected String getGameHelp()
{
return "Creates a 2 player Greedy Game.\n\n" +
"In this game, each action represents a chosen subset. " +
"Player 2 can choose any subset of set_size elements " +
"while Player 1 can only choose subsets up to size max_r.\n\n" +
"If the intersection of the \"sets\" chosen by the players " +
"is empty then the payoff to Player 2 will be the number of " +
"elements in the set he has chosen while the payoff to " +
"Player 1 will be the negation of this. Otherwise both " +
"players will receive 0.\n\n" +
"To change the range of the payoff values, you may use " +
"normalization or integer based payoffs.\n\n" +
"Note that the number of actions available to each player " +
"is (|S| choose maxnumber) + (|S| choose maxnumber - 1) " +
"+ ... + (|S| choose 1) where maxnumber is the maximum " +
"number of items in the set that the player can choose.";
}
/**
* All geometric games must provide a function to calculate the
* payoff for each player based on the sets chosen and the
* intersection between them. In this case, if the intersection
* is nonempty, the payoff to both players will be 0. If it
* is empty, the payoff to player 2 will be the number of
* elements in the set player 2 has chosen, while the payoff to
* player 1 will be the negation of this.
*/
public double calculatePayoff(int player, BitSet R, BitSet B,
BitSet intersection) {
double payoff;
if (R.intersects(B))
payoff = 0;
else if (player == 0)
payoff = -B.cardinality();
else
payoff = B.cardinality();
return payoff;
}
/**
* Generate game, set all variables so that payoffs can
* be calculated when they are needed.
*/
public void doGenerate()
{
setDescription("Greedy Game \n"
+ getDescription());
setName("Greedy Game");
initVariables(getLongParameter(sizeOfSet.name),
getLongParameter(maxForR.name),
getLongParameter(sizeOfSet.name));
}
}
| 6,316 | 32.247368 | 260 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/GuessTwoThirdsAve.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Generates an instance of the game in which players try to
* guess two thirds of the average of the amounts chosen by
* other players.
*/
public class GuessTwoThirdsAve extends Game
{
//---------------------------------------------------------
// Parameters: This game is only parameterized by the number
// of players and the number of actions.
private static Parameters.ParamInfo[] gttaParam;
static {
gttaParam = new Parameters.ParamInfo[] {Game.players, Game.symActions};
Global.registerParams(GuessTwoThirdsAve.class, gttaParam);
}
public GuessTwoThirdsAve()
throws Exception
{
super();
}
/**
* Set the numbers of players and actions for the game,
* initilaize variables, and so on.
*/
public void initialize()
throws Exception
{
super.initialize();
// Set the number of players and the number of actions
parsePlayersSameNumberActions();
}
//
// None to check.
//
protected void checkParameters() throws Exception
{
}
//
// None to randomize
//
public void randomizeParameters()
{
}
/**
* Return two-thirds of the average of the amounts in outcome
*/
public double getTwoThirdsAve(int[] outcome)
{
double ave = 0;
for (int i = 0; i < getNumPlayers(); i++)
ave += (double) outcome[i];
ave /= getNumPlayers();
return (2.0 * ave / 3.0);
}
/**
* Return the payoff for the given player in the given outcome.
*/
public double getPayoff(int[] outcome, int player)
{
double ave = getTwoThirdsAve(outcome);
int numClosest = 1;
double distOfClosest = Math.abs(outcome[0] - ave);
for (int i = 1; i < getNumPlayers(); i++) {
double dist = Math.abs(outcome[i] - ave);
if (dist == distOfClosest)
numClosest++;
else if (dist < distOfClosest) {
numClosest = 1;
distOfClosest = dist;
}
}
if (Math.abs(outcome[player] - ave) == distOfClosest)
return DEFAULT_HIGH / numClosest;
return 0.0;
}
/**
* Return a Vector with all players' utilities at the
* given outcome
*/
public Vector getPayoff(int[] outcome)
{
double ave = getTwoThirdsAve(outcome);
int numClosest = 1;
double distOfClosest = Math.abs(outcome[0] - ave);
for (int i = 1; i < getNumPlayers(); i++) {
double dist = Math.abs(outcome[i] - ave);
if (dist == distOfClosest)
numClosest++;
else if (dist < distOfClosest) {
numClosest = 1;
distOfClosest = dist;
}
}
Vector payoffVector = new Vector(getNumPlayers());
for (int i = 0; i < getNumPlayers(); i++) {
if (Math.abs(outcome[i] - ave) == distOfClosest) {
Double pay = new Double(DEFAULT_HIGH / numClosest);
payoffVector.add(i, pay);
} else {
Double pay = new Double(0.0);
payoffVector.add(i, pay);
}
}
return payoffVector;
}
protected String getGameHelp()
{
return "Creates an instance of the game in which all players " +
"guess a number trying to come as close as possible to " +
"two thirds of the average of the numbers guessed by all " +
"players.\n\n" +
"By default, the payoffs for this game are in the range from " +
"0 to " + DEFAULT_HIGH + ", where the player whose guess comes " +
"closest to two thirds of the average receives " + DEFAULT_HIGH +
" and the others receive 0. If more there is a tie, the payoff " +
"amount is split. To change the range of payoffs you can " +
"use the normalization or integer payoff options.";
}
/**
* Not really anything to generate
*/
public void doGenerate() {
setDescription("Guess Two Thirds of the Average\n" + getDescription());
setName("Guess Two Thirds of the Average");
}
}
| 4,495 | 23.302703 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/HawkAndDove.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a version of the two player Hawk and Dove game.
*
* Note that we are using a narrow definition of the hawk
* and dove game that only returns games of the form
*
* B,B C,A
* A,C D,D
*
* with A > B > C > D rather than the more broad definition
* proposed in some papers which allows Prisoners Dilemma and
* Chicken Games to count as Hawk and Dove.
*
*/
public class HawkAndDove extends MatrixGame
{
// Parameters: none
private static Parameters.ParamInfo[] hawkParam;
static {
hawkParam = new Parameters.ParamInfo[] {};
Global.registerParams(HawkAndDove.class, hawkParam);
}
// ----------------------------------------------
public HawkAndDove()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// The simple hawk and dove game will always have
// 2 players with 2 actions each.
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 2;
setNumActions(numActions);
initMatrix();
}
//
// None to check
//
protected void checkParameters() throws Exception
{
}
//
// None to randomize
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates a 2x2 Hawk and Dove.\n\nUses the more narrow " +
"definition of Hawk and Dove which does not, for example, " +
"allow games which would be classified as Prisoners " +
"Dilemmas or Chicken Games to qualify as Hawk and Dove." +
getRangeHelp();
}
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
setDescription("Two by Two Hawk and Dove Game\n"
+ getDescription());
setName("Hawk and Dove");
SortedAndRandomSet payoffValues = new SortedAndRandomSet();
Double a, b, c, d;
// Generate four payoff values in the range from
// payoff_low to payoff_high. Make sure that the
// four values are distinct.
for (int i = 0; i < 4; i++) {
Double randomPayoffAsDouble;
do {
double randomPayoff = Global.randomDouble(low, high);
randomPayoffAsDouble = new Double(randomPayoff);
} while (!(payoffValues.add(randomPayoffAsDouble)));
}
a = (Double) payoffValues.removeLargest();
b = (Double) payoffValues.removeLargest();
c = (Double) payoffValues.removeLargest();
d = (Double) payoffValues.removeLargest();
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
outcome.reset();
setPayoff(outcome.getOutcome(), 0, b.doubleValue());
setPayoff(outcome.getOutcome(), 1, b.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, a.doubleValue());
setPayoff(outcome.getOutcome(), 1, d.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, d.doubleValue());
setPayoff(outcome.getOutcome(), 1, a.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, c.doubleValue());
setPayoff(outcome.getOutcome(), 1, c.doubleValue());
}
}
| 3,730 | 24.040268 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/LocalEffectGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Abstract class which can be used to implement any Local-Effect
* game. Can be extended in order generate bi-directional LEGs,
* Uniform LEGs, etc.
*/
public abstract class LocalEffectGame extends Game
{
protected ALGraph graph;
// -------------------------------------------------
/**
* Constructor for a LEG.
*/
public LocalEffectGame()
throws Exception
{
super();
}
/**
* Sets the number of players based on the command line parameter.
* Separate initializers should be used for setting up the necessary
* functions and graphs.
*/
public void initialize()
throws Exception
{
super.initialize();
setNumPlayers((int) getLongParameter(Game.players.name));
}
/**
* Calculates the payoff for a player as the negation of the
* cost function for the action the player has chosen.
*
* @param outcome an array holding the action choices of each player
* @param player the player whose payoff should be returned
*/
public double getPayoff(int[] outcome, int player)
{
// First figure out how many players have chosen
// each action. (This is called the D function in
// the LEGs literature.)
int actions = getNumActions(0);
int[] D = new int[actions];
for (int i = 0; i < actions; i++)
D[i] = 0;
for (int i = 0; i < getNumPlayers(); i++) {
// Action idices start at 1
int node = outcome[i] - 1;
D[node]++;
}
// Remember that action indices start at 1
int chosenNode = outcome[player] - 1;
double cost = 0;
// First add the node function
Function nodeFunc = (Function) graph.getNodeData(chosenNode);
cost += nodeFunc.eval(D[chosenNode]);
// Now add the edge functions for all edges
// coming into the chosen node -- Note that because of
// the implementation of graphs, the effects stored on
// edge (a, b) are the effects of node b on node a, which
// is the opposite of how the edge functions are defined
// in the literature.
Iterator edgeIter = graph.getEdges(chosenNode);
try {
while (edgeIter.hasNext()) {
Edge e = (Edge) edgeIter.next();
Function edgeFunc = (Function) e.getData();
int neighborNode = e.getDest();
cost += edgeFunc.eval(D[neighborNode]);
}
} catch (Exception e) {
Global.handleError(e, "Error getting LEG payoff");
}
// The payoff is the negation of the cost
return(-cost);
}
}
| 3,235 | 26.423729 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/LocationGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Returns an instance of the two player location game
* based on Hotelling's original model.
*
*/
public class LocationGame extends Game
{
// Parameters: The location game is parameterized by the
// length l of the street, the length a of the street on the
// far side of player 1, the length b of the street on the
// far side of player 2, the cost c per distance of
// transporting the product, and min and max prices that
// the players can offer.
protected static Parameters.ParamInfo pADist;
protected static Parameters.ParamInfo pBDist;
protected static Parameters.ParamInfo pLDist;
protected static Parameters.ParamInfo pCost;
protected static Parameters.ParamInfo pLowAct;
protected static Parameters.ParamInfo[] lgParams;
static {
pLowAct = new Parameters.ParamInfo("price_low", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(5000), "lowest price each player can choose. Must be > 0 and <= 5000. The highest price each player can choose will then be price_low + actions - 1.");
pADist = new Parameters.ParamInfo("a", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double (1000), "distance between the location of player 1's store and his end of the street. Must fall between 0 and 1000.");
pBDist = new Parameters.ParamInfo("b", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(1000), "distance between the location of player 2's store and his end of the street. Must fall between 0 and 1000.");
pLDist = new Parameters.ParamInfo("l", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(1000), "length of the entire street. Must be >= a + b but <= 1000.");
pCost = new Parameters.ParamInfo("c", Parameters.ParamInfo.DOUBLE_PARAM, new Double(1), new Double(100), "cost per unit of transporting the goods. Must fall between 1 and 100. See the note in the help string about randomization and values of this parameter.");
lgParams = new Parameters.ParamInfo[] {Game.symActions, pADist, pBDist,
pLDist, pCost, pLowAct};
Global.registerParams(LocationGame.class, lgParams);
}
// ----------------------------------------------------------
public LocationGame()
throws Exception
{
super();
}
public void initialize() throws Exception
{
super.initialize();
// Set the number of players (always 2) and actions
setNumPlayers(2);
parseSameNumberActions();
}
//
// Make sure parameters are in the correct range. Does not
// need to check price_low and price_high as this is already
// taken care of by the initialize function.
//
protected void checkParameters() throws Exception
{
if (getDoubleParameter(pADist.name) < 0)
throw new Exception("a < 0");
if (getDoubleParameter(pBDist.name) < 0)
throw new Exception("b < 0");
if (getDoubleParameter(pLDist.name) <= 0)
throw new Exception("l <= 0");
if (getDoubleParameter(pCost.name) <= 0)
throw new Exception("c <= 0");
if (getDoubleParameter(pADist.name) + getDoubleParameter(pBDist.name) >
getDoubleParameter(pLDist.name))
throw new Exception("a + b > l");
}
//
// Randomize parameters that were not set by the user
//
public void randomizeParameters() {
// The low price is straight-forward to randomize
if (!(parameters.setByUser(pLowAct.name))) {
parameters.randomizeParameter(pLowAct.name);
}
// The cost per unit good does not directly depend on
// anything, but it is best if the cost is less than the
// price the player can sell for, thus when we randomize, we
// force the cost to be less.
if (!(parameters.setByUser(pCost.name))) {
pCost.high = new Double((double)getLongParameter(pLowAct.name));
parameters.randomizeParameter(pCost.name);
}
// The user must set all or none of l, a, and b to avoid
// over complication of the randomization.
if ((parameters.setByUser(pLDist.name) !=
parameters.setByUser(pADist.name)) ||
(parameters.setByUser(pLDist.name) !=
parameters.setByUser(pBDist.name))) {
Global.handleError("Randomization Error: Please set all or " +
"none of parameters a, b, and l.");
}
if (!parameters.setByUser(pLDist.name)) {
// Need to randomize all three
parameters.randomizeParameter(pLDist.name);
double sum=Global.randomDouble(0, getDoubleParameter(pLDist.name));
double a=Global.randomDouble(0, sum);
try {
parameters.setParameter(pADist.name, new Double(a));
parameters.setParameter(pBDist.name, new Double(sum-a));
} catch (Exception e) {
Global.handleError(e, "Randomization Error");
}
/*
parameters.randomizeParameter(pADist.name);
parameters.randomizeParameter(pBDist.name);
pLDist.low = new Double(getDoubleParameter(pADist.name)
+ getDoubleParameter(pBDist.name));
parameters.randomizeParameter(pLDist.name);
*/
}
}
protected String getGameHelp() {
return "Creates an instance of the two person Location " +
"Game based on Hotelling's original model.\n\nIn this " +
"game there is a street of length l. Player one has " +
"a shop set up distance a from one end of the street " +
"and player 2 has a shop set up distance b from the " +
"other end. Customers are uniformly distributed along " +
"the street and the cost of getting a good from a shop " +
"to a home on the street is c times the distance. The " +
"players must pick a price at which to sell their goods " +
"in order to maximize their profit assuming that " +
"production is free and customers will always choose " +
"the shop for which the combined good price and " +
"transportation cost is smaller.\n\nProfits may be " +
"scaled if normalization is used, but relations between " +
"the parameters will remain the same and are thus important.\n\n" +
"Be very careful randomizing parameters in this game. If the " +
"cost of transporting goods is too high, it will always be " +
"a dominant strategy for both players to choose their highest " +
"action and the game will lose some of its intended interesting " +
"properties.";
}
/**
* Return the payoff for the given player at the given outcome.
*/
public double getPayoff(int[] outcome, int player)
{
double dist[] = new double[2];
dist[0] = getDoubleParameter(pADist.name);
dist[1] = getDoubleParameter(pBDist.name);
double l = getDoubleParameter(pLDist.name);
double c = getDoubleParameter(pCost.name);
// Action counting always starts at 1 so need to
// adjust the index
long offset = getLongParameter(pLowAct.name) - 1;
double price[] = new double[2];
for (int i = 0; i < getNumPlayers(); i++)
price[i] = (double) (outcome[i] + (int) offset);
// First check if either player has priced their item
// so much higher that the other player makes all of the
// profits.
for (int i = 0; i < getNumPlayers(); i++) {
if (price[i] > price[1-i] + c * (l - dist[0] - dist[1])) {
if (player == i) {
// The player has charged too much and
// will receive no profit
return 0;
} else {
// The opponent has charged too much so all
// customers will go to the player
return (l * price[1-i]);
}
}
}
// If this is not the case, then player 1 will get all
// of the customers in the a section, player 2 will get all
// of the customers in the b section, and the middle
// section will be split up according to price and distance
// according to the formulas in Hotelling's work.
return (double) ((0.5 * (l + dist[player] - dist[1-player])
* price[player])
- ((price[player] * price[player]) / (2.0 * c))
+ ((price[0] * price[1]) / (2.0 * c)));
}
/**
* All information for generating payoffs for the location
* game is contained in the parameter set. There is no
* additional game generation necessary.
*/
public void doGenerate() {
setDescription("Location Game\n" + getDescription());
setName("Location Game");
return;
}
}
| 8,829 | 34.32 | 263 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/LongTensor.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* The LongTensor class can be used to store matrices
* of any dimension
*/
public class LongTensor {
private int numDimensions;
private int[] dimensionSize;
private long values[];
/**
* The constructor for a LongTensor
*
* @param dimSize an array holding the size of the tensor in
* each dimension
*/
public LongTensor(int[] dimSize) {
int valueArraySize = 1;
numDimensions = dimSize.length;
dimensionSize = new int[numDimensions];
for (int i = 0; i < numDimensions; i++) {
dimensionSize[i] = dimSize[i];
valueArraySize *= dimensionSize[i];
}
values = new long[valueArraySize];
for (int i = 0; i < valueArraySize; i++) values[i] = 0;
}
/**
* Translate an array of indices in the tensor into
* an index of the underlying values array. Assumes
* that each index in the array is between 0 and the size
* of that dimension - 1.
*/
private int translateIndices(int[] indices) {
int valueIndex = 0;
for (int i = 0; i + 1 < numDimensions; i++) {
valueIndex += indices[i] - 1;
valueIndex *= dimensionSize[i+1];
}
valueIndex += indices[numDimensions-1] - 1;
return valueIndex;
}
/**
* Set the value stored at the indexed spot in the tensor
*/
public void setValue(long value, int[] indices) {
int valueIndex = translateIndices(indices);
values[valueIndex] = value;
}
/**
* Get the value stored at the indexed spot in the tensor
*/
public long getValue(int[] indices) {
int valueIndex = translateIndices(indices);
return values[valueIndex];
}
public int getNumDimensions() {
return numDimensions;
}
public int getSizeOfDim(int dim) {
return dimensionSize[dim];
}
/**
* Probably won't use this much, but occasionally may be
* useful to get all values returned in one array.
*/
public long[] getValues() {
return values;
}
}
| 2,645 | 24.2 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/Main.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import java.lang.reflect.*;
import java.io.*;
import edu.stanford.multiagent.gamer.graphs.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* The main class called when GAMUT is run.
*/
// == To Create gamut.jar:
// == jar cvfm gamut.jar edu/stanford/multiagent/gamer/manfile Jama/ edu/
public class Main
{
// Made public so that the parameter info can be accessed by
// the help function in Global
public static Parameters.ParamInfo[] globalParamInfo;
private static Parameters.ParamInfo pSeed;
private static Parameters.ParamInfo pGame;
private static Parameters.ParamInfo pFilename;
private static Parameters.ParamInfo pRandomize;
private static Parameters.ParamInfo pOut;
private static Parameters.ParamInfo pHelpGraph;
private static Parameters.ParamInfo pHelpFunc;
private static Parameters.ParamInfo pHelpGame;
// -- Global Parameters
static {
pSeed=new Parameters.ParamInfo("random_seed", Parameters.ParamInfo.LONG_PARAM, new Long(0), new Long(Long.MAX_VALUE), "random seed, uses current time by default.");
pGame = new Parameters.ParamInfo("g", Parameters.ParamInfo.VECTOR_PARAM, null, null, "the name of the game to generate, or a list of classes from intersection of which a generator will be picked");
pFilename = new Parameters.ParamInfo("f", Parameters.ParamInfo.STRING_PARAM, null, null, "output file name");
pRandomize = new Parameters.ParamInfo("random_params", Parameters.ParamInfo.BOOLEAN_PARAM, null, null, "randomize unset parameters in default ranges",false, Boolean.FALSE);
pOut = new Parameters.ParamInfo("output", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the outputter to use. (Default: SimpleOutput)",false,"SimpleOutput");
pHelpGame = new Parameters.ParamInfo("helpgame", Parameters.ParamInfo.STRING_PARAM, null, null, "Print help info for a game.");
pHelpGraph = new Parameters.ParamInfo("helpgraph", Parameters.ParamInfo.STRING_PARAM, null, null, "Print help info for a graph.");
pHelpFunc = new Parameters.ParamInfo("helpfunc", Parameters.ParamInfo.STRING_PARAM, null, null, "Print help info for a function.");
globalParamInfo = new Parameters.ParamInfo[]
{pSeed, pGame, pFilename, pRandomize, pOut, Game.intPayoffs,
Game.intMult, Game.pNormalize, Game.pMinPayoff, Game.pMaxPayoff,
pHelpGame, pHelpGraph, pHelpFunc};
Global.params=new Parameters(globalParamInfo);
}
/**
* Return help for a given name/type
*/
protected static void printObjectHelp(int type, String name)
{
if( !Global.isKnown(type, name) )
{
System.out.println("Known classes are: ");
System.out.println(Global.getClassList(type));
}
else if( Global.isGround(type, name) )
{
Object obj = Global.getObjectOrDie(name, type);
// -- all of these have getHelp method
try {
Method mHelp = obj.getClass().getMethod("getHelp", null);
System.out.println(mHelp.invoke(obj, null));
} catch (Exception e) {
System.err.println("Couldn't get help for " + name);
return;
}
}
else
{
// -- list all subclasses
Set s=new TreeSet();
Global.getGroundClasses(type, name, s);
System.out.println(name + " consists of:");
for(Iterator it = s.iterator(); it.hasNext(); )
System.out.println((String)it.next());
}
}
/**
* Main method for GAMUT.
*/
public static void main(String[] args)
{
if(args.length<1)
{
System.out.println(Global.getHelp());
System.exit(1);
}
// -- Store the command line for posterity
Global.gArgs = new String[args.length];
System.arraycopy(args,0,Global.gArgs,0,args.length);
// -- pre-parse parameters
ParamParser p=null;
try {
p = new ParamParser(args);
Global.params.setFromParser(p);
} catch (Exception e) {
System.err.println(e.toString());
System.err.println(Global.getHelp());
System.exit(1);
}
// -- First, if any help parameters are present, just print
// -- help and ignore the rest
if(Global.params.isParamSet(pHelpGame.name))
{
printObjectHelp(Global.GAME,
Global.params.getStringParameter(pHelpGame.name));
System.exit(0);
}
if(Global.params.isParamSet(pHelpGraph.name))
{
printObjectHelp(Global.GRAPH,
Global.params.getStringParameter(pHelpGraph.name));
System.exit(0);
}
if(Global.params.isParamSet(pHelpFunc.name))
{
printObjectHelp(Global.FUNC,
Global.params.getStringParameter(pHelpFunc.name));
System.exit(0);
}
// -- set the random seed
Global.randSeed = ( Global.params.isParamSet(pSeed.name) ?
Global.params.getLongParameter(pSeed.name) :
System.currentTimeMillis() );
Global.rand=new Random(Global.randSeed);
System.err.println("GAMUT RANDOM SEED: " + Global.randSeed);
// -- Get Outputter Name
String outName;
outName = Global.params.getStringParameter(pOut.name);
// -- Instantiate the game
String gName=null;
boolean randomizingGame=false;
if(!Global.params.isParamSet(pGame.name)) {
if(!Global.params.getBooleanParameter(pRandomize.name)) {
System.err.println("ERROR: -g is the required parameter!");
System.err.println(Global.getHelp());
System.exit(1);
}
else
try {
randomizingGame=true;
// gName =Global.getRandomClass(Global.GAME);
System.err.println("WARNING: Randomizing from default class results in a restrictive distribution; this does not include 2-player or 2-action games, or more structured games (e.g. geometric games). See documentation for appropriate classes to use.");
Vector v = new Vector();
v.add("GameWithActionParam");
v.add("GameWithPlayerParam");
gName = Global.getRandomClassInt(Global.GAME, v);
} catch (Exception e) {
Global.handleError(e, "Randomizing Game");
}
}
else {
Vector gVector=Global.params.getVectorParameter(pGame.name);
if(gVector.size()==1)
{
// -- 1 game only specified
gName=(String)gVector.firstElement();
randomizingGame = !Global.isGround(Global.GAME, gName);
}
else
{
// -- intersection
gName = Global.getRandomClassInt(Global.GAME, gVector);
randomizingGame = true;
}
}
String sOutFile=null;
sOutFile = ( Global.params.isParamSet(pFilename.name) ?
Global.params.getStringParameter(pFilename.name)
: gName + ".game" );
// Make sure that the min_payoff and max_payoff params are set
// only if the normalize param is set and that max_payoff
// is greater than min_payoff if they are set
if (Global.params.getBooleanParameter(Game.pNormalize.name)) {
if (!Global.params.isParamSet(Game.pMinPayoff.name)) {
System.err.println(Global.getHelp());
Global.handleError("Must set param min_payoff when " +
"normalization feature is in use.");
}
if (!Global.params.isParamSet(Game.pMaxPayoff.name)) {
System.err.println(Global.getHelp());
Global.handleError("Must set param max_payoff when " +
"normalization feature is in use.");
}
if (Global.params.getDoubleParameter(Game.pMinPayoff.name) >=
Global.params.getDoubleParameter(Game.pMaxPayoff.name)) {
System.err.println(Global.getHelp());
Global.handleError("minpayoff >= max_payoff");
}
} else {
if (Global.params.isParamSet(Game.pMinPayoff.name)) {
System.err.println(Global.getHelp());
Global.handleError("min_payoff should not be set when " +
"normalization is not in use");
}
if (Global.params.isParamSet(Game.pMaxPayoff.name)) {
System.err.println(Global.getHelp());
Global.handleError("max_payoff should not be set when " +
"normalization is not in use");
}
}
Game g=null;
g = (Game) Global.getObjectOrDie(gName, Global.GAME);
// -- set all parameters and initialize
try {
boolean rp = Global.params.getBooleanParameter(pRandomize.name);
g.setParameters(p, rp);
g.initialize();
} catch (Exception e) {
System.err.println("ERROR: Initializing " + gName);
System.err.println(e.toString());
System.err.println(Global.getHelp());
System.err.println(g.getHelp());
if( Global.hasPresets(Global.GAME, gName) )
System.err.println("Preset parameters: " +
Global.getPresetParams(Global.GAME,gName));
System.exit(1);
}
//-- Check that no unknown parameters are passed
//-- Turn this off for random games - since they might have different
//-- Arguments
if(!randomizingGame && p.hasUnusedArgs())
{
System.err.println("ERROR: Unknown arguments: ");
String[] a=p.getUnusedArgs();
for(int i=0; i<a.length; i++)
System.err.println(a[i]);
System.err.println(Global.getHelp());
System.err.println(g.getHelp());
System.exit(1);
}
// Generate an instance
try {
g.generate();
} catch (Exception e) {
Global.handleError(e, "Failed to generate an instance");
}
PrintWriter out;
GameOutput outputter = (GameOutput)
Global.getObjectOrDie(outName, Global.OUTPUT);
try {
FileWriter fw = new FileWriter(sOutFile);
out = new PrintWriter(fw, true);
outputter.writeGame(out, g);
} catch (Exception e) {
Global.handleError(e, "Output failed");
}
}
}
| 9,921 | 31.214286 | 256 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/MajorityVoting.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Generates an instance of the Majority Voting game. Subclasses
* Game directly without an intermediate layer.
*
* Note that in this version of the Majority Voting game, players'
* utilities for each candidate are arbitrary and it is possible that
* a player would be indifferent between two or more candidates.
*
* Also, in this version if two candidates have the same number of
* votes, the lower indexed candidate is declared winner.
*/
public class MajorityVoting extends Game
{
//---------------------------------------------------------
// Parameters: The Majority Voting game is parameterized by
// the numbers of players and candidates (actions).
private static Parameters.ParamInfo[] mvParam;
static {
mvParam = new Parameters.ParamInfo[] {Game.players, Game.symActions};
Global.registerParams(MajorityVoting.class, mvParam);
}
// -----------------------------------------------------
// Keep track of the utility for each player for each
// candidate winning. Note that candidates are numbered
// starting at 0 in the preferences while actions are numbered
// starting at 0, so adjustments need to be made.
double preferences[][];
// -----------------------------------------------------
public MajorityVoting()
throws Exception
{
super();
}
//
// Set the numbers of players and actions for the game,
// initilaize variables, and so on.
//
public void initialize()
throws Exception
{
super.initialize();
// Set the number of players and the number of actions (time
// steps) from the parameters
parsePlayersSameNumberActions();
}
//
// None to check.
//
protected void checkParameters() throws Exception
{
}
//
// None to randomize
//
public void randomizeParameters()
{
}
/**
* Counts the votes of each player on the particular outcome
* and returns the action number of the candidate with the
* most votes.
*/
private long determineWinner(int[] outcome) {
int players = getNumPlayers();
int actions = getNumActions(0); // same for all players
long voteCounter[] = new long[actions];
for (int i = 0; i < actions; i++)
voteCounter[i] = 0;
for (int i = 0; i < players; i++)
// Remember that actions start at 1, while
// preferences start at 0
voteCounter[outcome[i] - 1] =
voteCounter[outcome[i] - 1] + 1;
long winner = 0;
for (int i = 1; i < actions; i++)
if (voteCounter[i] > voteCounter[(int)winner])
winner = i;
return winner;
}
/**
* Return the payoff for the given player in the given
* outcome. Assumes everything has already been set up.
*/
public double getPayoff(int[] outcome, int player) {
long winner = determineWinner(outcome);
return (preferences[player][(int)winner]);
}
/**
* Return a Vector with all players' utilities at the
* given outcome
*/
public Vector getPayoff(int[] outcome)
{
long winner = determineWinner(outcome);
int players = getNumPlayers();
Vector payoffVector = new Vector(players);
for (int i = 0; i < players; i++) {
Double pref = new Double(preferences[i][(int)winner]);
payoffVector.add(i, pref);
}
return payoffVector;
}
protected String getGameHelp()
{
return "Creates an instance of the Majority Voting Game.\n\n" +
"In this version of the Majority Voting Game, " +
"players' utilities for each candidate (i.e. action) " +
"being declared the winner are arbitrary and it is " +
"possible that a player would be indifferent between " +
"two or more candidates.\n\n" +
"If multiple candidates have the same number of votes and " +
"this number is higher than the number of votes any other " +
"candidate has, then the candidate with the lowest number " +
"is declared winner." + getRangeHelp();
}
/**
* Generate the game and store all of the players' utilities
* for each candidate in preferences matrix
*/
public void doGenerate() {
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
setDescription("Majority Voting\n" + getDescription());
setName("Majority Voting");
int players = getNumPlayers();
int actions = getNumActions(0); // same for all players
preferences = new double[players][actions];
for (int i = 0; i < players; i ++) {
for (int j = 0; j < actions; j++) {
preferences[i][j] = Global.randomDouble(low, high);
}
}
}
}
| 5,264 | 26 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/MatchingPennies.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a version of the standard Matching Pennies game.
*/
public class MatchingPennies extends ZeroSumGame
{
// Parameters: Matching Pennies takes no parameters
private static Parameters.ParamInfo[] mpParam;
static {
mpParam = new Parameters.ParamInfo[] {};
Global.registerParams(MatchingPennies.class, mpParam);
}
// ----------------------------------------------
public MatchingPennies()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 2;
setNumActions(numActions);
initPayoffs(2, 2);
}
//
// No params
//
protected void checkParameters() throws Exception
{
}
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates an instance of the Matching Pennies Game" +
getRangeHelp();
}
public void doGenerate()
{
double a = DEFAULT_HIGH;
setDescription("Matching Pennies\n" + getDescription());
setName("Matching Pennies");
Outcome outcome = new Outcome(getNumPlayers(), getNumActions());
outcome.reset();
setPayoff(outcome.getOutcome(), a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), -a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), -a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), a);
}
}
| 2,158 | 19.367925 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/MatrixGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Class implements the straightforward normal form game.
*/
public abstract class MatrixGame extends Game
{
private DoubleTensor[] payoffs;
/**
* Constructor for a new matrix game.
*/
public MatrixGame()
throws Exception
{
super();
}
/**
* Initializes the payoff array. Assumes that the numbers of
* players and actions have already been set.
*/
protected void initMatrix()
{
payoffs = new DoubleTensor[getNumPlayers()];
for(int i=0; i<getNumPlayers(); i++)
payoffs[i] = new DoubleTensor(getNumActions());
}
/**
* Returns the payoff for a player for a given outcome.
*
* @param outcome an array containing the actions chosen by each player
* @param player the player whose payoff should be returned.
*/
public double getPayoff(int[] outcome, int player)
{
return payoffs[player].getValue(outcome);
}
/**
* Sets the payoff for a player for a given outcome.
*
* @param outcome an array containing the actions chosen by each player
* @param player the player whose payoff should be returned.
* @param value the amount of the payoff
*/
protected void setPayoff(int[] outcome, int player, double value)
{
payoffs[player].setValue(value, outcome);
}
}
| 2,035 | 25.789474 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/MinimumEffortGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a Minimum Effort Game
*
* The MEG was coded as a TimingGame because it was very
* simple to add on using the TimingGame infrastructure. The
* downside is that the TimingGame class requires that
* MinimumEffortGame store many copies of the same parameters.
* It could be more efficient to set this up in another way.
*/
public class MinimumEffortGame extends TimingGame
{
// Parameters: A Minimum Effort Game is parameterized first by the
// number of players, next by the number of actions (in other words,
// the maximum level of effort which can be chosen), and finally by
// the values of the coefficients a, b, and c which are used in the
// payoff function a + bM - cE.
private static Parameters.ParamInfo pA;
private static Parameters.ParamInfo pB;
private static Parameters.ParamInfo pC;
private static Parameters.ParamInfo[] megParam;
static {
pA = new Parameters.ParamInfo("a", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-100), new Double(100), "constant a used in formula a + bM - cE. Should be between -100 and 100.");
pB = new Parameters.ParamInfo("b", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(100), "coefficient b used in formula a + bM - cE. Should be between 0 and 100.");
pC = new Parameters.ParamInfo("c", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(100), "coefficient used in formula a + bM - cE. Should be between 0 and 100 but must be < b.");
megParam = new Parameters.ParamInfo[] {Game.players, Game.symActions,
pA, pB, pC};
Global.registerParams(MinimumEffortGame.class, megParam);
}
// ----------------------------------------------
public MinimumEffortGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// Set the number of players and the number of actions (time
// steps) from the parameters
parsePlayersSameNumberActions();
}
//
// Make sure that the parameters are in the proper range
//
protected void checkParameters() throws Exception
{
if(getDoubleParameter(pC.name)
>= getDoubleParameter(pB.name))
throw new Exception("c >= b");
}
public void randomizeParameters()
{
// Force that user randomize all or none of a, b, and c
if ((parameters.setByUser(pA.name) != parameters.setByUser(pB.name)) ||
(parameters.setByUser(pA.name) != parameters.setByUser(pC.name))) {
Global.handleError("Randomization Error: Please set all or " +
"none of parameters a, b, and c.");
}
if (!parameters.setByUser(pA.name)) {
// Need to randomize all three
parameters.randomizeParameter(pA.name);
parameters.randomizeParameter(pB.name);
// Reset range on c as it must always be less than b
pC.high = new Double(getDoubleParameter(pB.name));
parameters.randomizeParameter(pC.name);
}
}
protected String getGameHelp()
{
return "Creates an instance of the Minimum Effort Game.\n\n" +
"In this game, the payoff for a player is determined by a " +
"formula a + bM - cE where E is the player's effort and M " +
"is the minimum effort of any player.";
}
public void doGenerate()
{
// Get parameter values
double a = getDoubleParameter(pA.name);
double b = getDoubleParameter(pB.name);
double c = getDoubleParameter(pC.name);
setDescription("Minimum Effort Game\n" + getDescription());
setName("Minimum Effort Game");
int players = getNumPlayers();
// Create TimingGameParams objects which will be
// necessary to hold the function parameters for each player
TimingGameParams low[] = new TimingGameParams[players];
TimingGameParams notLow[] = new TimingGameParams[players];
TimingGameParams tie[] = new TimingGameParams[players];
// All players have the same parameters in their functions
// all of the time
for (int i = 0; i < players; i++) {
low[i] = new TimingGameParams(-c, b, a);
notLow[i] = new TimingGameParams(-c, b, a);
tie[i] = new TimingGameParams(-c, b, a);
}
// Finally, set these parameters so that the payoff can be
// calculated using the timing game class
setParamsWithTie(low, tie, notLow);
}
}
| 4,942 | 31.519737 | 194 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/NPlayerChicken.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Generate an instance of the N-Player Chicken game. Subclasses
* Game directly without an intermediate layer.
*
*/
public class NPlayerChicken extends Game
{
//---------------------------------------------------------
// Parameters: N-player Chicken is parameterized by
// the numbers of players, the number of players who must
// cooperate to get the higher payoffs.
private static Parameters.ParamInfo cut;
private static Parameters.ParamInfo[] npcParam;
static {
// The randomization max for the cut will be reset to
// the number of players and is therefore unimportant
cut = new Parameters.ParamInfo("cutoff", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(100), "the number of players who need to cooperate to get the reward. Must be > 0 and <= players.");
npcParam = new Parameters.ParamInfo[] {Game.players, cut};
Global.registerParams(NPlayerChicken.class, npcParam);
}
// -----------------------------------------------------
// The following variables must be set when the game is generated.
// They are later used to determine the payoffs for each player
// at each scenario
private long cutoff;
private double reward;
private double cost;
// -----------------------------------------------------
public NPlayerChicken()
throws Exception
{
super();
}
/**
* Set the numbers of players and actions for the game,
* initilaize variables, and so on.
*/
public void initialize()
throws Exception
{
super.initialize();
// The number of players is extensible but the number
// of actions must always be 2
int players = (int) getLongParameter(Game.players.name);
setNumPlayers(players);
int numActions[];
numActions = new int[players];
for (int i = 0; i < players; i++)
numActions[i] = 2;
setNumActions(numActions);
}
/**
* Make sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if(getLongParameter(cut.name) <= 0)
throw new Exception("cutoff <= 0");
if(getLongParameter(cut.name)
> getLongParameter(Game.players.name))
throw new Exception("cutoff > players");
}
/**
* Randomize the parameters which were not filled in by the user.
*/
public void randomizeParameters()
{
cut.high = new Long(getLongParameter(Game.players.name));
parameters.randomizeParameter(cut.name);
}
/**
* Determine whether the number of players who chose action
* one is high enough that everyone gets the reward.
*/
private boolean allGetReward(int[] outcome) {
int numChoseOne = 0;
int players = getNumPlayers();
for (int i = 0; i < getNumPlayers(); i++)
if (outcome[i] == 1)
numChoseOne++;
if (numChoseOne >= cutoff)
return true;
return false;
}
/**
* Return the payoff for the given player in the given
* outcome. Assumes everything has already been set up.
*/
public double getPayoff(int[] outcome, int player) {
double payoff;
if (outcome[player] == 1) {
if (allGetReward(outcome)) {
payoff = reward - cost;
} else {
payoff = -cost;
}
} else {
if (allGetReward(outcome)) {
payoff = reward;
} else {
payoff = 0;
}
}
return payoff;
}
/**
* Return a Vector with all players' utilities at the
* given outcome
*/
public Vector getPayoff(int[] outcome)
{
int players = getNumPlayers();
Vector payoffVector = new Vector(players);
if (allGetReward(outcome)) {
for (int i = 0; i < players; i++) {
Double payoff;
if (outcome[i] == 1) {
payoff = new Double (reward - cost);
} else {
payoff = new Double (reward);
}
payoffVector.add (i, payoff);
}
} else {
for (int i = 0; i < players; i++) {
Double payoff;
if (outcome[i] == 1) {
payoff = new Double (-cost);
} else {
payoff = new Double (0);
}
payoffVector.add (i, payoff);
}
}
return payoffVector;
}
protected String getGameHelp()
{
return "Creates an instance of the N-Player Chicken Game.\n\n" +
"In N-Player Chicken, just as in the typical two player " +
"version of the game, players may cooperate or defect. " +
"There is a cost for choosing to cooperate. However, if " +
"a certain number of players choose to cooperate, then " +
"all players receive a reward.\n\n" +
"The cost and reward amounts are always chosen between 1 " +
"and 100 (with reward > cost). To change this range, " +
"use normalization.";
}
/**
* Generate the game.
*/
public void doGenerate() {
cutoff = getLongParameter(cut.name);
double lowCandR = 1;
double highCandR = 100;
// Choose the reward and cost amounts, such that the cost
// is less than the reward
SortedAndRandomSet values = new SortedAndRandomSet();
for (int i = 0; i < 2; i++) {
Double randomAsDouble;
do {
double random = Global.randomDouble(lowCandR, highCandR);
randomAsDouble = new Double(random);
} while (!(values.add(randomAsDouble)));
}
Double b = (Double) values.removeLargest();
Double c = (Double) values.removeLargest();
reward = b.doubleValue();
cost = c.doubleValue();
setDescription("N-Player Chicken\n" + getDescription());
setName("N-Player Chicken");
int players = getNumPlayers();
int actions = getNumActions(0); // always 2 for all players
}
}
| 6,219 | 23.488189 | 198 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/NPlayerPrisonersDilemma.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Generate an instance of N-Player Prisoner's Dilemma game as
* follows.
*
* Let C(i) be the payoff if you cooperate and i others cooperate,
* and let D(i) be the payoff if you defect while i others cooperate,
* such that
*
* 1) D(i) > C(i) for 0 <= i <= n-1
* 2) D(i+1) > D(i) and also C(i+1) > C(i) for 0 <= i < n-1
* 3) C(i) > (D(i) + C(i-1)) / 2 for 0 < i <= n-1
*
* For now this is done by using a linear function
* C(i) = Xc + Y
* D(i) = Xc + Z
* where 0 < Z - Y < X
*/
public class NPlayerPrisonersDilemma extends Game
{
private static final long COOPERATE = 1;
private static final long DEFECT = 2;
private double X, Y, Z;
//---------------------------------------------------------
// Parameters: N-player PD is parameterized by
// the numbers of players, and high and low bounds on
// the possible payoffs.
private static Parameters.ParamInfo paramX, paramY, paramZ;
private static Parameters.ParamInfo[] npdParam;
static {
// The upper bound of 100 on the randomization values
// of these variables was chosen somewhat arbitrarily.
paramX = new Parameters.ParamInfo("function_X", Parameters.ParamInfo.DOUBLE_PARAM, new Double (1), new Double(100000), "X in payoff functions (see description). Must be set such that 0 < Z - Y < X and all parameters must be less than 100,000.");
paramY = new Parameters.ParamInfo("function_Y", Parameters.ParamInfo.DOUBLE_PARAM, new Double (1), new Double(100000), "Y in payoff functions (see description). Must be set such that 0 < Z - Y < X and all parameters must be less than 100,000.");
paramZ = new Parameters.ParamInfo("function_Z", Parameters.ParamInfo.DOUBLE_PARAM, new Double (1), new Double(100000), "Z in payoff functions (see description). Must be set such that 0 < Z - Y < X and all parameters must be less than 100,000.");
npdParam = new Parameters.ParamInfo[] {Game.players, paramX,
paramY, paramZ};
Global.registerParams(NPlayerPrisonersDilemma.class, npdParam);
}
// -----------------------------------------------------
public NPlayerPrisonersDilemma()
throws Exception
{
super();
}
/**
* Set the numbers of players and actions for the game,
* initilaize variables, and so on.
*/
public void initialize()
throws Exception
{
super.initialize();
// The number of players is extensible but the number
// of actions must always be 2
int players = (int) getLongParameter(Game.players.name);
setNumPlayers(players);
int numActions[];
numActions = new int[players];
for (int i = 0; i < players; i++)
numActions[i] = 2;
setNumActions(numActions);
}
/**
* Make sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if (getDoubleParameter(paramX.name) < 2)
throw new Exception ("function_X < 2");
if (getDoubleParameter(paramY.name) >=
getDoubleParameter(paramZ.name))
throw new Exception ("function_Y >= function_Z");
if (getDoubleParameter(paramZ.name) -
getDoubleParameter(paramY.name) >=
getDoubleParameter(paramX.name))
throw new Exception ("function_Z - function_Y >= function_X");
}
/**
* Randomize parameters that were not set by the user
*/
public void randomizeParameters() {
// Force that either all of X, Y, and Z are set by the
// user, or none of them are set.
if ((!parameters.setByUser(paramX.name))
&& (!parameters.setByUser(paramY.name))
&& (!parameters.setByUser(paramZ.name))) {
// randomize such that 0 < Z - Y < X
parameters.randomizeParameter(paramY.name);
paramZ.low = new Double(getDoubleParameter(paramY.name));
parameters.randomizeParameter(paramZ.name);
paramX.low = new Double(getDoubleParameter(paramZ.name) -
getDoubleParameter(paramY.name));
parameters.randomizeParameter(paramX.name);
} else if ((!parameters.setByUser(paramX.name))
|| (!parameters.setByUser(paramY.name))
|| (!parameters.setByUser(paramZ.name))) {
Global.handleError("Randomization error. User must set values " +
"for all or none of function_X, function_Y, " +
"and function_Z parameters.");
}
}
/**
* Return the number of players who have chosen "cooperate"
* (i.e. action #1) in a given outcome
*/
private long numberOfCs(int[] outcome) {
long numCs = 0;
for (int i = 0; i < getNumPlayers(); i++) {
if (outcome[i] == COOPERATE) {
numCs++;
}
}
return numCs;
}
/**
* Evaluates payoff function. Note that numCs should include
* the current player if he is cooperating. This will be
* adjusted for automatically.
*/
private double evaluatePayoffFunction(long numCs, long action) {
if (action == COOPERATE) {
return (X * (numCs - 1)) + Y;
}
return (X * numCs) + Z;
}
/**
* Return the payoff for the given player in the given
* outcome. Assumes everything has already been set up.
*/
public double getPayoff(int[] outcome, int player) {
long numCs = numberOfCs(outcome);
double payoff = evaluatePayoffFunction(numCs, outcome[player]);
return (payoff);
}
/**
* Return a Vector with all players' utilities at the
* given outcome
*/
public Vector getPayoff(int[] outcome)
{
int players = getNumPlayers();
Vector payoffVector = new Vector(players);
long numCs = numberOfCs(outcome);
for (int i = 0; i < players; i++) {
Double payoff = new Double
(evaluatePayoffFunction(numCs, outcome[i]));
payoffVector.add(i, payoff);
}
return payoffVector;
}
protected String getGameHelp()
{
return "Creates an instance of the N-Player Prisoner's " +
"Dilemma Game. In the N-Player Prisoner's Dilemma, " +
"the payoff to each player is based on the number of " +
"players who cooperate not including the player himself.\n\n" +
"If the number of other players who cooperate is i, then we " +
"say that C(i) is the payoff for cooperating and D(i) is the " +
"payoff for defecting." +
"In order for this payoff scheme to result in a Prisoner's " +
"Dilemma, it must be the case that: \n" +
" 1) D(i) > C(i) for 0 <= i <= n-1 \n" +
" 2) D(i+1) > D(i) and also C(i+1) > C(i) for 0 <= i < n-1 \n" +
" 3) C(i) > (D(i) + C(i-1)) / 2 for 0 < i <= n-1 \n\n" +
"We guarantee these conditions are met by using linear " +
"functions for which you may provide the parameters: \n" +
" C(i) = Xc + Y\n" +
" D(i) = Xc + Z\n" +
"where 0 < Z - Y < X.";
}
/**
* Generate the game
*/
public void doGenerate() {
// -- get Parameter values
X = getDoubleParameter(paramX.name);
Y = getDoubleParameter(paramY.name);
Z = getDoubleParameter(paramZ.name);
int players = getNumPlayers();
int actions = getNumActions(0); // always 2 for all players
setDescription("N-Player Prisoner's Dilemma\n"
+ getDescription());
setName("N-Player Prisoner's Dilemma");
}
}
| 7,853 | 27.98155 | 247 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/Outcome.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.NoSuchElementException;
/**
* The utility class encapsulates the notion of an outcome
* Action numbering starts at one
*/
public class Outcome
{
private int nPlayers;
private int[] nActions;
private int nOutcomes;
private int[] actions;
private boolean hasMore;
public Outcome(int nPlayers, int[] nActions)
{
this.nPlayers = nPlayers;
this.nActions = nActions;
nOutcomes = nActions[0];
for (int i = 1; i < nPlayers; i++) {
nOutcomes *= nActions[i];
}
actions = new int[nPlayers];
hasMore=false;
reset();
}
public int[] getNumActions()
{
return nActions;
}
public int getNumPlayers()
{
return nPlayers;
}
public int getNumOutcomes()
{
return nOutcomes;
}
public void reset()
{
// Technically speaking, we do not always have more here, but
// need to set this to true in all cases to handle the case in
// which there is only one outcome. Will be corrected for the
// next time nextOutcome is called.
hasMore=true;
for(int i=0; i<nPlayers; i++)
actions[i]=1;
}
public void reset(int[] actions) throws ArrayIndexOutOfBoundsException
{
hasMore=false;
for(int i=0; i<nPlayers;i++)
{
if(actions[i]<1 || actions[i]>nActions[i])
throw new ArrayIndexOutOfBoundsException("Action out of Bounds");
this.actions[i]=actions[i];
if(actions[i] <nActions[i])
hasMore=true;
}
}
public int[] getOutcome()
{
return actions;
}
public boolean hasMoreOutcomes()
{
return hasMore;
}
/**
* In a two by two matrix game, the outcomes are looped over
* in the order top left, bottom left, top right, bottom right.
* Can extend this idea of first player's actions being looped
* through quickly and repeatedly, and last player's actions
* being looped through slowly and only once to figure out
* ordering for games of other sizes.
*/
public void nextOutcome() throws NoSuchElementException
{
if(!hasMore) throw new NoSuchElementException("No More Outcomes");
for(int i=0; i<nPlayers; i++)
{
if(actions[i] < nActions[i])
{
actions[i]++;
break;
}
else
{
actions[i] = 1;
if( i == nPlayers - 1 )
hasMore = false;
}
}
}
public String toString()
{
StringBuffer buf = new StringBuffer();
buf.append("[");
for(int i=0; i<nPlayers; i++)
buf.append(actions[i]).append( (i < nPlayers -1 ? " " : "]") );
return buf.toString();
}
public static void main(String[] args)
{
int[] nActions={4,2,3};
Outcome out = new Outcome(3, nActions);
for(out.reset(); out.hasMoreOutcomes(); out.nextOutcome())
{
System.out.println(out);
}
//out.nextOutcome();
}
}
| 3,491 | 21.101266 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/ParamParser.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Class for parsing command line parameters
* Keeps track of bookkeeping as well
*/
public class ParamParser
{
public static ParamParser emptyParser = new ParamParser();
// ------------------------------------------
// -- Data to hold semi-parsed arguments
private HashMap argmap;
private String description = null;
private static class ParamPair
{
Vector val;
boolean used=false;
public ParamPair(Vector val)
{
this.val=val;
this.used=false;
}
}
private int usedCount=0;
public ParamParser()
{
argmap=new HashMap();
usedCount=0;
}
/**
* Constructor to use if the arguments are coming from the
* command line and are thus already parsed into an array.
* Fills in the argmap.
*/
public ParamParser(String[] args) throws Exception
{
argmap=new HashMap();
usedCount=0;
if (args == null) {
description = "[]";
return;
}
description = "[ " + GameOutput.arrayToString(args, " ") + " ]";
int i=0;
while(i<args.length)
{
if(args[i].charAt(0)!='-')
throw new Exception("Error Parsing Parameters: " + args[i]);
String key=args[i].substring(1);
Vector val=new Vector();
while((++i < args.length))
{
// -- Case 1: doesn't start with -
// -- So it's either a normal value, or start of "parser" value
if(args[i].charAt(0)!='-')
{
// -- If it's not a parser
if(args[i].charAt(0)!='[')
{
val.add(args[i]);
continue;
}
//-- else deal with parser param.
Vector cmdline=new Vector();
//-first argument
if(args[i].length()!=1) // -- if no space after [
{
//cmdline.add(args[i].substring(1));
args[i] = args[i].substring(1);
i--;
}
// -- add things till last closing ]
int openCount=1;
while( (openCount > 0) && (++i < args.length) )
{
if(args[i].charAt(0)=='[')
openCount++;
int clcc=closeCount(args[i]);
if(clcc>0)
{
openCount-=clcc;
if(args[i].length()!=1)
cmdline.add(args[i].substring(0,args[i].length()-1));
}
else
cmdline.add(args[i]);
}
if(openCount>0)
throw new Exception("Unbalanced []!");
val.add(cmdline);
continue;
}
// -- Case 2: start's with -
// -- so it's either next param, or a negative number
if(args[i].length()==1)
throw new Exception("Bad Parameter: -");
if(Character.isDigit(args[i].charAt(1)))
{
val.add(args[i]);
continue;
}
break; //it start's with -, not a number, so next param
}
argmap.put(key, new ParamPair(val));
}
}
/**
* Checks number of closing braces ] in a string.
*/
private static int closeCount(String s)
{
int count=0;
int i=s.length();
while( (--i>=0) && s.charAt(i)==']')
count++;
return count;
}
/**
* Checks if all arguments are used
*/
public boolean hasUnusedArgs()
{
return (argmap.size() > usedCount);
}
/**
* Returns unused arguments
*/
public String[] getUnusedArgs()
{
String[] args=new String[argmap.size()-usedCount];
Iterator it=argmap.entrySet().iterator();
String key="";
int i=0;
while(it.hasNext())
{
Map.Entry e = (Map.Entry)it.next();
ParamPair p = (ParamPair)e.getValue();
if(!p.used)
args[i++]=(String)e.getKey();
}
return args;
}
/**
* Fills in hashmap with parameter values
*/
public void setParameters(Parameters pars)
throws Exception
{
Parameters.ParamInfo[] info = pars.getParamInfo(); //, HashMap params, boolean[] used
for(int i=0; i<info.length; i++)
{
if(pars.isParamSet(i) && !argmap.containsKey(info[i].name))
continue;
// -- Don't override previously set params
if(pars.setByUser(i))
continue;
boolean used = argmap.containsKey(info[i].name);
if(used)
{
ParamPair p = (ParamPair)argmap.get(info[i].name);
if(!p.used)
{
p.used=true;
argmap.put(info[i].name, p);
usedCount++;
}
Object val=parseParam(p.val, info[i]);
pars.setParameter(i, val, true);
}
else if (info[i].defaultValue!=null)
pars.setParameter(i, info[i].defaultValue, false);
}
}
/**
* Convert String into an appropriate object
*/
private Object parseParam(Vector val, Parameters.ParamInfo p)
throws NumberFormatException, Exception
{
switch(p.type)
{
case Parameters.ParamInfo.LONG_PARAM:
{
if(val.size()!=1)
throw new Exception("Parse error: " + p.name + " takes a single argument!");
Long v = Long.valueOf((String)val.get(0));
long high=((Long)p.high).longValue();
long low=((Long)p.low).longValue();
if(v.longValue() < low || v.longValue() > high)
throw new Exception("Out of range: " + p.name + "=" + v);
return v;
}
case Parameters.ParamInfo.DOUBLE_PARAM:
{
if(val.size()!=1)
throw new Exception("Parse error: " + p.name + " takes a single argument!");
Double v = Double.valueOf((String)val.get(0));
double high=((Double)p.high).doubleValue();
double low=((Double)p.low).doubleValue();
if(v.doubleValue() < low || v.doubleValue() > high)
throw new Exception("Out of range: " + p.name + "=" + v);
return v;
}
case Parameters.ParamInfo.BOOLEAN_PARAM:
{
if(val.size()> 1)
throw new Exception("Parse error: " + p.name + " takes at most one argument!");
if(val.size()==0) // -- used as a flag, indicates true
return Boolean.TRUE;
// -- otherwise need to parse the value
try {
int v = Integer.valueOf((String)val.get(0)).intValue();
if(v == 0)
return Boolean.FALSE;
if(v == 1)
return Boolean.TRUE;
throw new Exception();
} catch (Exception e) {
throw new Exception("Parse error: " + p.name + " takes 0 or 1 as an argument!");
}
}
case Parameters.ParamInfo.STRING_PARAM:
if(val.size()!=1)
throw new Exception("Parse error: " + p.name + " takes a single argument!");
return val.get(0);
case Parameters.ParamInfo.VECTOR_PARAM:
if(val.size()==0)
throw new Exception("Parse error: " + p.name + " needs at least one argument!");
return val;
case Parameters.ParamInfo.CMDLINE_PARAM:
if(val.size()!=1)
throw new Exception("Parse error: " + p.name + " takes a single argument in []!");
Vector cmdline=(Vector)val.get(0);
ParamParser pVal = new ParamParser((String[])cmdline.toArray(new String[]{}));
return pVal;
default:
throw new Exception("INTERNAL EXCEPTION: UNKNOWN PARAM TYPE!");
}
}
// -----------------------------------------------------
/**
* Converts to String
*/
public String toString()
{
return description;
}
/**
* Used for debugging only
*/
public static void main(String[] args) throws Exception
{
ParamParser p=new ParamParser(args);
System.out.println(p);
}
}
| 7,931 | 23.036364 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/ParameterizedObject.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import java.io.*;
/**
* Abstract class that can be extended by any class
* which needs to use the parameter set-up.
*/
public abstract class ParameterizedObject
{
protected Parameters parameters;
// ----------------------------------------------------
// Shortcuts to parameter functions
/**
* Returns the Parameters object of the class.
*/
public Parameters getParameters() {
return parameters;
}
/**
* Returns the value of the parameter with the given name
* as an Object.
*
* @param name parameter to return
*/
public Object getParameter(String name) {
return parameters.getParameter(name);
}
/**
* Returns the value of the parameter with the given name
* as a long (assuming the parameter is of type long).
*
* @param name parameter to return
*/
public long getLongParameter(String name) {
return parameters.getLongParameter(name);
}
/**
* Returns the value of the parameter with the given name
* as a boolean (assuming the parameter is of type boolean).
*
* @param name parameter to return
*/
public boolean getBooleanParameter(String name) {
return parameters.getBooleanParameter(name);
}
/**
* Returns the value of the parameter with the given name
* as a double (assuming the parameter is of type double).
*
* @param name parameter to return
*/
public double getDoubleParameter(String name) {
return parameters.getDoubleParameter(name);
}
/**
* Returns the value of the parameter with the given name
* as a String (assuming the parameter is of type String).
*
* @param name parameter to return
*/
public String getStringParameter(String name) {
return parameters.getStringParameter(name);
}
/**
* Sets the value of a parameter.
*
* @param name parameter to set the value of
* @param val value to set
* @throws Exception
*/
public void setParameter(String name, Object val)
throws Exception
{
parameters.setParameter(name, val);
}
/**
* Sets the value of a parameter.
*
* @param name parameter to set the value of
* @param val value to set
* @param byUser should be true if the parameter was set by the
* user on the command line
* @throws Exception
*/
public void setParameter(String name, Object val, boolean byUser)
throws Exception
{
parameters.setParameter(name, val, byUser);
}
// ------------------------------------------------------
/**
* The consctructor. Must be called by all subclasses
* It sets all parameter names/types and parses the parameter
* values passed to it
*/
protected ParameterizedObject()
throws Exception
{
Parameters.ParamInfo[] paramInfo=Global.getClassParamInfo(getClass());
parameters = new Parameters(paramInfo);
}
//
// Set Parameters in batch mode
//
/**
* Sets multiple parameters at once using a ParamParser.
*
* @param p the ParamParser containing the parameters and
* their values
* @param randomize should be set to true if it is desired
* that any unset parameters be randomized
* @throws Exception
*/
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
parameters.setFromParser(p);
if(randomize)
randomizeParameters();
}
/**
* Sets multiple parameters at once using a Parameters variable.
*
* @param p the Parameters variable containing the parameters and
* their values
* @param randomize should be set to true if it is desired
* that any unset parameters be randomized
* @throws Exception
*/
public void setParameters(Parameters p, boolean randomize)
throws Exception
{
parameters.setFromParams(p);
if(randomize)
randomizeParameters();
}
/**
* Initializes using preset parameter values.
*
* @throws Exception
*/
public void initialize()
throws Exception
{
// -- Assumes That Parameters Are already set
parameters.checkSet();
checkParameters();
}
/**
* Sets values of any unset parameters randomly. Can and should be
* overridden in subclasses to handle a non-uniform distribution
* and for constraints on parameters.
*/
public void randomizeParameters()
{
parameters.randomizeParameters();
}
/**
* Constructs a string with all parameter values.
*
* @param sep seperator to be placed between parameter values
*/
public String getParamDescription(String sep)
{
StringBuffer buff = new StringBuffer();
int n = parameters.getNParams();
for(int i=0; i<n; i++)
buff.append(parameters.getName(i) + ":\t" +
parameters.getParameter(i) + (i < n-1 ? sep : ""));
return buff.toString();
}
/**
* Returns description of the class. Subclasses should override.
*/
public String getDescription()
{
// -- by default, just spit out parameters
return "{ " + getParamDescription(", ") + " }";
}
/**
* Checks if Parameter values are consistent. Must be
* implemented by every non-abstract subclass of
* ParameterizedObject.
*
* @throws Exception if anything is wrong with the parameter
* values
*/
protected abstract void checkParameters() throws Exception;
/**
* Generate a (random) instance of the subclass based on
* input parameters.
*/
public abstract void doGenerate();
/**
* Return the help screen
*/
public abstract String getHelp();
}
| 6,522 | 24.782609 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/Parameters.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Class to hold parameter array objects and return
* parameter info.
*/
public class Parameters
{
private ParamInfo[] paramInfo;
private boolean[] paramSet;
private HashMap parameters;
private boolean[] userSet; // -- flag indicates param was set by user.
/**
* The constructor
*
* @param paramInfo an array of parameter information used to set
* up the hashmap and other necessary variables
*/
public Parameters(ParamInfo[] paramInfo) {
this.paramInfo=paramInfo;
parameters = new HashMap(paramInfo.length);
paramSet = new boolean[paramInfo.length];
userSet = new boolean[paramInfo.length];
for(int i=0; i<paramSet.length; i++)
paramSet[i] = userSet[i] = false;
}
/**
* Parses parameters and checks to make sure the required
* ones are there
*/
public void setFromParser(ParamParser p)
throws Exception
{
p.setParameters(this);
}
/**
* Parses parameters and checks to make sure the required
* ones are there
*/
public void setFromParams(Parameters p)
throws Exception
{
int n=getNParams();
for(int i=0; i<n; i++)
{
// -- don't override previously set params
if(p.isParamSet(getName(i)) && !setByUser(i))
setParameter(i, p.getParameter(getName(i)), p.setByUser(getName(i)));
}
}
/**
* Checks that every parameter has been set somehow
*
* @throws Exception if a required parameter is missing
*/
public void checkSet()
throws Exception
{
for(int i=0; i<paramInfo.length; i++)
if(!paramSet[i])
throw new Exception ((paramInfo[i].required ? "Required " : "") +
"Parameter " +
paramInfo[i].name + " is not set!"
);
}
/**
* Returns parameter info in a string with help
*/
public String getPrintableInfo() {
String info = new String();
if (paramInfo.length == 0) {
info = "No parameters.";
}
else {
for(int i=0; i<paramInfo.length; i++)
info = info + "-" + paramInfo[i].name +
":\t" + paramInfo[i].help + "\n";
}
return info;
}
/**
* Returns name of ith parameter
*/
public String getName(int i) {
return paramInfo[i].name;
}
/**
* Returns parameter information
*/
public ParamInfo[] getParamInfo()
{
return paramInfo;
}
/**
* Returns parameter set
*/
public boolean[] getParamSet()
{
return paramSet;
}
/**
* Returns parameters as a hashmap
*/
public HashMap getParametersAsHash()
{
return parameters;
}
/**
* Returns number of parameters
*/
public int getNParams()
{
return paramInfo.length;
}
/**
* Check if indexed parameter is set
*/
protected boolean isParamSet(int n)
{
return paramSet[n];
}
/**
* Check if parameter with the given name is set
*/
protected boolean isParamSet(String name)
{
return parameters.containsKey(name);
}
/**
* Implement accessors for parameters
*/
public Object[] getParameters()
{
Object[] vals = new Object[paramInfo.length];
for(int i=0; i<vals.length; i++)
vals[i] = getParameter(i);
return vals;
}
public void setParameters(Object[] params)
throws Exception
{
if(params.length!=paramInfo.length)
throw new Exception("setParameters: # of parameters differs");
for(int i=0; i<params.length; i++)
setParameter(i, params[i]);
}
public Object getParameter(int n)
{
return parameters.get(paramInfo[n].name);
}
public Object getParameter(String name)
{
return parameters.get(name);
}
public void setParameter(int n, Object val)
throws Exception
{
setParameter(n, val, false);
}
public void setParameter(int n, Object val, boolean byUser)
throws Exception
{
switch(paramInfo[n].type)
{
case ParamInfo.LONG_PARAM:
if (! (val instanceof Long) )
throw new Exception("setParameter: TYPE ERROR");
parameters.put(paramInfo[n].name, val);
paramSet[n] = true;
userSet[n] = byUser;
break;
case ParamInfo.DOUBLE_PARAM:
if (! (val instanceof Double) )
throw new Exception("setParameter: TYPE ERROR");
parameters.put(paramInfo[n].name, val);
paramSet[n] = true;
userSet[n] = byUser;
break;
case ParamInfo.STRING_PARAM:
if (! (val instanceof String) )
throw new Exception("setParameter: TYPE ERROR");
parameters.put(paramInfo[n].name, val);
paramSet[n] = true;
userSet[n] = byUser;
break;
case ParamInfo.BOOLEAN_PARAM:
if (! (val instanceof Boolean) )
throw new Exception("setParameter: TYPE ERROR");
parameters.put(paramInfo[n].name, val);
paramSet[n] = true;
userSet[n] = byUser;
break;
case ParamInfo.VECTOR_PARAM:
if (! (val instanceof Vector) )
throw new Exception("setParameter: TYPE ERROR");
parameters.put(paramInfo[n].name, val);
paramSet[n] = true;
userSet[n] = byUser;
break;
case ParamInfo.CMDLINE_PARAM:
if (! (val instanceof ParamParser) )
throw new Exception("setParameter: TYPE ERROR");
parameters.put(paramInfo[n].name, val);
paramSet[n] = true;
userSet[n] = byUser;
break;
default:
throw new Exception("Unknown Param Type " + paramInfo[n].type);
}
}
public void setParameter(String name, Object val)
throws Exception
{
setParameter(name, val, false);
}
public void setParameter(String name, Object val, boolean byUser)
throws Exception
{
int i=getParamIndex(name);
if(i==-1)
throw new Exception("setParameter: Unknown parameter " + name);
setParameter(i, val, byUser);
}
//
// Return the index of the given parameter
// == NOTE: Could be actually done as a hashmap!
// == NOTE: But this seems to be working,
// == NOTE: and currently not a bottleneck.
//
protected int getParamIndex(String name)
{
for(int i=0; i<paramInfo.length; i++)
if(paramInfo[i].name.equals(name))
return i;
return -1;
}
//
// For efficiency/convenience,
//
public long getLongParameter(String name)
{
return ((Long)getParameter(name)).longValue();
}
public double getDoubleParameter(String name)
{
return ((Double)getParameter(name)).doubleValue();
}
public String getStringParameter(String name)
{
return (String)getParameter(name);
}
public Vector getVectorParameter(String name)
{
return (Vector)getParameter(name);
}
public boolean getBooleanParameter(String name)
{
return ((Boolean)getParameter(name)).booleanValue();
}
public ParamParser getParserParameter(String name)
{
return (ParamParser)getParameter(name);
}
/**
* Return true if the parameter was set by the user
* and false otherwise
*/
public boolean setByUser(String name) {
int i = getParamIndex(name);
if(i == -1)
{
System.err.println("FATAL ERROR: Invalid parameter name "
+ name);
System.exit(1);
}
return userSet[i];
}
public boolean setByUser(int i) {
return userSet[i];
}
/**
* Randomize a single parameter based on its range. Note that this will
* result in the same status as set by user (i.e. non-default).
*/
public void randomizeParameter(int i)
{
try {
if(paramInfo[i].required || (paramSet[i] && userSet[i]))
return;
/*
if( paramSet[i] )
{
//System.err.println("WARNING: Randomizing Set Parameter " +
// paramInfo[i].name);
}
*/
switch(paramInfo[i].type)
{
case ParamInfo.LONG_PARAM:
{
long high = ((Long)paramInfo[i].high).longValue();
long low = ((Long)paramInfo[i].low).longValue();
long val=Math.abs(Global.rand.nextLong());
val %= (high - low + 1);
val +=low;
setParameter(i, new Long(val), true);
}
break;
case ParamInfo.DOUBLE_PARAM:
{
double high = ((Double)paramInfo[i].high).doubleValue();
double low = ((Double)paramInfo[i].low).doubleValue();
double val=Global.rand.nextDouble();
val = low + val*(high-low);
setParameter(i, new Double(val), true);
}
break;
case ParamInfo.BOOLEAN_PARAM:
setParameter(i, new Boolean(Global.randomBoolean()), true);
break;
case ParamInfo.CMDLINE_PARAM:
{
// Will be set to actual values later
setParameter(i, ParamParser.emptyParser, true);
}
break;
}
} catch (Exception e) {
Global.handleError(e, "Internal error in RandomizeParameters");
}
}
public void randomizeParameter(String name)
{
int ind=getParamIndex(name);
if(ind==-1)
{
System.err.println("FATAL ERROR: Invalid parameter name "
+ name);
System.exit(1);
}
randomizeParameter(ind);
}
/**
* Sets parameters uniformly at random. Can be overridden in
* subclasses for non uniform distribution, and for constraints
* on parameters.
*/
public void randomizeParameters()
{
for(int i=0; i<paramInfo.length; i++) {
randomizeParameter(i);
}
}
//--------------------------------------------------------------
/**
* Structure to hold parameter information
*/
public static class ParamInfo
{
public static final int LONG_PARAM=1;
public static final int DOUBLE_PARAM=2;
public static final int BOOLEAN_PARAM=3;
public static final int STRING_PARAM=4;
public static final int VECTOR_PARAM=5;
public static final int CMDLINE_PARAM=6;
public String name;
public int type;
public Object low;
public Object high;
public String help;
public boolean required=false;
public Object defaultValue=null;
public ParamInfo(String name, int type, Object low, Object high, String help)
{
this.name=name;
this.type=type;
this.low=low;
this.high=high;
this.help = help;
this.defaultValue = null;
}
public ParamInfo(String name, int type, Object low, Object high, String help, boolean required)
{
this.name=name;
this.type=type;
this.low=low;
this.high=high;
this.help = help;
this.required = required;
this.defaultValue = null;
}
public ParamInfo(String name, int type, Object low, Object high, String help, boolean required, Object defaultValue)
{
this.name=name;
this.type=type;
this.low=low;
this.high=high;
this.help = help;
this.required = required;
this.defaultValue = defaultValue;
}
}
}
| 11,282 | 21.840081 | 117 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/PolymatrixGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
/**
* Generate a Polymatrix Game with any given structure as long
* as the structure has been implemented as a graph class.
* For example, can be used to create polymatrix games with
* tree structures or ring structures.
*
* Similar to StructuredGraphicalGame except the payoff matrices
* in the graphical games are per node and the payoff matrices in
* the polymatrix game are per edge. (This means it is sensible
* for polymatrix games to have subgames that are not just random,
* unlike the random graphical games.)
*
*/
public class PolymatrixGame extends GraphicalGame
{
// ------------------------------------------------------
// Parameters: The polymatrix games takes in a graph class
// and a game class and the parameters for each of these.
//
private static Parameters.ParamInfo pGraph;
private static Parameters.ParamInfo pGraphParams;
private static Parameters.ParamInfo pSubGame;
private static Parameters.ParamInfo pSubGameParams;
private static Parameters.ParamInfo[] pgParam;
static {
pGraph = new Parameters.ParamInfo("graph", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the graph structure class to use");
pGraphParams = new Parameters.ParamInfo("graph_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the graph, must be enclosed in [].");
pSubGame = new Parameters.ParamInfo("subgame", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the game class to use as a subgame. There will be an error if the subgame does not have two players or if the number of actions for either of the players is different than that supplied by the actions parameter.");
pSubGameParams = new Parameters.ParamInfo("subgame_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the subgame, must be enclosed in []. If the \"players\" or \"actions\" parameters are generally required by this subgame, they may be left out. These will be reset to appropriate values automatically. All other parameters may be generated randomly and will then be regenerated for each instance of the subgame.");
pgParam = new Parameters.ParamInfo[] {Game.players,
Game.symActions, pGraph,
pGraphParams, pSubGame,
pSubGameParams};
Global.registerParams(PolymatrixGame.class, pgParam);
}
// ---------------------------------------------------
private ParamParser edgeGameParams;
private String subGameName;
boolean randomize;
// ---------------------------------------------------
public PolymatrixGame()
throws Exception
{
super();
}
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
}
/**
* Initialize this game, the graph, and the two player games.
*/
public void initialize()
throws Exception
{
super.initialize();
// Get number of players and actions
parsePlayersSameNumberActions();
// Initialize the graph
initGraph();
// The number of players is equal to the number of
// nodes in the graph, and the number of actions
// depends on the parameters of the random game
if( graph.getNNodes() != getNumPlayers() )
throw new Exception("Number of nodes in the graph must be the same as the number of players!");
if (graph.reflexEdgesOk())
throw new Exception("Reflexive edges not allowed in the graph!");
if (!graph.hasSymEdges())
throw new Exception("Graph used by LEG must be undirected!");
// Get the parameters for the edge games. These will
// be stored for later when the edge games are created.
edgeGameParams = parameters.getParserParameter(pSubGameParams.name);
subGameName = parameters.getStringParameter(pSubGame.name);
}
/**
* Randomize parameters that were not set by the user
*/
public void randomizeParameters() {
try {
if(!parameters.setByUser(pGraph.name))
parameters.setParameter(pGraph.name,
Global.getRandomClass(Global.GRAPH,
"GraphWithNodeParam"));
if(!parameters.setByUser(pSubGame.name))
parameters.setParameter(pSubGame.name,
Global.getRandomClass(Global.GAME,
"GameWithActionParam"));
} catch (Exception e) {
Global.handleError(e, "Randomizing Graphs/SubGames");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
/**
* This will be done for the subgame matrices and the graph
* separately
*/
protected void checkParameters() throws Exception
{
// -- if need to randomize graphs parameters, then must
// -- be able to set number of nodes
if(randomize && parameters.isParamSet(pGraph.name))
if(!Global.isPartOf(Global.GRAPH, getStringParameter(pGraph.name),
"GraphWithNodeParam"))
throw new Exception("ERROR: Cannot randomize graph parameters unless graph is an instance of GraphWithNodeParam!");
if(randomize && parameters.isParamSet(pSubGame.name))
if(!Global.isPartOf(Global.GAME, getStringParameter(pSubGame.name),
"GameWithActionParam"))
throw new Exception("ERROR: Cannot randomiza subgame parameters unless can set number of actions. Need an instance of GameWithActionParam!");
}
protected String getGameHelp()
{
return "Creates a polymatrix game using the given graph and " +
"the given subgame type to form two player edge games.\n\n" +
"If randomization is desired, graph must belong to the " +
"GraphWithNodesParam class, and subgame must support 2 players and belong to the GameWithActionParam class.";
}
/**
* Initialize a graph with the number of nodes
* equal to the number of players.
*/
protected void initGraph()
{
// Instantiate a graph of the type selected by the user
String graphName = parameters.getStringParameter(pGraph.name);
graph = (ALGraph) Global.getObjectOrDie(graphName, Global.GRAPH);
ParamParser graphParams =
parameters.getParserParameter(pGraphParams.name);
try {
if(randomize)
{
// -- manually set everything
graph.setParameter("nodes", new Long(getNumPlayers()), true);
// -- try to override reflexivity/symmetry params
try {graph.setParameter("reflex_ok", Boolean.FALSE, true);}
catch (Exception e) {}
try {graph.setParameter("sym_edges", Boolean.TRUE, true);}
catch (Exception e) {}
}
graph.setParameters(graphParams, randomize);
graph.initialize();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(graph.getHelp());
Global.handleError(e, "Error initializing graph: ");
}
}
/**
* Generates a new instance of the edge game. Needs to set
* parameters each time in case parameters are randomized.
*/
private Game generateNewEdgeGame(Game edgeGame)
throws Exception
{
if (randomize)
{
// -- override players/actions
try {edgeGame.setParameter("players", new Long(2), true);}
catch (Exception e) {
//System.err.println("Warning: could not set players parameter for subgame.");
}
try {edgeGame.setParameter("actions", getParameter("actions"),
true);}
catch (Exception e) {
//System.err.println("Warning: could not set actions parameter for subgame.");
}
}
edgeGame.setParameters(edgeGameParams, randomize);
edgeGame.initialize();
// Check to make sure that the subgame is valid to be
// used as part of a polymatrix game.
if (2 != edgeGame.getNumPlayers()) {
Global.handleError ("Subgames of polymatrix games " +
"must have two players: " + subGameName);
}
if ((getNumActions(0) != edgeGame.getNumActions(0)) ||
(getNumActions(0) != edgeGame.getNumActions(1))) {
Global.handleError ("Subgames of polymatrix games " +
"must have the same number of actions as " +
"the number which each player of the " +
"polymatrix game has: " + subGameName);
}
edgeGame.generate();
return edgeGame;
}
/**
* Generate the matrices for each node of the graph and
* the graph connecting neighbors to each other.
*/
public void doGenerate()
{
setDescription("Polymatrix Game\n" + getDescription());
setName("Polymatrix Game");
// Generate the graph for the game.
graph.doGenerate();
setDescription(getDescription() + "\nGraph Params:\n" + graph.getDescription());
for (int i = 0; i < graph.getNNodes(); i++) {
Iterator edgeIter = graph.getEdges(i);
while (edgeIter.hasNext()) {
Edge edge = (Edge) edgeIter.next();
Game edgeGame = null;
// Make sure the edge data was not set already as this
// might have happened when the reverse edge was set
if (edge.getData() == null) {
// Now make sure the reversed edge exists
Edge reverse = graph.getEdge(edge.getDest(),
edge.getSource());
try {
// Make sure there is a reverse
if (reverse == null)
throw new Exception ("Found edge without " +
"existence of reverse " +
"edge. Polymatrix games " +
"must use reflexive graphs.");
// Create a new instance of the edge game
// -- this is cleaner, it resets parameter status
// -- and parameter values
edgeGame = (Game) Global.getObjectOrDie(
subGameName,
Global.GAME);
edgeGame = generateNewEdgeGame(edgeGame);
} catch (Exception e) {
Global.handleError(e, "Unable to generate polymatrix game (subgame "+subGameName +")");
}
int[] dimensions = new int[2];
// Dimensions of matrix for player 2
dimensions[0] = getNumActions(edge.getDest());
dimensions[1] = getNumActions(edge.getSource());
DoubleTensor payMatrixDest = new DoubleTensor(dimensions);
// Dimensions of matrix for player 1
dimensions[0] = getNumActions(edge.getSource());
dimensions[1] = getNumActions(edge.getDest());
DoubleTensor payMatrixSource =
new DoubleTensor(dimensions);
Outcome outcome=new Outcome(2, dimensions);
outcome.reset();
int[] next = new int[2];
int[] reverseNext = new int[2];
while (outcome.hasMoreOutcomes()) {
next = outcome.getOutcome();
outcome.nextOutcome();
reverseNext[0] = next[1];
reverseNext[1] = next[0];
payMatrixSource.setValue
(edgeGame.getPayoff(next, 0), next);
payMatrixDest.setValue
(edgeGame.getPayoff(reverseNext, 1),
reverseNext);
}
// Now set the data for the edges on the graph
try {
edge.setData(payMatrixSource);
reverse.setData(payMatrixDest);
} catch (Exception e) {
Global.handleError(e, "Error setting edge data");
}
}
}
}
}
}
| 11,583 | 30.392954 | 457 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/PrisonersDilemma.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return an instance of the two player Prisoner's Dilemma
*/
public class PrisonersDilemma extends MatrixGame
{
// Parameters: no parameters
private static Parameters.ParamInfo[] pdParam;
static {
pdParam = new Parameters.ParamInfo[] {};
Global.registerParams(PrisonersDilemma.class, pdParam);
}
// ----------------------------------------------
public PrisonersDilemma()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// The simple prisoner's dilemma game will always have
// 2 players with 2 actions each.
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 2;
setNumActions(numActions);
initMatrix();
}
//
// None to check
//
protected void checkParameters() throws Exception
{
}
//
// None to randomize
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates a 2x2 Prisoner's Dilemma" + getRangeHelp();
}
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
setDescription("Prisoner's Dilemma\n"
+ getDescription());
setName("Prisoner's Dilemma");
SortedAndRandomSet payoffValues = new SortedAndRandomSet();
Double t, r, p, s;
// Use rejection sampling to make sure the values of the
// four random payoffs chosen are such that r > (s+t) / 2
// where t is the largest payoff, r is second largest,
// and s is smallest
do {
// Generate four payoff values in the range from
// payoff_low to payoff_high. Make sure that the
// four values are distinct.
for (int i = 0; i < 4; i++) {
Double randomPayoffAsDouble;
do {
double randomPayoff = Global.randomDouble(low, high);
randomPayoffAsDouble = new Double(randomPayoff);
} while (!(payoffValues.add(randomPayoffAsDouble)));
}
t = (Double) payoffValues.removeLargest();
r = (Double) payoffValues.removeLargest();
p = (Double) payoffValues.removeLargest();
s = (Double) payoffValues.removeLargest();
} while (r.floatValue() <=
(s.floatValue() + t.floatValue()) / 2.0);
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
outcome.reset();
setPayoff(outcome.getOutcome(), 0, r.doubleValue());
setPayoff(outcome.getOutcome(), 1, r.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, t.doubleValue());
setPayoff(outcome.getOutcome(), 1, s.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, s.doubleValue());
setPayoff(outcome.getOutcome(), 1, t.doubleValue());
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, p.doubleValue());
setPayoff(outcome.getOutcome(), 1, p.doubleValue());
}
}
| 3,514 | 22.75 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/PureCoordinationMatrix.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Abstract class implements a normal form game which is
* common payoff and therefore only requires that the payoff
* for each outcome be stored once.
*/
public abstract class PureCoordinationMatrix extends Game
{
private DoubleTensor payoffs;
// -----------------------------------------------
/**
* Constructor for a new pure coordination matrix game.
*/
public PureCoordinationMatrix()
throws Exception
{
super();
}
/**
* Initializes the payoff array assuming the numbers of players
* and actions have already been set.
*/
protected void initMatrix()
{
payoffs = new DoubleTensor(getNumActions());
}
/**
* Returns the payoff for a player at a given outcome.
*
* @param outcome an array holding the action choices for each player
* @param player the player whose payoff should be returned, irrelevant
* since the game is common payoff
*/
public double getPayoff(int[] outcome, int player)
{
return payoffs.getValue(outcome);
}
/**
* Sets the payoff for all players for a given outcome.
*
* @param outcome an array holding the action choices for each player
* @param value the amount of the payoff for this outcome
*/
protected void setPayoff(int[] outcome, double value)
{
payoffs.setValue(value, outcome);
}
}
| 2,107 | 25.024691 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/RandomCompoundGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a compound game based on a randomly generated
* symmetric 2x2 matrix.
*/
public class RandomCompoundGame extends CompoundGame
{
// Parameters: The number of players is a parameter.
private static Parameters.ParamInfo[] rcgParam;
static {
rcgParam = new Parameters.ParamInfo[] {players};
Global.registerParams(RandomCompoundGame.class, rcgParam);
}
// ----------------------------------------------
public RandomCompoundGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
// Number of players and actions are initialized
// by the CompoundGame superclass, as is the graph.
super.initialize();
}
//
// Make sure that the parameters are in the proper range
//
protected void checkParameters() throws Exception
{
// None to check
}
//
// Randomize the parameters which were not filled in by
// the user.
//
public void randomizeParameters()
{
// None to randomize
}
protected String getGameHelp()
{
return "Creates a Compound Game from a randomly " +
"generated symmetric 2x2 matrix.\n\n" +
"A Compound Game is a game in which the payoff " +
"for each player is calculated as if he were playing " +
"the same two by two game with each of the other players " +
"and summing the payoffs.\n\n" +
"The values in the 2x2 game matrix are always " +
"chosen at random from values between -100 and 100. To " +
"change this range, use the normalization or integer " +
"payoff options.";
}
/**
* Generate the symmetric 2x2 subgame and create a polymatrix
* game with this 2x2 matrix at all edges except the edges
* from nodes to themselves which will have stub 0 matrices.
*/
public void doGenerate()
{
double low = -100;
double high = 100;
setDescription("Random Compound Game\n"
+ getDescription());
setName("Random Compound Game");
double R, S, T, P;
// Generate four subgame payoff values in the range
// from matrix_low to matrix_high.
R = Global.randomDouble(low, high);
S = Global.randomDouble(low, high);
T = Global.randomDouble(low, high);
P = Global.randomDouble(low, high);
generatePolymatrixGame(R, S, T, P);
}
}
| 3,000 | 23.598361 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/RandomGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a uniformly random game
*/
public class RandomGame extends MatrixGame
{
// -- Parameters: Random games are parameterized only on the
// number of players and the number of actions
private static Parameters.ParamInfo[] rgParam;
static {
rgParam = new Parameters.ParamInfo[] {Game.players, Game.actions};
Global.registerParams(RandomGame.class, rgParam);
}
// ----------------------------------------------
/**
* Construct a new game
*/
public RandomGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
parsePlayersActions();
initMatrix();
}
/**
* None to check
*/
protected void checkParameters() throws Exception
{
}
/**
* Return the help screen
*/
protected String getGameHelp()
{
return "Creates a game with the given number of players " +
"with payoffs distributed uniformly at random." +
getRangeHelp();
}
/**
* Fill in the payoffs
*/
public void doGenerate()
{
double low = DEFAULT_LOW;
double high= DEFAULT_HIGH;
setDescription("A Game With Uniformly Random Payoffs\n"
+ getDescription());
setName("Random Matrix Game");
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
for(outcome.reset(); outcome.hasMoreOutcomes(); outcome.nextOutcome())
{
for(int i=0; i<getNumPlayers(); i++)
setPayoff(outcome.getOutcome(), i,
Global.randomDouble(low, high));
}
}
}
| 2,249 | 21.5 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/RandomGraphicalGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
/**
* Generate a Graphical Game with any given structure as long
* as the structure has been implemented as a graph class.
* For example, can be used to create Ring Structured Games
* and Tree Structured Games.
*
* This is a working version of the graphical game with
* random payoffs. Other styles of payoffs are not yet
* implemented.
*
*/
public class RandomGraphicalGame extends GraphicalGame
{
// ------------------------------------------------------
// Parameters: Takes as parameters the graph to be used
// with its parameters, and the number of actions (which
// currently must be the same for all players).
//
private static Parameters.ParamInfo pGraph;
private static Parameters.ParamInfo pGraphParams;
private static Parameters.ParamInfo[] rggParam;
static {
pGraph = new Parameters.ParamInfo("graph", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the graph structure class to use");
pGraphParams = new Parameters.ParamInfo("graph_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the graph, must be enclosed in [].");
rggParam = new Parameters.ParamInfo[] {Game.players,
Game.symActions, pGraph,
pGraphParams};
Global.registerParams(RandomGraphicalGame.class, rggParam);
}
// ----------------------------------
private boolean randomize;
public RandomGraphicalGame()
throws Exception
{
super();
}
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
}
public void initialize()
throws Exception
{
super.initialize();
// Get number of players and actions
parsePlayersSameNumberActions();
// Initialize the graph
initGraph();
// The number of players is equal to the number of
// nodes in the graph, and the number of actions
// depends on the parameters of the random game
if( graph.getNNodes() != getNumPlayers() )
throw new Exception("Number of nodes in the graph must be the same as the number of players!");
if (graph.reflexEdgesOk())
throw new Exception("Reflexive edges not allowed in the graph!");
}
//
// This will be done for the subgame matrices and the graph
// separately
//
protected void checkParameters() throws Exception
{
// -- if need to randomize graphs parameters, then must
// -- be able to set number of nodes
if(randomize && parameters.isParamSet(pGraph.name))
if(!Global.isPartOf(Global.GRAPH, getStringParameter(pGraph.name),
"GraphWithNodeParam"))
throw new Exception("ERROR: Cannot randomize graph parameters unless graph is an instance of GraphWithNodeParam!");
}
//
// Randomize parameters that were not set by the user
//
public void randomizeParameters() {
try {
if(!parameters.setByUser(pGraph.name))
parameters.setParameter(pGraph.name,
Global.getRandomClass(Global.GRAPH, "GraphWithNodeParam"));
} catch (Exception e) {
Global.handleError(e, "Randomizing Graphs");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
protected String getGameHelp()
{
return "Creates a version of any random graphical game. " +
"Parameters for the given graph class " +
"must be set. If randomization is desired, graph must belong to the class GraphWithNodeParam. Note also that the number of nodes in the graph as implied by graph parameters must match the number of players.";
}
/**
* Initialize a graph with the number of nodes
* equal to the number of players.
*/
protected void initGraph()
{
// Instantiate a graph of the type selected by the user
String graphName = parameters.getStringParameter(pGraph.name);
graph = (ALGraph) Global.getObjectOrDie(graphName, Global.GRAPH);
ParamParser graphParams =
parameters.getParserParameter(pGraphParams.name);
try {
if(randomize)
{
// -- then manually set node parameter
graph.setParameter("nodes", new Long(getNumPlayers()), true);
// -- try to override reflexivity params
// -- NOTE:This code assumes that all graphs either have this
// -- NOTE: flag, or have reflex_ok always False.
// -- NOTE: This should be reflected in Docs
try {
graph.setParameter("reflex_ok", Boolean.FALSE, true);
} catch (Exception e) {}
}
graph.setParameters(graphParams, randomize);
graph.initialize();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(graph.getHelp());
System.err.println(graph.getDescription());
Global.handleError(e, "Error initializing graph: ");
}
}
/**
* Generate the matrices for each node of the graph
* graph and the graph connecting neighbors to each other.
*/
public void doGenerate()
{
setDescription("Random Graphical Game\n" + getDescription());
setName("Random Graphical Game");
// Generate the graph for the game.
graph.doGenerate();
setDescription(getDescription() + "\nGraph Params:\n" + graph.getDescription());
Vector actionsVector = new Vector(1);
actionsVector.add(0, String.valueOf(getNumActions(0)));
// Now that the graph has been generated, initialize the node
// games to have the correct number of players
for (int i = 0; i < getNumPlayers(); i++) {
// Count the number of edges attached to the node
// representing the player in the graph
long numPlayers = 1;
Iterator edgeIter = graph.getEdges(i);
while (edgeIter.hasNext()) {
edgeIter.next();
numPlayers++;
}
Long numPlayersLong = new Long(numPlayers);
Game nodeGame = null;
try {
nodeGame = new RandomGame();
nodeGame.parameters.setParameter(Game.players.name,
numPlayersLong);
nodeGame.parameters.setParameter(Game.actions.name,
actionsVector);
nodeGame.initialize();
} catch (Exception e) {
Global.handleError(e, "Unable to initialize node game");
}
int[] dimensions = new int[(int) numPlayers];
for (int j = 0; j < (int) numPlayers; j++)
dimensions[j] = getNumActions(0);
DoubleTensor payMatrix = new DoubleTensor(dimensions);
// Generate the matrix game for the node. An entire random
// game is created although only the payoffs for one player
// are used.
try {
nodeGame.generate();
} catch (Exception e) {
Global.handleError(e, "Error generating node game");
}
Outcome outcome=new Outcome(nodeGame.getNumPlayers(),
nodeGame.getNumActions());
outcome.reset();
int[] next = new int[(int)numPlayers];
while (outcome.hasMoreOutcomes()) {
next = outcome.getOutcome();
outcome.nextOutcome();
// Get payoffs for the first player
payMatrix.setValue
(nodeGame.getPayoff(next, 0), next);
}
// Now set the data for the node on the graph
try {
setNodeMatrix(i, payMatrix);
} catch (Exception e) {
Global.handleError(e, "Error setting node data");
}
nodeGame=null;
}
}
}
| 7,913 | 27.989011 | 213 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/RandomLEG.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Generate a Local Effect Game with a given graphical
* structure and a given function.
*
*/
public class RandomLEG extends LocalEffectGame
{
boolean randomize;
// --------------------------------------------------
// Parameters: The parameters taken by the random LEG
// are the name of the graph and function classes to be
// used, the numbers of players, as well as the parameters
// required by the particular graph and function classes.
//
protected static Parameters.ParamInfo pGraph;
protected static Parameters.ParamInfo pGraphParams;
protected static Parameters.ParamInfo pFunc;
protected static Parameters.ParamInfo pFuncParams;
protected static Parameters.ParamInfo[] rlegParam;
static {
pGraph = new Parameters.ParamInfo("graph", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the graph class to use");
pGraphParams = new Parameters.ParamInfo("graph_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the graph, must be enclosed in [].");
pFunc = new Parameters.ParamInfo("func", Parameters.ParamInfo.STRING_PARAM, null, null, "the name of the function class to use");
pFuncParams = new Parameters.ParamInfo("func_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the function, must be enclosed in [].");
rlegParam = new Parameters.ParamInfo[] {Game.players, Game.symActions,
pGraph, pGraphParams,
pFunc, pFuncParams};
Global.registerParams(RandomLEG.class, rlegParam);
}
// -------------------------------------------------------
public RandomLEG()
throws Exception
{
super();
}
/**
* Set parameters for the LEG. The parameters for the function
* and graph will be taken care of later.
*/
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
}
/**
* Initialized the random local effect game
*/
public void initialize()
throws Exception
{
// The LocalEffectGame class takes care of initializing
// the number of players
super.initialize();
// Get number of players and actions
parsePlayersSameNumberActions();
// Initialize the graph
initGraph();
// The number of actions is equal to the number of
// nodes in the graph
if( graph.getNNodes() != getNumActions(0) )
throw new Exception("Number of nodes in the graph must be the same as the number of actions!");
if (!graph.hasSymEdges())
throw new Exception("Graph used by LEG must be undirected!");
if (graph.reflexEdgesOk())
throw new Exception("Reflexive edges not allowed in LEG graphs!");
}
protected void checkParameters() throws Exception
{
// -- if need to randomize graphs parameters, then must
// -- be able to set number of nodes
if(randomize && parameters.isParamSet(pGraph.name))
if(!Global.isPartOf(Global.GRAPH, getStringParameter(pGraph.name),
"GraphWithNodeParam"))
throw new Exception("ERROR: Cannot randomize graph parameters unless graph is an instance of GraphWithNodeParam!");
}
//
// Randomize parameters not provided by the user
//
public void randomizeParameters() {
try {
if(!parameters.setByUser(pGraph.name))
parameters.setParameter(pGraph.name,
Global.getRandomClass(Global.GRAPH,
"GraphWithNodeParam"));
if(!parameters.setByUser(pFunc.name))
parameters.setParameter(pFunc.name,
Global.getRandomClass(Global.FUNC));
} catch (Exception e) {
Global.handleError(e, "Randomizing Graphs/Function");
}
// Deal with the CMDLINE_PARAM
super.randomizeParameters();
}
protected String getGameHelp()
{
return "Creates a Local-Effect Game using the specified " +
"graph class and specified function class.\n\nPlease note " +
"that you should be careful when you choose the graph " +
"class and set the graph parameters here. The graph " +
"chosen should be symmetric (i.e. whenever there is an " +
"edge from a to b there is also an edge from b to a) and " +
"should not have reflexive edges. Set the parameters for " +
"the graph accordingly!";
}
/**
* Initialize a graph with the number of nodes
* equal to the number of actions.
*/
protected void initGraph()
{
// Instantiate a graph of the type selected by the user
String graphName = parameters.getStringParameter(pGraph.name);
graph = (ALGraph) Global.getObjectOrDie(graphName,
Global.GRAPH);
ParamParser graphParams =
parameters.getParserParameter(pGraphParams.name);
try {
if(randomize)
{
// -- manually set everything if randomizing
graph.setParameter("nodes", new Long(getNumActions(0)), true);
// -- try to override reflexivity/symmetry params
try {graph.setParameter("reflex_ok", Boolean.FALSE, true);}
catch (Exception e) {}
try {graph.setParameter("sym_edges", Boolean.TRUE, true);}
catch (Exception e) {}
}
// -- set other parameters from command line.
graph.setParameters(graphParams, randomize);
graph.initialize();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(graph.getHelp());
e.printStackTrace();
Global.handleError(e, "Error initializing graph: ");
}
/*
// Make sure that the graph in use has symmetric edges
// and does not allow reflexive edges
if (!graph.hasSymEdges()) {
Global.handleError("It is required that the graph used " +
"in a Random LEG has symmetric edges.");
}
if (graph.reflexEdgesOk()) {
Global.handleError("It is required that the graph used " +
"in a Random LEG does not allow " +
"reflexive edges.");
}
*/
}
/**
* Generate the graph and for each node and edge of the graph,
* a function.
*/
public void doGenerate()
{
setDescription("Random Local-Effect Game\n" + getDescription());
setName("Random Local-Effect Game");
// Generate the graph for the game.
graph.doGenerate();
setDescription(getDescription() + "\nGraph Params:\n" + graph.getDescription());
String funcName = parameters.getStringParameter(pFunc.name);
ParamParser funcParams = parameters.getParserParameter(pFuncParams.name);
// Add a function of the appropriate type to each edge
// of the graph and to each node of the graph
for (int i = 0; i < graph.getNNodes(); i++) {
Function fNode = (Function) Global.getObjectOrDie(funcName,
Global.FUNC);
try {
fNode.setDomain(0, getNumPlayers());
fNode.setParameters(funcParams, randomize);
fNode.initialize();
fNode.doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(fNode.getHelp());
Global.handleError(e, "Error initializing function");
}
graph.setNodeData(i, fNode);
Iterator edgeIter = graph.getEdges(i);
while (edgeIter.hasNext()) {
Edge edge = (Edge) edgeIter.next();
Function fEdge = (Function) Global.getObjectOrDie(funcName,
Global.FUNC);
try {
fEdge.setDomain(0, getNumPlayers());
fEdge.setParameters(funcParams, randomize);
fEdge.initialize();
fEdge.doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(fEdge.getHelp());
Global.handleError(e, "Error initializing function");
}
edge.setData(fEdge);
}
}
}
}
| 8,350 | 28.718861 | 175 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/RandomZeroSum.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Create a random version of a two-player zero-sum game.
*/
public class RandomZeroSum extends ZeroSumGame
{
// Parameters: ZeroSumGame is parameterized by the number
// of actions for each player.
private static Parameters.ParamInfo[] rzsParam;
static {
rzsParam = new Parameters.ParamInfo[] {Game.actions};
Global.registerParams(RandomZeroSum.class, rzsParam);
}
// ----------------------------------------------
public RandomZeroSum()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// All zero sum games must have two players. The
// number of actions for each is extensible.
setNumPlayers(2);
parseActions();
initPayoffs(getNumActions(0), getNumActions(1));
}
//
// Nothing to check
//
protected void checkParameters() throws Exception
{
}
//
// Nothing to randomize
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates a 2 player Zero Sum Game" + getRangeHelp() + "\n\n" +
"Note that when normalization is used, there may be error " +
"in the last digits of the decimal payoffs resulting in a " +
"games which are occasionally not quite zero sum.";
}
/**
* Create an instance of the zero sum game
*/
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
setDescription("Zero Sum Game\n" + getDescription());
setName("Random Zero Sum Game");
Outcome outcome = new Outcome(2, getNumActions());
outcome.reset();
int[] next = new int[2];
// Loop through all outcomes in the matrix, generating
// random payoffs between payoff_low and payoff_high
// and randomly negating half of them
while (outcome.hasMoreOutcomes()) {
double pay = Global.randomDouble(low, high);
next = outcome.getOutcome();
outcome.nextOutcome();
if (Global.randomBoolean()) {
pay = -pay;
}
setPayoff(next, pay);
}
}
}
| 2,750 | 21.185484 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/RockPaperScissors.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return an instance of Rock, Paper, Scissors
*/
public class RockPaperScissors extends ZeroSumGame
{
// Parameters: none
private static Parameters.ParamInfo[] rpsParam;
static {
rpsParam = new Parameters.ParamInfo[] {};
Global.registerParams(RockPaperScissors.class, rpsParam);
}
// ----------------------------------------------
public RockPaperScissors()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// There will always be two players in this game, and they
// will always have three actions each.
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 3;
setNumActions(numActions);
initPayoffs(3, 3);
}
//
// None to check
//
protected void checkParameters() throws Exception
{
}
//
// None to randomize
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates an instance of the Rock, Paper, Scissors Game." +
getRangeHelp();
}
public void doGenerate()
{
double a = DEFAULT_HIGH;
setDescription("Rock, Paper, Scissors\n" + getDescription());
setName("Rock, Paper, Scissors");
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
// First column in matrix
outcome.reset();
setPayoff(outcome.getOutcome(), 0);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), -a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), a);
// Second column in matrix
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), -a);
// Third column in matrix
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), -a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0);
}
}
| 2,679 | 19 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/ShapleysGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return a version of Shapley's Game which is a
* variation on the standard Rock, Paper, Scissors.
*/
public class ShapleysGame extends MatrixGame
{
// Parameters: none
private static Parameters.ParamInfo[] sgParam;
static {
sgParam = new Parameters.ParamInfo[] {};
Global.registerParams(ShapleysGame.class, sgParam);
}
// ----------------------------------------------
public ShapleysGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// There will always be two players in this game, and they
// will always have three actions each.
setNumPlayers(2);
int numActions[];
numActions = new int[2];
numActions[0] = numActions[1] = 3;
setNumActions(numActions);
initMatrix();
}
//
// None to check
//
protected void checkParameters() throws Exception
{
}
//
// None to randomize
//
public void randomizeParameters()
{
}
protected String getGameHelp()
{
return "Creates an instance of Shapley's Game" +
"\n\nBy default, all payoffs will fall in the range " +
"[0, " + (int) DEFAULT_HIGH + "]. This range can be " +
"altered by setting the normalization options or " +
"by using integer payoffs.";
}
public void doGenerate()
{
double a = DEFAULT_HIGH;
setDescription("Shapley's Game\n" + getDescription());
setName("Shapley's Game");
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
// First column in matrix
outcome.reset();
setPayoff(outcome.getOutcome(), 0, 0);
setPayoff(outcome.getOutcome(), 1, 0);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, 0);
setPayoff(outcome.getOutcome(), 1, a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, a);
setPayoff(outcome.getOutcome(), 1, 0);
// Second column in matrix
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, a);
setPayoff(outcome.getOutcome(), 1, 0);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, 0);
setPayoff(outcome.getOutcome(), 1, 0);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, 0);
setPayoff(outcome.getOutcome(), 1, a);
// Third column in matrix
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, 0);
setPayoff(outcome.getOutcome(), 1, a);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, a);
setPayoff(outcome.getOutcome(), 1, 0);
outcome.nextOutcome();
setPayoff(outcome.getOutcome(), 0, 0);
setPayoff(outcome.getOutcome(), 1, 0);
}
}
| 3,257 | 21.163265 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/SimpleInspectionGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Return an instance of the Simple Inspection game
*/
public class SimpleInspectionGame extends GeometricGame
{
// --------------------------------------------------------
// Parameters: Geometric games must always have two players
// and a number of actions based on the available subsets which
// can be chosen. Thus the SimpleInspection Game is parameterized
// first on the number of elements in the set S and the max number
// which each of the two players can choose for their sets. The
// number of actions for each player is (|S| choose max number)
// + (|S| choose max number - 1) + ... + (|S| choose 1)
private static Parameters.ParamInfo sizeOfSet;
private static Parameters.ParamInfo maxForR;
private static Parameters.ParamInfo maxForB;
private static Parameters.ParamInfo[] sigParam;
static {
sizeOfSet = new Parameters.ParamInfo("set_size", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(8), "number of elements in set S from which the players choose elements. Must be > 0 but <= 8 in order o keep the number of actions reasonable.");
maxForR = new Parameters.ParamInfo("max_r", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(8), "maximum number of elements which player one (the \"red\" player) can choose from S. Must be > 0 and <= set_size.");
maxForB = new Parameters.ParamInfo("max_b", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(8), "maximum number of elements which player two (the \"blue\" player) can choose from S. Must be > 0 and <= set_size.");
sigParam = new Parameters.ParamInfo[] {sizeOfSet, maxForR, maxForB};
Global.registerParams(SimpleInspectionGame.class, sigParam);
}
// ----------------------------------------------
public SimpleInspectionGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// All geometric games have two players
setNumPlayers(2);
// Figure out how many actions each player has and
// set these numbers
int numActions[];
numActions = new int[2];
numActions[0] = (int)getGeoNumActions(getLongParameter(sizeOfSet.name),
getLongParameter(maxForR.name));
numActions[1] = (int)getGeoNumActions(getLongParameter(sizeOfSet.name),
getLongParameter(maxForB.name));
setNumActions(numActions);
}
//
// Make sure that the parameters are in the proper range
//
protected void checkParameters() throws Exception
{
if (getLongParameter(sizeOfSet.name) <= 0)
throw new Exception("set_size <= 0");
if (getLongParameter(maxForR.name) <= 0)
throw new Exception("max_r <= 0");
if (getLongParameter(maxForR.name) > getLongParameter(sizeOfSet.name))
throw new Exception("max_r > set_size");
if (getLongParameter(maxForB.name) <= 0)
throw new Exception("max_b <= 0");
if (getLongParameter(maxForB.name) > getLongParameter(sizeOfSet.name))
throw new Exception("max_b > set_size");
}
//
// Randomize parameters that were not set by the user
//
public void randomizeParameters() {
// Require that the user sets either all or none of
// set_size, max_r, and max_b.
if ((!parameters.setByUser(sizeOfSet.name))
&& (!parameters.setByUser(maxForR.name))
&& (!parameters.setByUser(maxForB.name))) {
parameters.randomizeParameter(sizeOfSet.name);
maxForR.high = new Long(getLongParameter(sizeOfSet.name));
maxForB.high = new Long(getLongParameter(sizeOfSet.name));
parameters.randomizeParameter(maxForR.name);
parameters.randomizeParameter(maxForB.name);
} else if ((!parameters.setByUser(sizeOfSet.name))
|| (!parameters.setByUser(maxForR.name))
|| (!parameters.setByUser(maxForB.name))) {
Global.handleError("Randomization error. User must set " +
"values for all or none of set_size, " +
"max_r, and max_b parameters.");
}
}
protected String getGameHelp()
{
return "Creates a 2 player Simple Inspection Game\n\n" +
"This game is very similar to the Greedy Game. " +
"Each action represents a chosen subset from a set of " +
"total size set_size. " +
"Player 1 can choose any subset of up to max_r elements " +
"while Player 1 can only choose subsets up to size max_b.\n\n" +
"If the intersection of the \"sets\" chosen by the players " +
"is empty then the payoff to Player 2 will be " + DEFAULT_HIGH +
" while the payoff to Player 1 will be " + DEFAULT_LOW +
" Otherwise both players will receive 0.\n\n" +
"To change the range of the payoff values, you may use " +
"normalization or integer based payoffs.\n\n" +
"Note that the number of actions available to each player " +
"is (|S| choose maxnumber) + (|S| choose maxnumber - 1) " +
"+ ... + (|S| choose 1) where maxnumber is the maximum " +
"number of items in the set that the player can choose.";
}
/**
* All geometric games must provide a function to calculate the
* payoff for each player based on the sets chosen and the
* intersection between them. In this case, if the intersection
* is not empty, the payoff to both players will be 0. If it
* is empty, the payoff to player 2 will be DEFAULT_HIGH and the
* payoff to player 1 will be DEFAULT_LOW.
*/
public double calculatePayoff(int player, BitSet R, BitSet B,
BitSet intersection) {
double payoff;
if (R.intersects(B))
payoff = 0;
else if (player == 0)
payoff = DEFAULT_LOW;
else
payoff = DEFAULT_HIGH;
return payoff;
}
/**
* Generate game, set all variables so that payoffs can
* be calculated when they are needed
*/
public void doGenerate()
{
setDescription("Simple Inspection Game \n" + getDescription());
setName("Simple Inspection Game");
initVariables(getLongParameter(sizeOfSet.name),
getLongParameter(maxForR.name),
getLongParameter(maxForB.name));
}
}
| 6,759 | 32.465347 | 252 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/SimpleOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* A very simple outputter, mostly for development purposes.
*/
public class SimpleOutput extends GameOutput
{
public void writeGame(PrintWriter out, Game g)
throws Exception
{
out.println(commentString(GAMER_STRING, "# "));
out.println(commentString(g.getDescription(), "# "));
Outcome o = new Outcome(g.getNumPlayers(), g.getNumActions());
for(o.reset(); o.hasMoreOutcomes(); o.nextOutcome())
{
out.print(o + " :\t[ ");
for(int i=0; i<g.getNumPlayers(); i++)
out.print(g.getOutputPayoff(o.getOutcome(), i) + " ");
out.println("]");
}
}
}
| 1,302 | 26.145833 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/SortedAndRandomSet.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Utility class holding a list of objects that can be returned
* either by size (largest or smallest) or randomly from the
* remaining elements in the list
*/
public class SortedAndRandomSet extends TreeSet {
public SortedAndRandomSet() {
super();
}
/**
* Removes the smallest element in the list
*/
public Object removeSmallest() {
Object smallest = first();
remove(smallest);
return (smallest);
}
/**
* Removes the largest element in the list.
*/
public Object removeLargest() {
Object largest = last();
remove(largest);
return(largest);
}
/**
* Removes a random element from the list.
*/
public Object removeRandom() {
Object randomObject = first();
int position = Global.rand.nextInt(size());
Iterator iter = iterator();
for (int i = 0; i <= position; i++)
randomObject = iter.next();
iter.remove();
return (randomObject);
}
}
| 1,659 | 22.055556 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/SpecialOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* This outputter uses game own output function
*/
public class SpecialOutput extends GameOutput
{
public void writeGame(PrintWriter out, Game g)
{
out.println(commentString(GAMER_STRING, "# "));
out.println(commentString(g.getDescription(), "# "));
out.println("# Players: " + g.getNumPlayers());
out.print("# Actions: [ ");
for(int i=0; i<g.getNumPlayers(); i++)
out.print(g.getNumActions(i) + " ");
out.println("]");
try {
g.writeGame(out);
} catch (Exception e) {
System.err.println("FATAL: Failed to write game!");
System.err.println(e.getMessage());
System.exit(1);
}
}
}
| 1,347 | 25.96 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/TimingGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Abstract class implements common features among timing games.
*
* For the extents and purposes of this class, "timing
* game" can refer to any game in which the payoff is
* computed using a function of the "earliest" (lowest
* numbered) action chosen, your own action, and whether
* your action came first, tied for first, or came later.
*/
public abstract class TimingGame extends Game
{
// --------------------------------------------------------
/**
* TimingGameParams is a simple helper class used to store
* all of the parameters for the Timing Game function for
* one particular player.
*
* This can be extended if timing games with more complicated
* payoff functions are added. If any of the parameters are
* set to 0, their corresponding terms are ignored.
*/
public static class TimingGameParams {
private double multYourTime;
private double multLowTime;
private double additional;
/**
* Constructor for TimingGameParams objects.
*
* @param yourTime amount to be multiplied by a player's individual
* time and added to a payoff
* @param lowTime amount to be multiplied by the lowest time chosen
* by any player and added to a payoff
* @param added additional amount to be added to a payoff
*/
public TimingGameParams(double yourTime, double lowTime,
double added)
{
this.multYourTime = yourTime;
this.multLowTime = lowTime;
this.additional = added;
}
/**
* Returns the multiplier for a player's own time.
*/
public double getMultYourTime() {
return multYourTime;
}
/**
* Sets the multiplier for a player's own time.
*/
public void setMultYourTime(double value) {
multYourTime = value;
}
/**
* Returns the multiplier for the lowest time of all players.
*/
public double getMultLowTime() {
return multLowTime;
}
/**
* Sets the multiplier for the lowest time of all players.
*/
public void setMultLowTime(double value) {
multLowTime = value;
}
/**
* Returns the extra amount to be added to the payoff.
*/
public double getAdditional() {
return additional;
}
/**
* Sets the extra amount to be added to the payoff.
*/
public void setAdditional(double value) {
additional = value;
}
}
// -----------------------------------------------------
private TimingGameParams lowPlayerParams[];
private TimingGameParams tiedForLowParams[];
private TimingGameParams notLowestParams[];
// allowTies should be true for games in which it is possible
// for people to make moves that end the game at the same time
// (for example, war of attrition), and false for games in which
// only one player really ends the game (like centipede)
private boolean allowsTies;
// -----------------------------------------------------
/**
* Constructor for a new timing game.
*/
public TimingGame()
throws Exception
{
super();
}
/**
* Sets the parameters for the payoff functions for the case
* when the player has the lowest time, the case when the player
* is tied, and the case when the player does not have the lowest
* time. If ties are not allowed, use setParamsNoTies instead.
*
* @param lowParams parameter settings for calculating payoff in
* the case when a player is the only one with the lowest time
* @param tiedParams parameter settings for calculating payoff in
* the case when a player is tied for the lowest time
* @param notLowestParams parameter settings for calculating payoff in
* the case when a player does not have the lowest time
*/
public void setParamsWithTie(TimingGameParams lowParams[],
TimingGameParams tiedParams[],
TimingGameParams notLowParams[])
{
int players = getNumPlayers();
lowPlayerParams = new TimingGameParams[players];
tiedForLowParams = new TimingGameParams[players];
notLowestParams = new TimingGameParams[players];
for (int i = 0; i < players; i++) {
lowPlayerParams[i] = lowParams[i];
tiedForLowParams[i] = tiedParams[i];
notLowestParams[i] = notLowParams[i];
}
allowsTies = true;
}
/**
* Set the parameters for the payoff functions for the case
* when the player has the lowest time and for when the player
*does not. Use this function if ties are not allowed.
*
* @param lowParams parameter settings for calculating payoff in
* the case when a player is the only one with the lowest time
* @param notLowestParams parameter settings for calculating payoff in
* the case when a player does not have the lowest time
*/
public void setParamsNoTies(TimingGameParams lowParams[],
TimingGameParams notLowParams[])
{
int players = getNumPlayers();
lowPlayerParams = new TimingGameParams[players];
notLowParams = new TimingGameParams[players];
tiedForLowParams = null;
for (int i = 0; i < players; i++) {
lowPlayerParams[i] = lowParams[i];
notLowestParams[i] = notLowParams[i];
}
allowsTies = false;
}
/**
* Returns the payoff for the given player in the given
* outcome using the common timing game parameterized
* function. Assumes all parameters have already been
* properly set up.
*
* @param outcome an array holding the actions of each player
* @param player the player whose payoff should be returned
*/
public double getPayoff(int[] outcome, int player) {
boolean playerLowest = true;
boolean otherChoseSame = false;
boolean lowerChoseSame = false;
int lowestTime = outcome[player];
// Determine if this player chose the lowest time,
// if others chose the same time, and what the
// lowest time was
for (int i = 0; i < getNumPlayers(); i++)
if (i != player)
if (outcome[i] < lowestTime) {
playerLowest = false;
lowestTime = outcome[i];
} else if (outcome[i] == outcome[player]) {
otherChoseSame = true;
if (i < player)
lowerChoseSame = true;
}
// Choose the correct function parameters based on
// whether or not the player chose the lowest time
TimingGameParams params;
if (playerLowest) {
if (otherChoseSame) {
if (allowsTies) {
// Player's move ended the game simultaneously
// with other players' ending moves
params = tiedForLowParams[player];
} else {
if (lowerChoseSame) {
// Player's move did not end the game
// because an "earlier" player ended on
// the same turn
params = notLowestParams[player];
} else {
// Player's move did end the game even
// though "later" players would have
// ended on the same turn
params = lowPlayerParams[player];
}
}
} else {
// Player's move did end the game
params = lowPlayerParams[player];
}
} else {
// Player's move did not end the game
params = notLowestParams[player];
}
// Calculate the payoff based on the parameters that
// have been set above, the time tha the game was ended,
// and the time that the player chose / would have
// chosen to end the game
return (params.getMultYourTime() * outcome[player] +
params.getMultLowTime() * lowestTime +
params.getAdditional());
}
}
| 7,988 | 28.156934 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/TravelersDilemma.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
/**
* Return an instance of the game Traveler's Dilemma
*/
public class TravelersDilemma extends TimingGame
{
// Parameters: Traveler's Dilemma is parameterized by the number
// of players and actions (all players must have same number
// of actions as these represent the "dollar" amounts that
// it is possible to claim), the reward units for the player who
// claims the smallest amount.
private static Parameters.ParamInfo pReward;
private static Parameters.ParamInfo[] tdParam;
static {
// When the reward is randomized, its range is reset after
// the other params are read in to be from 1 to the number of
// actions. The reward can be outside this range if it is
// set by hand.
pReward = new Parameters.ParamInfo("reward", Parameters.ParamInfo.DOUBLE_PARAM, new Double(1), new Double(100.0), "the amount of the reward for the player who claims the lowest dollar amount. Must be > 0 and <= 100.");
tdParam = new Parameters.ParamInfo[] {Game.players,
Game.symActions, pReward};
Global.registerParams(TravelersDilemma.class, tdParam);
}
// ----------------------------------------------
public TravelersDilemma()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// Both players and number of actions are extensible,
// but the number of actions must be the same for
// all players
parsePlayersSameNumberActions();
}
//
// Make sure that the parameters are in the proper range
//
protected void checkParameters() throws Exception
{
if (getDoubleParameter(pReward.name) <= 0)
throw new Exception("reward <= 0");
}
//
// Randomize any params not set by the user
//
public void randomizeParameters()
{
// Reset the range of the reward based on the number of
// actions.
int val[] = Global.parseIntArray((Vector)
getParameter(Game.actions.name));
pReward.high = new Double((double) val[0]);
parameters.randomizeParameter(pReward.name);
}
protected String getGameHelp()
{
return "Creates an instance of Traveler's Dilemma game.\n\n" +
"In order to make the game interesting, the parameters " +
"should be set up so that the reward is larger than one " +
"(but usually smaller than the number of actions)." +
" When this holds, the unique " +
"Nash equilibrium will be the unsatisfying equilibrium " +
"in which everyone chooses the smallest dollar amount.\n\n" +
"When randomization is used, the reward will automatically " +
"be chosen from somewhere in this range.";
}
public void doGenerate()
{
setDescription("Traveler's Dilemma\n" + getDescription());
setName("Traveler's Dilemma");
int players = getNumPlayers();
// Get reward amount
double reward = getDoubleParameter(pReward.name);
// Create TimingGameParams objects which will be
// necessary to hold the function parameters for each player
TimingGameParams low[] = new TimingGameParams[players];
TimingGameParams notLow[] = new TimingGameParams[players];
TimingGameParams tie[] = new TimingGameParams[players];
// All players will receive a base payoff of the lowest
// action chosen times the value of a "dollar." The
// player(s) choosing the lowest action will receive
// an additional reward of the reward amount.
for (int i = 0; i < players; i++) {
// Set up function parameters for when player chooses
// the unique lowest time and gets the reward
low[i] = new TimingGameParams(0, 1, reward);
// Function params for when player does not have
// the unique low time
tie[i] = new TimingGameParams(0, 1, 0);
notLow[i] = new TimingGameParams(0, 1, 0);
}
// Finally, set these parameters so that the payoff can be
// calculated using the timing game class
setParamsWithTie(low, tie, notLow);
}
}
| 4,635 | 30.114094 | 220 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/TwoByTwoGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.Arrays;
/**
* Return a 2x2 game of a given type from Rapoport's distribution.
*/
public class TwoByTwoGame extends MatrixGame
{
// -- Parameters: Takes as a parameter the game id number
// according to Rappoport's classification.
private static Parameters.ParamInfo pType;
private static Parameters.ParamInfo[] ttParam;
static {
pType = new Parameters.ParamInfo("type", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(85), "type of the 2x2 game in Rappoport's classification, in [1,85]");
ttParam = new Parameters.ParamInfo[] {pType};
Global.registerParams(TwoByTwoGame.class, ttParam);
}
// ----------------------------------------------
/**
* Construct a new game
*/
public TwoByTwoGame()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
setNumPlayers(2);
setNumActions(new int[] {2,2});
initMatrix();
}
/**
* Checks that parameters are ok
*/
protected void checkParameters() throws Exception
{
if ((getLongParameter(pType.name) < 1) ||
(getLongParameter(pType.name) > 85))
throw new Exception("parameter type out of range");
}
/**
* Randomizes type
*/
public void randomizeParameters()
{
parameters.randomizeParameter(parameters.getParamIndex(pType.name));
}
/**
* Returns the help screen
*/
protected String getGameHelp()
{
return "Creates a game of two actions and two players " +
"of a given type according to Rappoport's classification." +
getRangeHelp();
}
/**
* Fills in the payoffs
*/
public void doGenerate()
{
double low = DEFAULT_LOW;
double high = DEFAULT_HIGH;
int type = (int)getLongParameter(pType.name);
setDescription("A Two By Two Game of type " + type + "\n"
+ getDescription());
setName("Two by Two Game of type " + type);
// -- make random payoff vectors
double[][] payoffs = new double[2][5];
for(int i=0; i<2; i++)
{
for(int j=1; j<=4; j++)
payoffs[i][j]=Global.randomDouble(low, high);
Arrays.sort(payoffs[i]);
}
Outcome outcome=new Outcome(getNumPlayers(), getNumActions());
for(outcome.reset(); outcome.hasMoreOutcomes(); outcome.nextOutcome())
{
for(int i=0; i<getNumPlayers(); i++)
{
int[] actions=outcome.getOutcome();
int row=actions[0] - 1;
int col=actions[1] - 1;
int ord=allGames[type-1][i][row][col];
setPayoff(outcome.getOutcome(), i,
payoffs[i][ord]);
}
}
}
/**
* All of Rappoport's games in one table!
* indices are: game, player, row, col
* entries: order of the payoff
*/
private static final int[][][][] allGames =
{
{ { {4, 3}, {2, 1} }, { {4, 3}, {2, 1} } },
{ { {4, 3}, {1, 2} }, { {4, 3}, {2, 1} } },
{ { {4, 3}, {2, 1} }, { {4, 2}, {3, 1} } },
{ { {4, 3}, {1, 2} }, { {4, 2}, {3, 1} } },
{ { {4, 3}, {1, 2} }, { {4, 1}, {3, 2} } },
{ { {4, 2}, {3, 1} }, { {4, 3}, {2, 1} } },
{ { {3, 4}, {2, 1} }, { {3, 2}, {4, 1} } },
{ { {3, 4}, {1, 2} }, { {3, 2}, {4, 1} } },
{ { {3, 4}, {1, 2} }, { {3, 1}, {4, 2} } },
{ { {2, 4}, {1, 3} }, { {3, 2}, {4, 1} } },
{ { {2, 4}, {1, 3} }, { {3, 1}, {4, 2} } },
{ { {2, 4}, {1, 3} }, { {2, 1}, {4, 3} } },
{ { {3, 4}, {2, 1} }, { {4, 2}, {3, 1} } },
{ { {3, 4}, {1, 2} }, { {4, 2}, {3, 1} } },
{ { {3, 4}, {2, 1} }, { {4, 1}, {3, 2} } },
{ { {3, 4}, {1, 2} }, { {4, 1}, {3, 2} } },
{ { {2, 4}, {1, 3} }, { {4, 2}, {3, 1} } },
{ { {2, 4}, {1, 3} }, { {4, 1}, {3, 2} } },
{ { {3, 4}, {1, 2} }, { {4, 3}, {2, 1} } },
{ { {3, 4}, {2, 1} }, { {4, 3}, {2, 1} } },
{ { {2, 4}, {1, 3} }, { {4, 3}, {2, 1} } },
{ { {4, 3}, {2, 1} }, { {4, 3}, {1, 2} } },
{ { {4, 3}, {1, 2} }, { {4, 3}, {1, 2} } },
{ { {4, 3}, {2, 1} }, { {4, 2}, {1, 3} } },
{ { {4, 3}, {1, 2} }, { {4, 2}, {1, 3} } },
{ { {4, 2}, {3, 1} }, { {4, 3}, {1, 2} } },
{ { {4, 2}, {3, 1} }, { {4, 2}, {1, 3} } },
{ { {4, 3}, {2, 1} }, { {4, 1}, {2, 3} } },
{ { {4, 3}, {1, 2} }, { {4, 1}, {2, 3} } },
{ { {4, 2}, {3, 1} }, { {4, 1}, {2, 3} } },
{ { {3, 2}, {1, 4} }, { {4, 2}, {3, 1} } },
{ { {3, 2}, {1, 4} }, { {4, 1}, {3, 2} } },
{ { {3, 1}, {2, 4} }, { {4, 2}, {3, 1} } },
{ { {3, 1}, {2, 4} }, { {4, 1}, {3, 2} } },
{ { {2, 3}, {1, 4} }, { {4, 2}, {3, 1} } },
{ { {2, 3}, {1, 4} }, { {4, 1}, {3, 2} } },
{ { {3, 2}, {1, 4} }, { {4, 3}, {2, 1} } },
{ { {3, 1}, {2, 4} }, { {4, 3}, {2, 1} } },
{ { {2, 3}, {1, 4} }, { {4, 3}, {2, 1} } },
{ { {3, 4}, {2, 1} }, { {4, 1}, {2, 3} } },
{ { {3, 4}, {1, 2} }, { {4, 1}, {2, 3} } },
{ { {3, 4}, {2, 1} }, { {3, 1}, {2, 4} } },
{ { {3, 4}, {1, 2} }, { {3, 1}, {2, 4} } },
{ { {2, 4}, {1, 3} }, { {4, 1}, {2, 3} } },
{ { {3, 4}, {2, 1} }, { {2, 1}, {3, 4} } },
{ { {3, 4}, {1, 2} }, { {2, 1}, {3, 4} } },
{ { {2, 4}, {1, 3} }, { {3, 1}, {2, 4} } },
{ { {2, 4}, {1, 3} }, { {2, 1}, {3, 4} } },
{ { {3, 4}, {2, 1} }, { {4, 3}, {1, 2} } },
{ { {3, 4}, {1, 2} }, { {4, 3}, {1, 2} } },
{ { {3, 4}, {2, 1} }, { {4, 2}, {1, 3} } },
{ { {3, 4}, {1, 2} }, { {4, 2}, {1, 3} } },
{ { {3, 4}, {2, 1} }, { {3, 2}, {1, 4} } },
{ { {3, 4}, {1, 2} }, { {3, 2}, {1, 4} } },
{ { {2, 4}, {1, 3} }, { {4, 3}, {1, 2} } },
{ { {2, 4}, {1, 3} }, { {4, 2}, {1, 3} } },
{ { {2, 4}, {1, 3} }, { {3, 2}, {1, 4} } },
{ { {4, 2}, {1, 3} }, { {4, 3}, {1, 2} } },
{ { {4, 2}, {1, 3} }, { {4, 2}, {1, 3} } },
{ { {4, 2}, {1, 3} }, { {4, 1}, {2, 3} } },
{ { {4, 1}, {3, 2} }, { {4, 3}, {1, 2} } },
{ { {4, 1}, {3, 2} }, { {4, 2}, {1, 3} } },
{ { {4, 1}, {2, 3} }, { {4, 2}, {1, 3} } },
{ { {3, 2}, {1, 4} }, { {4, 1}, {2, 3} } },
{ { {2, 3}, {1, 4} }, { {4, 1}, {2, 3} } },
{ { {3, 2}, {4, 1} }, { {3, 4}, {2, 1} } },
{ { {2, 3}, {4, 1} }, { {3, 4}, {2, 1} } },
{ { {2, 3}, {4, 1} }, { {2, 4}, {3, 1} } },
{ { {2, 4}, {3, 1} }, { {2, 3}, {4, 1} } },
{ { {3, 2}, {4, 1} }, { {4, 1}, {2, 3} } },
{ { {3, 2}, {4, 1} }, { {3, 1}, {2, 4} } },
{ { {3, 2}, {4, 1} }, { {2, 1}, {3, 4} } },
{ { {2, 4}, {3, 1} }, { {4, 1}, {2, 3} } },
{ { {2, 3}, {4, 1} }, { {4, 1}, {2, 3} } },
{ { {2, 4}, {3, 1} }, { {3, 1}, {2, 4} } },
{ { {2, 3}, {4, 1} }, { {3, 1}, {2, 4} } },
{ { {2, 4}, {3, 1} }, { {2, 1}, {3, 4} } },
{ { {2, 3}, {4, 1} }, { {2, 1}, {3, 4} } },
{ { {2, 1}, {2, 1} }, { {2, 2}, {1, 1} } },
{ { {1, 1}, {1, 1} }, { {4, 3}, {2, 1} } },
{ { {2, 3}, {2, 1} }, { {2, 1}, {2, 3} } },
{ { {3, 4}, {2, 1} }, { {4, 1}, {2, 2} } },
{ { {3, 1}, {1, 2} }, { {3, 1}, {1, 2} } },
{ { {3, 2}, {1, 3} }, { {1, 2}, {3, 1} } },
{ { {2, 1}, {1, 2} }, { {2, 1}, {1, 2} } }
};
}
| 7,314 | 30.12766 | 167 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/TwoPlayerOutput.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.io.*;
/**
* A very simple outputter, for two player games
*/
public class TwoPlayerOutput extends GameOutput
{
public void writeGame(PrintWriter out, Game g)
throws Exception
{
if(g.getNumPlayers()!=2)
throw new Exception("Unsupported Game Type for Output!");
out.println("// " + GAMER_STRING + "\n");
out.println(commentString(g.getDescription(), "// "));
int n=g.getNumActions(0);
int m=g.getNumActions(1);
int[] o=new int[2];
for(int i=1; i<=n; i++)
{
o[0]=i;
for(int j=1; j<=m; j++)
{
o[1]=j;
out.print("(" + g.getOutputPayoff(o,0) + ", " +
g.getOutputPayoff(o,1) + ")");
if(j!=m)
out.print("\t");
}
out.println("");
}
}
}
| 1,419 | 23.482759 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/UniformLEG.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
import java.util.*;
import edu.stanford.multiagent.gamer.graphs.*;
import edu.stanford.multiagent.gamer.functions.*;
/**
* Generate a Local Effect Game with a given graphical
* structure and a given function structure such that
* every edge from b to a has the same local effect as
* an edge from c to a. (This is opposite notation from
* the LEG literature.)
*
* Very similar to RandomLEG except for the generation
* function.
*/
public class UniformLEG extends RandomLEG
{
// --------------------------------------------------
// Parameters: Parameters carry over from RandomLEG
// and from the graph and function being used. No new
// parameters are introduced here.
//
static {
Global.registerParams(UniformLEG.class, rlegParam);
}
// -------------------------------------------------------
public UniformLEG()
throws Exception
{
super();
}
protected String getGameHelp()
{
return "Creates a Uniform Local-Effect Game using the " +
"specified graph class and specified function class.\n\n" +
"A Uniform Local-Effect Game is a LEG with a graphical " +
"structure in which every edge from b to a has the same " +
"local-effect function as the edge from c to a. (This " +
"notation is slightly different from what is used in the " +
"local-effect literature, but is equivalent.)\n\n" +
"Please note " +
"that you should be careful when you choose the graph " +
"class and set the graph parameters here. The graph " +
"chosen should be symmetric (i.e. whenever there is an " +
"edge from a to b there is also an edge from b to a) and " +
"should not have reflexive edges. (Each node will have a " +
"local effect on itself, but this is handled outside of the " +
"graph.) Set the parameters for the graph accordingly!";
}
/**
* Generates the graph and for each node and edge of the graph,
* a function, making sure that functions are the same on every
* edge from b to a as they are on the edge from c to a.
*/
public void doGenerate()
{
setDescription("Uniform Local-Effect Game\n" +
getDescription());
setName("Uniform Local-Effect Game");
// Generate the graph for the game.
graph.doGenerate();
setDescription(getDescription() + "\nGraph Params:\n" + graph.getDescription());
// First loop through all of the nodes creating their
// node functions and an array containing their
// effect functions for other nodes
int numNodes = graph.getNNodes();
Function effectFunctions[] = new Function[numNodes];
String funcName = parameters.getStringParameter("func");
ParamParser funcParams = parameters.getParserParameter("func_params");
for (int i = 0; i < numNodes; i++) {
Function fNode = (Function) Global.getObjectOrDie(funcName,
Global.FUNC);
try {
fNode.setDomain(0, getNumPlayers());
fNode.setParameters(funcParams, randomize);
fNode.initialize();
fNode.doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(fNode.getHelp());
Global.handleError(e, "Error initializing function");
}
graph.setNodeData(i, fNode);
effectFunctions[i] = (Function) Global.getObjectOrDie
(funcName, Global.FUNC);
try {
effectFunctions[i].setDomain(0, getNumPlayers());
effectFunctions[i].setParameters(funcParams, randomize);
effectFunctions[i].initialize();
effectFunctions[i].doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(effectFunctions[i].getHelp());
Global.handleError(e, "Error initializing function");
}
}
// Now loop through the edges of the graph and add the
// appropriate function to each
for (int i = 0; i < graph.getNNodes(); i++) {
Iterator edgeIter = graph.getEdges(i);
while (edgeIter.hasNext()) {
Edge edge = (Edge) edgeIter.next();
Function fEdge = effectFunctions[edge.getDest()];
edge.setData(fEdge);
}
}
}
}
| 4,758 | 30.726667 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/WarOfAttrition.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Return an instance of the game War of Attrition
*/
public class WarOfAttrition extends TimingGame
{
// Parameters: War Of Attrition is parameterized first by the number
// of actions (in other words, the maximum number of time steps),
// and finally by low and high boundaries on the valuations for
// each player for the item, and low and high boundaries on how
// much the the utility of each player will decrease at each time
// step (each player has a different decrement value).
private static Parameters.ParamInfo valLow;
private static Parameters.ParamInfo valHigh;
private static Parameters.ParamInfo decrementLow;
private static Parameters.ParamInfo decrementHigh;
private static Parameters.ParamInfo[] warParam;
static {
// The valLow, valHigh, decrementLow, and decrementHigh
// randomization params were chosen somewhat arbitrarily. The
// user can hand set these parameters to be out of the randomization
// range, though it is recommended that the valuation stays
// significantly higher than the decrement. If the user sets either
// the decrements or the values but not both then the range for the
// other will be updated automatically.
valLow = new Parameters.ParamInfo("valuation_low", Parameters.ParamInfo.DOUBLE_PARAM, new Double(10), new Double(1000), "lower bound on the players' valuations for the item, should be between 10 and 1000.");
valHigh = new Parameters.ParamInfo("valuation_high", Parameters.ParamInfo.DOUBLE_PARAM, new Double(10), new Double(1000), "upper bound on the players' valuations for the item. Must be >= valuation_low.");
decrementLow = new Parameters.ParamInfo("decrement_low", Parameters.ParamInfo.DOUBLE_PARAM, new Double(1), new Double(100), "lower bound on the amount that the worth of the object to a player is decremented by at each time step. Note that each player has a different decrement value. Should be <= valuation_low, and between 1 and 100.");
decrementHigh = new Parameters.ParamInfo("decrement_high", Parameters.ParamInfo.DOUBLE_PARAM, new Double(1), new Double(100), "upper bound on the amount that the worth of the object to a player is decremented by at each time step. Must be >= decrement_low.");
warParam = new Parameters.ParamInfo[] {Game.symActions,
valLow, valHigh,
decrementLow, decrementHigh};
Global.registerParams(WarOfAttrition.class, warParam);
}
// ----------------------------------------------
public WarOfAttrition()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
// The number of players must always be two, but the number
// of actions is extensible
setNumPlayers(2);
parseSameNumberActions();
}
/**
* Make sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if(getDoubleParameter(decrementLow.name) <= 0)
throw new Exception("decrement_low <= 0");
if(getDoubleParameter(valLow.name) <= 0)
throw new Exception("valuation_low <= 0");
if(getDoubleParameter(valLow.name)
> getDoubleParameter(valHigh.name))
throw new Exception("valuation_low > valuation_high");
if(getDoubleParameter(decrementLow.name)
> getDoubleParameter(decrementHigh.name))
throw new Exception("decrement_low > decrement_high");
if(getDoubleParameter(decrementHigh.name)
> getDoubleParameter(valLow.name))
throw new Exception("decrement_high > valuation_low");
}
/**
* Randomize the parameters which were not filled in by
* the user. Since it would be extremely complicated to
* allow random combinations of 4 variables which need to be
* fully ordered to be set, we force that both decrements are
* either set or not set, and same for both valuations.
*/
public void randomizeParameters()
{
// Check that either both or neither decrement values are set.
if (parameters.setByUser(decrementLow.name) !=
parameters.setByUser(decrementHigh.name)) {
Global.handleError("Randomization Error: Please set either " +
"both or neither of parameters " +
"decrement_low and decrement_high");
}
// Check that either both or neither valuation values are set.
if (parameters.setByUser(valLow.name) !=
parameters.setByUser(valHigh.name)) {
Global.handleError("Randomization Error: Please set either " +
"both or neither of parameters " +
"valuation_low and valuation_high");
}
// Set the decrements
if (!(parameters.setByUser(decrementHigh.name))) {
if (parameters.setByUser(valLow.name)) {
if (getDoubleParameter(valLow.name) < 1.0) {
Global.handleError("Randomization Error: Parameter " +
"valuation_low should be >= 1.0 " +
"to leave room for decrement_low " +
"and decrement_high randomization.");
}
decrementLow.high = new
Double(getDoubleParameter(valLow.name));
decrementHigh.high = new
Double(getDoubleParameter(valLow.name));
}
parameters.randomizeParameter(decrementLow.name);
decrementHigh.low =
new Double(getDoubleParameter(decrementLow.name));
parameters.randomizeParameter(decrementHigh.name);
}
// Set the valuations
if (!(parameters.setByUser(valHigh.name))) {
valLow.low = new
Double(getDoubleParameter(decrementHigh.name));
valHigh.low = new
Double(getDoubleParameter(decrementHigh.name));
parameters.randomizeParameter(valLow.name);
valHigh.low =
new Double(getDoubleParameter(valLow.name));
parameters.randomizeParameter(valHigh.name);
}
}
protected String getGameHelp()
{
return "Creates an instance of the War of Attrition. In a " +
"War of Attrition, two players are in a dispute over an " +
"object, and each chooses a time to concede the object to " +
"the other player. If both concede at the same time, they " +
"share the object. Each player has a valuation of " +
"the object, and each player's utility is decremented at " +
"every time step.\n\n" +
"Payoffs are based on the ranges of valuations and decrements " +
"provided. Although normalization may have the effect that " +
"the ranges of the payoffs will change, the ratio of the " +
"valuation amount to the decrement amount will still come " +
"into play.";
}
public void doGenerate()
{
// -- get Parameter values
double lowVal = getDoubleParameter(valLow.name);
double highVal = getDoubleParameter(valHigh.name);
double lowDec = getDoubleParameter(decrementLow.name);
double highDec = getDoubleParameter(decrementHigh.name);
setDescription("War of Attrition\n" + getDescription());
setName("War of Attrition");
int players = getNumPlayers();
// Generate valuations for the object in the range from
// lowVal to highVal for each player
double valuations[] = new double[players];
for (int i = 0; i < players; i++) {
valuations[i] = Global.randomDouble(lowVal, highVal);
}
// Generate time step decrement amounts for each player
// in the range from lowDec to highDec
double decrement[] = new double[players];
for (int i = 0; i < players; i++) {
decrement[i] = Global.randomDouble(lowDec, highDec);
}
// Create TimingGameParams objects which will be
// necessary to hold the function parameters for each player
TimingGameParams low[] = new TimingGameParams[players];
TimingGameParams notLow[] = new TimingGameParams[players];
TimingGameParams tie[] = new TimingGameParams[players];
for (int i = 0; i < players; i++) {
// Set up function parameters for when player chooses
// lowest time
low[i] = new TimingGameParams(0, -decrement[i], decrement[i]);
// Function params for when player ties for low time
tie[i] = new TimingGameParams(0, -decrement[i],
valuations[i]/2 + decrement[i]);
// Function params for when player does not have low time
notLow[i] = new TimingGameParams(0, -decrement[i],
valuations[i] + decrement[i]);
// note: In each of these, the additional add-on of
// decrement[i] is there to balance out the fact that the
// first time step should not be subtracting anything
}
// Finally, set these parameters so that the payoff can be
// calculated using the timing game class
setParamsWithTie(low, tie, notLow);
}
}
| 9,174 | 35.122047 | 340 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/ZeroSumGame.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer;
/**
* Abstract class used for representing a two-player zero-sum
* game. Implemented in a similar manner to MatrixGame
* except only one payoff matrix needs to be stored.
*/
public abstract class ZeroSumGame extends Game
{
// Payoffs holds the payoff matrix for player 1,
// the payoffs for player 2 are found by negating these.
double[][] payoffs;
// --------------------------------------------------
/**
* Constructor for two-player zero-sum games.
*/
public ZeroSumGame()
throws Exception
{
super();
}
/**
* Create the matrix of payoffs.
*
* @param a1 the number of actions player 1 has
* @param a2 the number of actions player 2 has
*/
public void initPayoffs(int a1, int a2) {
payoffs = new double[a1][a2];
}
/**
* Return the payoff for the specified player at the
* specified outcome.
*
* @param outcome an array holding the outcome choices for
* each player
* @param player the player whose action should be returned
*/
public double getPayoff(int[] outcome, int player) {
if (player == 0)
return payoffs[outcome[0] - 1][outcome[1] - 1];
return (-payoffs[outcome[0] - 1][outcome[1] - 1]);
}
/**
* Set the payoff for the first player at the given outcome.
* The payoff for player 2 at this outcome will be the negation
* of this.
*
* @param outcome an array holding the outcome choices for
* each player
* @param payoff the amount of the payoff
*/
public void setPayoff(int[] outcome, double payoff) {
payoffs[outcome[0] - 1][outcome[1] - 1] = payoff;
}
}
| 2,371 | 25.651685 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/ConcaveTableFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Class implements a table lookup concave function (for truly
* random table functions)
*/
public class ConcaveTableFunction extends IncreasingTableFunction
{
// -- Parameters
static {
Global.registerParams(ConcaveTableFunction.class, tfParam);
}
// --------------------------------------------------
protected String getFunctionHelp()
{
return "ConcaveTableFunction: Represents a general concave function as a table of points. Function is evaluated by looking up nearest point to the x value. No interpolation is done.";
}
public ConcaveTableFunction()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
}
/**
* Generate the table
*/
public void doGenerate()
{
int nPoints=(int)getLongParameter(pPoints.name);
double min = getDoubleParameter(pMin.name);
double max = getDoubleParameter(pMax.name);
// -- generate derivative
table = new double[nPoints];
double maxDeriv = max-min;
table[0] = -maxDeriv;
table[nPoints-1] = maxDeriv;
// recGenerate(0, nPoints-1, table[0], table[nPoints-1]);
recGenerate(0, nPoints-1, -maxDeriv, maxDeriv);
double[] deriv=table;
intAndNorm(deriv);
}
/**
* Just used for testing
*/
public static void main(String[] args)
throws Exception
{
Global.rand=new Random( System.currentTimeMillis() );
ConcaveTableFunction p = new ConcaveTableFunction();
p.setParameters(new ParamParser(args), false);
p.initialize();
p.doGenerate();
for(int i=0; i<p.table.length; i++)
System.out.println(p.table[i]);
System.out.println("\n--------------------------");
System.out.println(p.eval(0));
System.out.println(p.eval(1));
System.out.println(p.eval(0.5));
System.out.println(p.eval(0.7));
}
}
| 2,651 | 22.891892 | 184 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/DecreasingWrapper.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import edu.stanford.multiagent.gamer.*;
/**
* A Wrapper that takes an arbitrary increasing function,
* and turns it into a decreasing one (by negating)
*/
public class DecreasingWrapper extends Function
{
// Parameters: The name of the function to wrap
private static Parameters.ParamInfo pBase;
private static Parameters.ParamInfo pMin;
private static Parameters.ParamInfo pFuncParams;
private static Parameters.ParamInfo[] dcrParams;
static {
pBase = new Parameters.ParamInfo("base_func", Parameters.ParamInfo.STRING_PARAM, null, null, "name of the function to wrap. must be increasing.");
pMin = new Parameters.ParamInfo("min", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "the minimum of the function", false, new Double(0));
pFuncParams = new Parameters.ParamInfo("base_params", Parameters.ParamInfo.CMDLINE_PARAM, null, null, "parameters to be handed off to the base function, must be enclosed in [].", false, ParamParser.emptyParser);
dcrParams = new Parameters.ParamInfo[] {pBase, pMin, pFuncParams};
Global.registerParams(DecreasingWrapper.class, dcrParams);
}
// --------------------------------------------------
boolean randomize=false;
public DecreasingWrapper()
throws Exception
{
super();
}
protected String getFunctionHelp()
{
return "DecreasingWrapper: Takes an increasing base function, and makes it descreasing by negating and shifting up.";
}
public void initialize()
throws Exception
{
super.initialize();
}
public void setParameters(ParamParser p, boolean randomize)
throws Exception
{
super.setParameters(p, randomize);
this.randomize=randomize;
}
/**
* Randomize things
*/
public void randomizeParameters()
{
// -- First, base function
try {
if(!parameters.setByUser(pBase.name))
parameters.setParameter(pBase.name, Global.getRandomClass(Global.FUNC, "IncreasingFunction"));
} catch (Exception e) {
Global.handleError(e, "Randomizing Decreasing Wrapper");
}
parameters.randomizeParameter(pMin.name);
}
protected void checkParameters()
throws Exception
{
if(dMax <= dMin)
throw new Exception("Bad Range!");
String fName = getStringParameter(pBase.name);
if(!Global.isPartOf(Global.FUNC, fName, "IncreasingFunction"))
throw new Exception("Base function must be increasing!");
}
// -- Things used to compute value
Function fBase;
double add;
/**
* Computes the additive constant to satisfy the min parameter.
*/
public void doGenerate()
{
fBase = (Function)Global.getObjectOrDie(getStringParameter(pBase.name), Global.FUNC);
try {
fBase.setDomain(getDMin(), getDMax());
fBase.setParameters(parameters.getParserParameter(pFuncParams.name),randomize);
fBase.initialize();
fBase.doGenerate();
} catch (Exception e) {
System.err.println(getHelp());
System.err.println(fBase.getHelp());
Global.handleError(e, "Base Function Parameters");
}
double min=getDoubleParameter(pMin.name);
double act=-fBase.eval(dMax); // -f is smallest at dMax
add = min - act;
}
public double eval(double x)
{
return - fBase.eval(x) + add;
}
public String getDescription()
{
StringBuffer buff=new StringBuffer();
buff.append("DecreasingWrapper(");
buff.append(getParamDescription(", "));
buff.append(")\nWrapped::");
buff.append(fBase.getDescription());
buff.append("\t");
return buff.toString();
}
}
| 4,263 | 27.426667 | 212 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/ExpFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Implements an exponential function with given multiplicative
* and additive terms.
*
*/
public class ExpFunction extends Function
{
// Parameters: the exponential function takes a multiplicative
// and an additive term as parameters.
private static Parameters.ParamInfo pAlpha, pBeta;
private static Parameters.ParamInfo[] expParams;
static {
// Parameter ranges are very arbitrary..
pAlpha = new Parameters.ParamInfo("alpha", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(1), "multiplicative constant. Should be in the range 0 to 1. Defaults to 1.", false, new Double(1));
pBeta = new Parameters.ParamInfo("beta", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "additive term. Defaults to 0.", false, new Double(0));
expParams = new Parameters.ParamInfo[] {pAlpha, pBeta};
Global.registerParams(ExpFunction.class, expParams);
}
// --------------------------------------------------
protected String getFunctionHelp()
{
return "ExpFunction: A function of the form f(x) = exp(alpha * x) + beta";
}
public ExpFunction()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
}
protected void checkParameters()
throws Exception
{
if(dMax <= dMin)
throw new Exception("Bad Range!");
}
/**
* There is no generation whatsoever involved for
* the exponential function.
*/
public void doGenerate()
{
}
public double eval(double x)
{
double alpha = (double) getDoubleParameter(pAlpha.name);
double beta = (double) getDoubleParameter(pBeta.name);
double exp = Math.exp(alpha * x) + beta;
return exp;
}
}
| 2,537 | 23.882353 | 207 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/Function.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import edu.stanford.multiagent.gamer.*;
/**
* An abstract class for single-arity function classes
*/
public abstract class Function extends ParameterizedObject
{
public Function()
throws Exception
{
super();
}
/**
* Return the help screen
*/
public String getHelp()
{
StringBuffer buff=new StringBuffer();
buff.append(Global.wrap(getFunctionHelp(), 70));
buff.append("\n\nFunction Parameters:\n");
buff.append(Global.wrap(parameters.getPrintableInfo(), 70));
return buff.toString();
}
/**
* Returns a help string describing the function and the
* parameters taken by the function
*/
protected abstract String getFunctionHelp();
/**
* Evaluates the function at a single point and return
* the value
*
* @param x the point at which to evaluate the function
*/
public abstract double eval(double x);
/**
* Calls initialize in the super class ParemeterizedObject which
* checks parameters
*
* @throws Exception if there is a problem with the parameters
*/
public void initialize()
throws Exception
{
super.initialize();
}
//-- Domain interval
protected double dMin=0, dMax=1; // -- domain interval
/**
* Sets the domain range. This range must be set before
* randomization happens.
*
* @param min minimum value in the domain
* @param max maximum value in the domain
*/
public void setDomain(double min, double max)
{
dMin=min;
dMax=max;
}
/**
* Returns the minimum value in the domain.
*/
public double getDMin()
{
return dMin;
}
/**
* Returns the maximum value in the domain.
*/
public double getDMax()
{
return dMax;
}
}
| 2,535 | 21.846847 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/IncreasingPoly.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Class implements an increasing polynomial function of a single argument
*/
public class IncreasingPoly extends PolyFunction
{
static {
Global.registerParams(IncreasingPoly.class, PolyFunction.pfParam);
}
protected String getFunctionHelp()
{
return "IncreasingPoly: Represents an increasing polynomial. Coefficients and degree can either be specified explicitely, or randomized to lie within given ranges.";
}
public IncreasingPoly()
throws Exception
{
super();
}
public IncreasingPoly(double[] coefs, double dMin, double dMax)
throws Exception
{
this.coefs=coefs;
this.dMin=dMin;
this.dMax=dMax;
}
public void initialize()
throws Exception
{
super.initialize();
}
protected void checkParameters()
throws Exception
{
super.checkParameters();
if(parameters.setByUser("coefs"))
{
PolyFunction deriv=getDerivative();
double min=deriv.getMinimum();
if(min<0)
throw new Exception("This polynomial doesn't seem to be increasing on its domain!");
}
}
/**
* Randomize things
*
* This is not the most efficient algorithm. It works, but
* something more robust can replace it later.
*/
public void randomizeParameters()
{
try {
// -- First, degree
if(!parameters.setByUser("degree"))
parameters.randomizeParameter("degree");
// -- Then, coefficients
double coefMin = getDoubleParameter("coef_min");
double coefMax = getDoubleParameter("coef_max");
int degree = (int)getLongParameter("degree");
if(!parameters.setByUser("coefs"))
{
if(degree==0)
{
// -- Nothing to do, it's flat
Vector v=new Vector();
double c=Global.randomDouble(coefMin, coefMax);
v.add(String.valueOf(c));
setParameter("coefs", v);
return;
}
// -- else need a random derivative
PolyFunction deriv=new PolyFunction();
deriv.setDomain(dMin, dMax);
deriv.setParameters(this.parameters, false);
deriv.setParameter("degree", new Long(degree-1), true);
deriv.randomizeParameters();
deriv.initialize();
deriv.doGenerate();
double min=deriv.getMinimum();
if(min<=0)
{
deriv.coefs[0]-=min;
deriv.coefs[0]+=Global.randomDouble(0,coefMax);
}
PolyFunction integral=deriv.integrate();
setParameter("coefs", integral.getParameter("coefs"));
this.coefs=integral.coefs;
this.dMin=integral.dMin;
this.dMax=integral.dMax;
}
} catch (Exception e) {
Global.handleError(e, "Random Increasing Poly");
}
}
/**
* Used only for testing
*/
public static void main(String[] args)
throws Exception
{
Global.rand=new Random( System.currentTimeMillis() );
PolyFunction p = new IncreasingPoly();
p.setDomain(1,3);
p.setParameters(new ParamParser(args), true);
p.initialize();
p.doGenerate();
for(int i=p.coefs.length-1; i>=0; i--)
System.out.print(p.coefs[i] + " ");
System.out.println("");
}
}
| 3,847 | 22.321212 | 166 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/IncreasingTableFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
*Class implements a table lookup incr. function (for truly random table functions)
*
*/
public class IncreasingTableFunction extends TableFunction
{
// -- Parameters
static {
Global.registerParams(IncreasingTableFunction.class, tfParam);
}
// --------------------------------------------------
protected String getFunctionHelp()
{
return "IncreasingTableFunction: Represents a general increasing function as a table of points. Function is evaluated by looking up nearest point to the x value. No interpolation is done.";
}
public IncreasingTableFunction()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
}
// -- Convert a derivative into a function
protected void intAndNorm(double[] deriv)
{
double min = getDoubleParameter(pMin.name);
double max = getDoubleParameter(pMax.name);
int nPoints=(int)getLongParameter(pPoints.name);
// -- Generate unnormalized points
table = new double[nPoints];
table[0] = 0;
double tMin=0, tMax=0;
for(int i=1; i<table.length; i++)
{
table[i] = table[i-1] + deriv[nPoints - i];
if(table[i] < tMin)
tMin = table[i];
if(table[i] > tMax)
tMax = table[i];
}
// System.err.println(pMin.name);
//System.err.println(min + ", " + max + "\t" + tMin + ", " + tMax);
// -- Stretch to match max and min
double f=(max-min) / (tMax-tMin);
for(int i=0; i<table.length; i++)
table[i] = (table[i]-tMin) * f + min;
}
// -- Recusively generate increasing function
protected void recGenerate(int minIdx, int maxIdx, double min, double max)
{
// -- assume boundary elements are set
// -- base case
if(maxIdx - minIdx <=1)
return; //-- nothing to do
// -- otherwise
int idx = Global.randomInt(minIdx+1, maxIdx-1);
table[idx] = Global.randomDouble(min, max);
// -- left
recGenerate(minIdx, idx, min, table[idx]);
// --right
recGenerate(idx, maxIdx, table[idx], max);
}
// -- generate the table
public void doGenerate()
{
int nPoints=(int)getLongParameter(pPoints.name);
double min = getDoubleParameter(pMin.name);
double max = getDoubleParameter(pMax.name);
table = new double[nPoints];
table[0] = min;
table[nPoints-1] = max;
recGenerate(0,nPoints-1,min,max);
}
// == Just for testing
public static void main(String[] args)
throws Exception
{
Global.rand=new Random( System.currentTimeMillis() );
IncreasingTableFunction p = new IncreasingTableFunction();
p.setParameters(new ParamParser(args), false);
p.initialize();
p.doGenerate();
for(int i=0; i<p.table.length; i++)
System.out.println(p.table[i]);
System.out.println("\n--------------------------");
System.out.println(p.eval(0));
System.out.println(p.eval(1));
System.out.println(p.eval(0.5));
System.out.println(p.eval(0.7));
}
}
| 3,731 | 24.387755 | 193 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/LogFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Class implements a log function.
*/
public class LogFunction extends Function
{
// Parameters: The log function takes as parameters a multiplicative
// and an additive term.
private static Parameters.ParamInfo pAlpha, pBeta;
private static Parameters.ParamInfo[] logParams;
static {
// Ranges on these are extremely arbitrary..
pAlpha = new Parameters.ParamInfo("alpha", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(10), "multiplicative constant");
pBeta = new Parameters.ParamInfo("beta", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "additive term");
logParams = new Parameters.ParamInfo[] {pAlpha, pBeta};
Global.registerParams(LogFunction.class, logParams);
}
// --------------------------------------------------
protected String getFunctionHelp()
{
return "LogFunction: A function of the form f(x) = alpha * ln(x + k) + beta. k is calculated automatically as 1-dMin, where dMin is the lower bound on the domain.";
}
private double shift=0;
public LogFunction()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
}
protected void checkParameters()
throws Exception
{
if( dMax < dMin )
throw new Exception("Bad Range!: " + "[" + dMax + ", " + dMin + "]");
//if (dMin <= 0)
// System.err.println("WARNING: Log Domain non positive, shifting arguments by " + (1-dMin));
}
/**
* Shifts the function if the domain min is less than or
* equal to 0.
*/
public void doGenerate()
{
if(getDMin()<=0)
shift = 1-getDMin();
}
public double eval(double x)
{
double alpha = (double) getDoubleParameter(pAlpha.name);
double beta = (double) getDoubleParameter(pBeta.name);
double log = alpha * Math.log(x + shift) + beta;
return log;
}
}
| 2,682 | 24.311321 | 165 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/PolyFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Class implements a polynomial function of a single argument
*/
public class PolyFunction extends Function
{
// -- Constants for minimization
protected static final double EPSILON = 0.00001;
protected static final int MAX_ITER = 100000;
protected static final int N_RESTARTS = 50;
// -- Parameters
private static Parameters.ParamInfo pDegree;
private static Parameters.ParamInfo pCoefs;
private static Parameters.ParamInfo pCoefMin;
private static Parameters.ParamInfo pCoefMax;
protected static Parameters.ParamInfo[] pfParam;
static {
pDegree = new Parameters.ParamInfo("degree", Parameters.ParamInfo.LONG_PARAM, new Long(0), new Long(10), "degree of the polynomial function.");
// The range on this variable is meaningless since it is a vector.
pCoefs = new Parameters.ParamInfo("coefs", Parameters.ParamInfo.VECTOR_PARAM, new Double(0), new Double(0), "coefficients of polynomial (should be a list of d+1 numbers where d is the degree), in the increasing order of degree.");
pCoefMax = new Parameters.ParamInfo("coef_max", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "upper bound on polynomial coefficients, used only for randomizing. Can be anywhere from -1000 to 1000 but defaults to 10.",false, new Double(10));
pCoefMin = new Parameters.ParamInfo("coef_min", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "lower bound on polynomial coefficients, used only for randomizing. Can be anywhere from -1000 to 1000 but defaults to -10.",false, new Double(-10));
pfParam = new Parameters.ParamInfo[] {pDegree, pCoefs, pCoefMin, pCoefMax};
Global.registerParams(PolyFunction.class, pfParam);
}
// --------------------------------------------------
protected String getFunctionHelp()
{
return "PolyFunction: Represents a general polynomial. Coefficients and degree can either be specified explicitely, or randomized to lie within given ranges.";
}
protected double[] coefs;
public PolyFunction()
throws Exception
{
super();
}
public PolyFunction(double[] coefs, double dMin, double dMax)
throws Exception
{
this.coefs=coefs;
this.dMin=dMin;
this.dMax=dMax;
}
public void initialize()
throws Exception
{
super.initialize();
}
protected void checkParameters()
throws Exception
{
this.coefs = Global.parseDoubleArray((Vector)getParameter("coefs"));
if (coefs.length != getLongParameter("degree") + 1)
throw new Exception("The number of coefficients must be " +
"equal to the degree of the polynomial + 1.");
if(dMin > dMax)
throw new Exception("min > max in polynomial domain: " +
"[" + dMax + ", " + dMin + "]");
}
/**
* The only thing involved in generating the polynomial is
* storing the coefficients in a more easily accessable variable.
*/
public void doGenerate()
{
coefs = Global.parseDoubleArray((Vector) getParameter("coefs"));
}
/**
* Evaluate the polynomial
*/
public double eval(double x)
{
double val=coefs[0];
double y=x;
for(int i=1; i<coefs.length; i++)
{
val+=coefs[i]*y;
y*=x;
}
return val;
}
/**
*Randomize things
*/
public void randomizeParameters()
{
// -- First, degree
if(!parameters.setByUser(pDegree.name))
parameters.randomizeParameter(pDegree.name);
// -- Then, coefficients
double coefMin = getDoubleParameter(pCoefMin.name);
double coefMax = getDoubleParameter(pCoefMax.name);
if(!parameters.setByUser(pCoefs.name))
{
int degree = (int)getLongParameter(pDegree.name);
coefs=new double[degree+1];
Vector coefVector=new Vector();
for(int i=0; i<=degree; i++)
{
coefs[i]=Global.randomDouble(coefMin, coefMax);
coefVector.add(String.valueOf(coefs[i]));
}
try {
parameters.setParameter(pCoefs.name, coefVector);
} catch (Exception e) {
Global.handleError(e, "Randomizing polynomial!");
}
}
}
/**
* Finds the minimum value of the function.
*
* Note that this is probably not the best way to go about it.
* Ideally, should be changed to a better algorithm later.
*/
public double getMinimum()
{
PolyFunction deriv=null;
try {
deriv=getDerivative();
} catch (Exception e) {
Global.handleError(e, "Couldn't make derivative!");
}
Vector v = new Vector();
v.add(new Double(dMin));
v.add(new Double(dMax));
getMinima(dMin, dMax, deriv, v);
double minval = eval(dMin);
for(int i=0; i<v.size(); i++)
{
double x = ((Double)v.get(i)).doubleValue();
double val=eval(x);
minval=Math.min(val, minval);
}
return minval;
}
/**
* Appends all local minima in the specified interval to v.
*/
public void getMinima(double a, double b, PolyFunction deriv, Vector v)
{
double x=getMinimum(a,b, deriv);
if( Math.abs(a-x) > EPSILON && Math.abs(b-x) > EPSILON )
{
v.add(new Double(x));
getMinima(x+EPSILON, b, deriv, v);
getMinima(a, x-EPSILON, deriv, v);
}
}
/**
* Does gradient descent to get a local minimum in an interval a,b.
*/
public double getMinimum(double a, double b, PolyFunction deriv)
{
double min=b;
double minVal=eval(b);
if(eval(a) < eval(b))
{
min=a;
minVal=eval(a);
}
int nIter=0;
double alpha=(b-a)/10000;
Random rand=new Random(System.currentTimeMillis());
for(int n=0; n<N_RESTARTS; n++)
{
double x;
double newx=a+(b-a)*rand.nextDouble();
nIter=0;
do
{
x=newx;
double xval=eval(x);
if(xval<minVal)
{
min=x;
minVal=xval;
}
newx=x-alpha*deriv.eval(x);
if(newx<a) newx=a;
if(newx>b) newx=b;
nIter++;
} while (Math.abs(newx-x)>EPSILON && nIter <=MAX_ITER);
//if(nIter >= MAX_ITER)
//System.err.println("WARNING: #iterations exceeded in PolyFunction");
if(eval(newx)<minVal)
min=newx;
}
return min;
}
/**
* Returns a derivative polynomial.
*/
public PolyFunction getDerivative()
throws Exception
{
if(coefs.length==1)
return new PolyFunction(new double[] {0.0}, dMin, dMax); // f'=0
// -- otherwise differntiate
double[] deriv=new double[coefs.length-1];
for(int i=1; i<coefs.length; i++)
deriv[i-1]=coefs[i]*i;
return new PolyFunction(deriv, dMin, dMax);
}
/**
* Integrates a polynomial and adds random constant term.
*/
public PolyFunction integrate()
throws Exception
{
double[] newpoly=new double[coefs.length+1];
Vector v=new Vector();
newpoly[0]=Global.randomDouble(getDoubleParameter("coef_min"), getDoubleParameter("coef_max"));
v.add(String.valueOf(newpoly[0]));
for(int i=1; i<=coefs.length; i++)
{
newpoly[i]=coefs[i-1]/(double)i;
v.add(String.valueOf(newpoly[i]));
}
PolyFunction integral=new PolyFunction(newpoly, dMin, dMax);
integral.setParameter("degree", new Long(coefs.length));
integral.setParameter("coefs", v);
return integral;
}
/**
* Used only for testing.
*/
public static void main(String[] args)
throws Exception
{
Global.rand=new Random( System.currentTimeMillis() );
PolyFunction p = new PolyFunction();
p.setParameters(new ParamParser(args), true);
p.initialize();
p.doGenerate();
double min=p.getMinimum();
System.out.println("\n---\n" + min + "\n------\n");
for(int i=p.coefs.length-1; i>=0; i--)
System.out.print(p.coefs[i] + " ");
System.out.println("");
}
}
| 8,374 | 23.34593 | 271 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/TableFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Class implements a table lookup function for truly random
* table functions.
*/
public class TableFunction extends Function
{
// -- Parameters
protected static Parameters.ParamInfo pMin;
protected static Parameters.ParamInfo pMax;
protected static Parameters.ParamInfo pPoints;
protected static Parameters.ParamInfo[] tfParam;
static {
pMin = new Parameters.ParamInfo("min", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "minimum of the function", false, new Double(-1));
pMax = new Parameters.ParamInfo("max", Parameters.ParamInfo.DOUBLE_PARAM, new Double(-1000), new Double(1000), "maximum of the function", false, new Double(1));
pPoints = new Parameters.ParamInfo("points", Parameters.ParamInfo.LONG_PARAM, new Long(2), new Long(10000), "number of points in the table lookup",false, new Long(100));
tfParam = new Parameters.ParamInfo[] {pMin, pMax, pPoints};
Global.registerParams(TableFunction.class, tfParam);
}
// --------------------------------------------------
protected String getFunctionHelp()
{
return "TableFunction: Represents a general function as a random table of points. Function is evaluated by looking up nearest point to the x value. No interpolation is done.";
}
// -- the table
protected double[] table;
public TableFunction()
throws Exception
{
super();
}
public void initialize()
throws Exception
{
super.initialize();
}
protected void checkParameters()
throws Exception
{
if(getDoubleParameter(pMin.name) >= getDoubleParameter(pMax.name))
throw new Exception("min>=max!");
if(dMin >= dMax)
throw new Exception("min >= max in domain domain!");
}
/**
* Randomizes things
*/
public void randomizeParameters()
{
parameters.randomizeParameter(pPoints.name);
if(parameters.setByUser(pMin.name))
{
pMax.low = parameters.getParameter(pMin.name);
parameters.randomizeParameter(pMax.name);
}
else
{
parameters.randomizeParameter(pMax.name);
pMin.high=parameters.getParameter(pMax.name);
parameters.randomizeParameter(pMin.name);
}
}
/**
* Generates the table.
*/
public void doGenerate()
{
table = new double[(int)getLongParameter(pPoints.name)];
double min = getDoubleParameter(pMin.name);
double max = getDoubleParameter(pMax.name);
for(int i=0; i<table.length; i++)
table[i]=Global.randomDouble(min, max);
}
/**
* Evaluates the table, by finding nearest point.
*/
public double eval(double x)
{
if(x<=dMin)
return table[0];
if(x>=dMax)
return table[table.length-1];
// -- get index
double r = (x-dMin)/(dMax-dMin);
int ind=(int)(r*table.length);
return table[ind];
}
/**
* Used only for testings
*/
public static void main(String[] args)
throws Exception
{
Global.rand=new Random( System.currentTimeMillis() );
TableFunction p = new TableFunction();
p.setParameters(new ParamParser(args), true);
p.initialize();
p.doGenerate();
for(int i=0; i<p.table.length; i++)
System.out.print(p.table[i] + " ");
System.out.println("\n--------------------------");
System.out.println(p.eval(0));
System.out.println(p.eval(1));
System.out.println(p.eval(0.5));
System.out.println(p.eval(0.7));
}
}
| 4,179 | 24.02994 | 176 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/functions/VectorFunction.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.functions;
import edu.stanford.multiagent.gamer.*;
/**
* An abstract class to support functions on vectors of values.
*/
public abstract class VectorFunction extends ParameterizedObject
{
/**
* Constructor for a vector function.
*/
public VectorFunction()
throws Exception
{
super();
}
/**
* Returns the arity of the function
*/
public abstract int getArity();
/**
* Returns the value of the function evaluated on x.
*
* @param x an array of values on which the function should
* be executed
*/
public abstract double eval(double[] x);
/**
* Initializes the vector function.
*/
public void initialize()
throws Exception
{
super.initialize();
}
}
| 1,452 | 23.627119 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/ALGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* An Adjacency list implementation of the Graph interface.
*
*/
public abstract class ALGraph extends Graph
{
protected Vector nodes;
/**
* Constructor
*/
public ALGraph()
throws Exception
{
super();
nodes=new Vector();
}
/**
* Constructor which initializes the number of nodes.
*
* @param nNodes the number of nodes in the graph
*/
public ALGraph(int nNodes)
throws Exception
{
super();
nodes = new Vector(nNodes);
this.nNodes=nNodes;
for(int i=0; i<nNodes; i++)
nodes.add(new LinkedList());
}
/**
* Adds a new node to the graph.
*/
public void addNode()
{
nNodes++;
nodes.add(new LinkedList());
}
/**
* Add a new edge to the graph.
*
* @param s the index of the node where the edge should start
* @param t the index of the node where the edge should end
*/
public void addEdge(int s, int t)
{
addEdge(s,t,null);
}
/**
* Add an edge with data to the graph.
*
* @param s the index of the node where the edge should start
* @param t the index of the node where the graph should end
* @param data the data which is to be stored at the edge
*/
public void addEdge(int s, int t, Object data)
{
if(areNeighbours(s,t))
return;
LinkedList list = (LinkedList)nodes.get(s);
Edge e=new Edge(s, t);
e.setData(data);
list.add(e);
nEdges++;
}
/**
* Sets the data item for a preexisting edge.
*
* @param s the index of the node where the edge begins
* @param t the index of the node where the edge ends
* @param data the data which is to be stored at the edge
*/
public void setEdgeData(int s, int t, Object data)
{
LinkedList list = (LinkedList)nodes.get(s);
Iterator it = list.iterator();
while(it.hasNext())
{
Edge e = (Edge)it.next();
if(e.getDest() == t)
{
it.remove();
e.setData(data);
list.add(e);
return;
}
}
}
/**
* Removes an edge from the graph.
*
* @param s the index of the node where the edge begins
* @param t the index of the node where the edge ends
*/
public void removeEdge(int s, int t)
{
LinkedList list = (LinkedList)nodes.get(s);
Iterator it=list.iterator();
while(it.hasNext())
{
Edge e = (Edge)it.next();
if(e.getDest()==t)
{
it.remove();
nEdges--;
return;
}
}
}
/**
* Removes an edge from the graph.
*
* @param e the edge to be removed
*/
public void removeEdge(Edge e)
{
LinkedList list = (LinkedList)nodes.get(e.getSource());
list.remove(e);
nEdges--;
}
/**
* Returns an Edge object from the graph.
*
* @param s the index of the node where the edge begins
* @param t the index of the node where the edge ends
*/
public Edge getEdge(int s, int t)
{
LinkedList list = (LinkedList)nodes.get(s);
Iterator it=list.iterator();
while(it.hasNext())
{
Edge e = (Edge)it.next();
if(e.getDest()==t)
return e;
}
return null;
}
/**
* Checks if two nodes are neighbours in the graph. Note that
* direction matters in this check.
*
* @param from the index of the node where the edge begins
* @param to the index of the node where the edge ends
*/
public boolean areNeighbours(int from, int to)
{
LinkedList list = (LinkedList)nodes.get(from);
Iterator it=list.iterator();
while(it.hasNext())
{
Edge e = (Edge)it.next();
if(e.getDest()==to)
return true;
}
return false;
}
/**
* Returns an iterator over the node's neighbours.
*
* @param from the index of the node whose neighbours should
* be returned
*/
public Iterator getNeighbours(int from)
{
LinkedList list = (LinkedList)nodes.get(from);
final Iterator it = list.iterator();
return new Iterator() {
public void remove() {
throw new UnsupportedOperationException("Graph Iterator");
}
public Object next() {
return new Integer(((Edge)it.next()).getDest());
}
public boolean hasNext() {
return it.hasNext();
}
};
}
/**
* Returns an iterator over the outgoing edges from a node.
*
* @param from the index of the node whose neighbours should
* be returned
*/
public Iterator getEdges(int from)
{
return ((LinkedList)nodes.get(from)).iterator();
}
/**
* Return number of neighbours extending from a node.
*
* @param from the index of the node
*/
public int getNumNeighbours(int from)
{
return ((LinkedList)nodes.get(from)).size();
}
/**
* May be implemented by subclasses to check parameters
* if any exist.
*/
protected void checkParameters() throws Exception
{
return;
}
}
| 5,688 | 20.227612 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/AMGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
/**
* An Adjacency matrix implementation of the Graph interface
*
* Not fully implemented.
*/
public abstract class AMGraph extends Graph
{
private Vector nodes;
/**
* Constructor
*/
public AMGraph()
throws Exception
{
throw new UnsupportedOperationException("AMGraph is not yet functional. Implement it, or use ALGraph instead.");
//super();
//nodes=new Vector();
}
/**
* Constructor, initializes the number of nodes
*/
public AMGraph(int nNodes)
throws Exception
{
throw new UnsupportedOperationException("AMGraph is not yet functional. Implement it, or use ALGraph instead.");
/*
super();
nodes = new Vector(nNodes);
this.nNodes=nNodes;
for(int i=0; i<nNodes; i++)
nodes.add(new BitSet(nNodes));
*/
}
/**
* Adds a node.
*/
public void addNode()
{
nNodes++;
nodes.add(new BitSet(nNodes));
}
/**
* Adds an edge.
*/
public void addEdge(int s, int t)
{
BitSet b = (BitSet)nodes.get(s);
b.set(t);
nEdges++;
}
/**
* Add an edge with data
*
* Currently not implemented, does the same thing as the other
* version of addEdge.
*/
public void addEdge(int s, int t, Object data)
{
BitSet b = (BitSet) nodes.get(s);
b.set(t);
nEdges--;
// --- TODO: set the edge data
}
/**
* Sets the data item for the edge between s and t
* if this edge already exists
*/
public void setEdgeData(int s, int t, Object data)
{
// --- TODO: fill in this function
}
/**
* Removes an edge
*/
public void removeEdge(int s, int t)
{
BitSet b = (BitSet)nodes.get(s);
b.clear(t);
nEdges--;
}
public void removeEdge(Edge e)
{
removeEdge(e.getSource(), e.getDest());
}
/**
* Gets an Edge
*/
public Edge getEdge(int s, int t)
{
throw new UnsupportedOperationException("Edges not supported in matrix graph");
}
/**
* Checks if two nodes are neighbours. This check is directional.
*/
public boolean areNeighbours(int from, int to)
{
BitSet b = (BitSet)nodes.get(from);
return b.get(to);
}
/**
* Returns an iterator over the node's neighbours
*/
public Iterator getNeighbours(int from)
{
final BitSet b = (BitSet)nodes.get(from);
return new Iterator() {
private int currentBit=b.nextSetBit(0);
public void remove() {
throw new UnsupportedOperationException("Graph Iterator");
}
public Object next() {
if(currentBit==-1)
throw new NoSuchElementException("Graph Iterator");
int oldBit=currentBit;
currentBit = b.nextSetBit(currentBit+1);
return new Integer(oldBit);
}
public boolean hasNext() {
return (currentBit!=-1);
}
};
}
/**
* Return an iterator over the outgoing edges
*/
public Iterator getEdges(int from)
{
throw new UnsupportedOperationException("Edges not supported in matrix graph");
}
}
| 3,801 | 20.122222 | 118 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/BAGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generetes a power-law out-degree graph using Barabasi-Albert model.
* Gives exponent of -3.
*/
public class BAGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters:
// m0 - starting number of vertices
// m>=m0 - additional vertices
// t number of time steps
//
private static Parameters.ParamInfo pStartNodes;
private static Parameters.ParamInfo pAddEdges;
private static Parameters.ParamInfo pTime;
private static Parameters.ParamInfo[] baParam;
static {
pStartNodes = new Parameters.ParamInfo("m0", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(100), "Number of nodes to start with. Defaults to 5.", false, new Long(5));
pAddEdges = new Parameters.ParamInfo("m", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(100), "Number of edges to add to each new node <=m0.", false, new Long(1));
pTime = new Parameters.ParamInfo("t", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(1000000), "The total number of time steps.");
baParam = new Parameters.ParamInfo[] {pStartNodes, pAddEdges, pTime};
Global.registerParams(BAGraph.class, baParam);
}
// ----------------------------------------------
public BAGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "BAGraph: Generates a power-law out-degree graph using Barabasi-Albert model. Resulting power-law exponent is around -3.";
}
/**
* Calls graph initialize
*/
public void initialize()
throws Exception
{
super.initialize();
}
/**
* Makes sure that the parameters are in the proper range.
*/
protected void checkParameters() throws Exception
{
if(getLongParameter(pAddEdges.name) > getLongParameter(pStartNodes.name))
throw new Exception("m must be <= m0");
}
/**
* Returns true if it must be the case that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return true;
}
/**
* Returns true if reflexive edges are allowed.
*/
public boolean reflexEdgesOk() {
return false;
}
/**
* Generates a random graph with given parameters.
*/
public void doGenerate()
{
int m0=(int)getLongParameter(pStartNodes.name);
int m=(int)getLongParameter(pAddEdges.name);
int t=(int)getLongParameter(pTime.name);
// -- initialize (cumulative) probabilities
int[] degrees=new int[m0+t];
int[] cumul=new int[m0+t];
for(int i=0; i<degrees.length; i++)
degrees[i]=1;
// -- add initial nodes
for(int i=0; i<m0; i++)
addNode();
// -- Now start adding nodes
for(int currNode=m0; currNode<degrees.length; currNode++)
{
addNode();
// -- generate cumul distribution
cumul[0]=degrees[0];
for(int i=1; i<currNode; i++)
cumul[i]=cumul[i-1]+degrees[i];
// -- now add to it m edges
for(int j=0; j<m; j++)
{
int r=Global.randomInt(1, cumul[currNode-1]);
int n;
for(n=0; n<currNode; n++)
if(r<=cumul[n])
break;
addEdge(currNode, n); addEdge(n, currNode);
degrees[n]++; degrees[currNode]++;
}
}
}
}
| 3,977 | 23.109091 | 177 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/CompleteGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a complete graph with the specified number of
* nodes.
*/
public class CompleteGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: The random graph is parameterized on the
// numbers of nodes and a flag telling whether or not
// reflexive edges should be included.
//
private static Parameters.ParamInfo[] cgParam;
static {
cgParam = new Parameters.ParamInfo[] {Graph.pNumNodes, Graph.pReflexEdges};
Global.registerParams(CompleteGraph.class, cgParam);
}
// ----------------------------------------------
protected String getGraphHelp()
{
return "CompleteGraph: Generates a complete graph with a specified number of nodes.";
}
/**
* Constructor to be used when parameters are coming from
* the command line. The nodes vector will then be set up in
* initialize rather than here.
*/
public CompleteGraph()
throws Exception
{
super();
}
/**
* Constructor to be used when parameters are being set
* by the game creating the graph
*/
public CompleteGraph(long numNodes, boolean reflexive)
throws Exception
{
super((int) numNodes);
try {
Long numNodesLong = new Long(numNodes);
parameters.setParameter(Graph.pNumNodes.name, numNodesLong);
Boolean reflexBool = new Boolean(reflexive);
parameters.setParameter(Graph.pReflexEdges.name, reflexBool);
} catch (Exception e) {
System.out.println("Unable to set graph parameters\n");
}
}
/**
* Calls graph initialize and also set up the nodes Vector
* if it has not yet been set up
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
int numNodes = 0;
try {
numNodes = (int) getLongParameter(Graph.pNumNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameters " +
"to initialize CompleteGraph");
}
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Resets the range of the number of nodes and randomize
*/
public void randomizeParameters()
{
if(!parameters.setByUser(pReflexEdges.name))
parameters.randomizeParameter(pReflexEdges.name);
if(!parameters.setByUser(Graph.pNumNodes.name)) {
// Do not want to allow very large graphs when we
// are randomizing since these are not always appropriate.
Graph.pNumNodes.high = new Long(20);
parameters.randomizeParameter(pNumNodes.name);
}
}
/**
* Makes sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(Graph.pNumNodes.name) <= 0)
throw new Exception("nodes <= 0");
}
/**
* It is always the case in complete graphs that for every edge
* a to b there is also an edge b to a
*/
public boolean hasSymEdges() {
return (true);
}
/**
* Return true if reflexive edges are allowed
*/
public boolean reflexEdgesOk() {
return (getBooleanParameter(Graph.pReflexEdges.name));
}
/**
* Generate a random graph with given parameters.
*/
public void doGenerate() {
long numNodes = getLongParameter(pNumNodes.name);
long currEdges = 0;
// Add edges between every pair of points in both directions.
// Only add the egde from a node to itself if the reflexive
// flag is set.
for (int i = 0; i < numNodes; i++)
for (int j = 0; j < numNodes; j++)
if ((reflexEdgesOk()) || (i != j))
addEdge(i, j);
}
}
| 4,385 | 23.640449 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/Edge.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
/**
* Implements an Edge data structure for graphs. Any
* Object can be stored in the edge
*/
public class Edge
{
private int to;
private int from;
private Object data;
// ---------------------------------------
public Edge(int from, int to)
{
this.from=from;
this.to=to;
data=null;
}
public int getSource() {
return from;
}
public int getDest() {
return to;
}
public Object getData() {
return data;
}
public void setData(Object d) {
data=d;
}
}
| 1,245 | 20.859649 | 89 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/Graph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* An abstract base class for graph implementations. Note that
* currently nodes are assumed to be consecutive, starting at 0,
* and that this class must be updated, if node removal is desired.
*/
public abstract class Graph extends ParameterizedObject
{
/*
*Private fields
*/
protected int nEdges;
protected int nNodes;
protected HashMap nodeData;
// -----------------------------------------------------------
/**
* Constructor. Currently only one version is available and it
* does not take parameters.
*/
protected Graph()
throws Exception
{
super();
nEdges=nNodes=0;
nodeData = new HashMap();
}
/**
* Initializes the graph structure using preset parameter values.
*/
public void initialize()
throws Exception
{
super.initialize();
}
/**
* Returns the help string with information about the graph class
* and the parameters taken by the class.
*/
public String getHelp()
{
StringBuffer buff=new StringBuffer();
buff.append(Global.wrap(getGraphHelp(), 70));
buff.append("\n\nGraph Parameters:\n");
buff.append(Global.wrap(parameters.getPrintableInfo(), 70));
return buff.toString();
}
/**
* Returns a help information string about the particular
* graph, does not include parameter information.
*/
protected abstract String getGraphHelp();
/**
* Returns the number of edges in the graph.
*/
public int getNEdges()
{
return nEdges;
}
/**
* Returns the number of vertices in the graph.
*/
public int getNNodes()
{
return nNodes;
}
/**
* Returns any data that is being stored at a node.
*
* @param n the index of the node
*/
public Object getNodeData(int n)
{
return nodeData.get(new Integer(n));
}
/**
* Sets node data.
*
* @param n the index of the node
* @param data the data to be stored at the node
*/
public void setNodeData(int n, Object data)
{
nodeData.put(new Integer(n), data);
}
/**
* Adds a new node to the graph.
*/
public abstract void addNode();
/**
* Adds a new edge to the graph between nodes s and t.
*
* @param s index of first node
* @param t index of second node
*/
public abstract void addEdge(int s, int t);
/**
* Adds a new edge to the graph between nodes s and t and
* sets the edge data for this edge.
*
* @param s index of first node
* @param t index of second node
* @param data data to be stored on this edge
*/
public abstract void addEdge(int s, int t, Object data);
/**
* Sets the edge data for an already existing edge.
*
* @param s index of the first node on the edge
* @param t index of the second node on the egde
* @param data data to be stored on the edge
*/
public abstract void setEdgeData(int s, int t, Object data);
/**
* Removes an edge from the graph.
*
* @param s index of the first node on the edge
* @param t index of the second node on the edge
*/
public abstract void removeEdge(int s, int t);
/**
* Removes an edge from the graph.
*
* @param e the edge to be removed
*/
public abstract void removeEdge(Edge e);
/**
* Gets an Edge.
*
* @param s index of the first node on the edge
* @param t index of the second node on the edge
*/
public abstract Edge getEdge(int s, int t);
/**
* Checks if two nodes are neighbours, i.e. if there exists an
* edge from the first node to the second. Note that the
* order of nodes specified does matter for directed graphs.
*
* @param from index of the node at which the edge begins
* @param to index of the node at which the egde ends
*/
public abstract boolean areNeighbours(int from, int to);
/**
*Returns an iterator over a node's neighbours.
*
* @param from index of the node
*/
public abstract Iterator getNeighbours(int from);
/**
*Returns an iterator over the outgoing edges from a node.
*
* @param from index of the node
*/
public abstract Iterator getEdges(int from);
/**
* Returns true if the graph is symmetric, i.e. if it must be
* the case that for every edge from node a to node b there
* also exists an edge from node b to node a.
*/
public abstract boolean hasSymEdges();
/**
* Returns true if reflexive edges are allowed in the graph.
*/
public abstract boolean reflexEdgesOk();
//-------------------------------------------------------
// -- Static stuff: Parameters which are used in many
// subclasses of graph
protected static Parameters.ParamInfo pSymEdges;
protected static Parameters.ParamInfo pReflexEdges;
protected static Parameters.ParamInfo pNumNodes;
static {
pSymEdges = new Parameters.ParamInfo("sym_edges", Parameters.ParamInfo.BOOLEAN_PARAM, new Boolean(false), new Boolean(true), "Set this to true if it should be the case that whenever there is an edge from node a to node b, there is also an edge from node b to node a.", false, Boolean.TRUE);
pReflexEdges = new Parameters.ParamInfo("reflex_ok", Parameters.ParamInfo.BOOLEAN_PARAM, new Boolean(false), new Boolean(true), "Set this to true if reflexive edges are allowed.", false, Boolean.FALSE);
pNumNodes = new Parameters.ParamInfo("nodes", Parameters.ParamInfo.LONG_PARAM, new Long(2), new Long(100000), "Number of nodes in the random graph. May be set very large by hand, but when randomized will not be set to anything over 20 since very large graphs do not work well in some games. Occasionally this parameter must be set to something even smaller by hand.");
}
}
| 6,676 | 25.287402 | 371 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/NAryTree.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates an N-ary tree with a given N and a given depth.
*
*/
public class NAryTree extends ALGraph
{
// ---------------------------------------------------
// Parameters: The N-ary tree is specified by N and the
// depth of the tree.
//
private static Parameters.ParamInfo pN;
private static Parameters.ParamInfo pDepth;
private static Parameters.ParamInfo[] treeParam;
static {
// Allow up to 5 children or a depth of 8 when the parameters are set
// manually, although it is not advisable to set both of these params
// to large values. Scale down limits when parameters are randomized.
pN = new Parameters.ParamInfo("n", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(5), "Number of children of every non-leaf node in the tree.");
pDepth = new Parameters.ParamInfo("depth", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(8), "Depth of the tree. Please note that it is advisable to use a very small value for at least one of n and depth parameters to avoid creating graphs too large for the games.");
treeParam = new Parameters.ParamInfo[] {pN, pDepth};
Global.registerParams(NAryTree.class, treeParam);
}
// ----------------------------------------------
protected String getGraphHelp()
{
return "NAryTree: Generates an n-ary tree with a given branching factor and a given depth.";
}
/**
* Constructor.
*/
public NAryTree()
throws Exception
{
super();
}
/**
* Calls graph initialize and also set up the nodes Vector
* if it has not yet been set up
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
long n = 0, depth = 0;
try {
n = getLongParameter(pN.name);
depth = getLongParameter(pDepth.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameters " +
"to initialize NAryTree");
}
int numNodes = (int) getNumNodes(n, depth);
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Reset the range of the number of nodes and randomize
*/
public void randomizeParameters()
{
// Do not want to allow very large graphs when we
// are randomizing since these are not always appropriate.
if(!parameters.setByUser(pN.name)) {
pN.high = new Long(3);
parameters.randomizeParameter(pN.name);
}
if(!parameters.setByUser(pDepth.name)) {
pDepth.high = new Long(4);
parameters.randomizeParameter(pDepth.name);
}
}
/**
* Makes sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(pN.name) <= 0)
throw new Exception("n <= 0");
if (getLongParameter(pDepth.name) <= 0)
throw new Exception("depth <= 0");
}
/**
* It is always the case in N-Ary tree that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return (true);
}
/**
* It is never the case in N-ary trees that reflexive edges
* are allowed
*/
public boolean reflexEdgesOk() {
return (false);
}
/**
* Generates the N-ary tree of the given depth
*/
public void doGenerate() {
long n = getLongParameter(pN.name);
long depth = getLongParameter(pDepth.name);
int numNodes = (int) getNumNodes(n, depth);
int child = 1;
int parent = 0;
while (child < numNodes - 1) {
for (int i = 0; i < n; i++) {
try {
// Note that edges are being added in both
// directions (parent to child and also child to
// parent) at the moment.
addEdge(parent, child);
addEdge(child, parent);
} catch (Exception e) {
Global.handleError(e, "Error adding edge to tree");
}
child++;
}
parent++;
}
}
/**
* Determines how many nodes need to be created to hold an
* N-ary tree of the given depth
*/
private long getNumNodes(long n, long depth) {
long numNodes = 0;
for (int i = 0; i < depth; i++)
numNodes += Math.pow(n, i);
return numNodes;
}
}
| 4,917 | 22.990244 | 278 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/NDimensionalGrid.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a graph on an n-dimensional grid, i.e. 1D
* is a line, 2D is a regular grid, and so on. Currently
* all dimensions are the same length to keep parameterization
* from getting out of hand.
*/
public class NDimensionalGrid extends ALGraph
{
// ---------------------------------------------------
// Parameters: The N-dimensional grid is parameterized on
// the number of dimensions and the size of a dimension.
//
protected static Parameters.ParamInfo pN;
protected static Parameters.ParamInfo pDimSize;
protected static Parameters.ParamInfo[] ndgParam;
static {
pN = new Parameters.ParamInfo("num_dimensions", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(10), "Dimensions of the graph. Must be > 0. May be set up to 10, but when randomized will be no greater than 4 since graphs of higher dimensions will be too large for most games.");
pDimSize = new Parameters.ParamInfo("dim_size", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(20), "Size of a single dimension in the graph. Must be > 0. Can be set up to 20, but when randomized will be no greater than 4.");
ndgParam = new Parameters.ParamInfo[] {pN, pDimSize};
Global.registerParams(NDimensionalGrid.class, ndgParam);
}
// ----------------------------------------------
protected String getGraphHelp()
{
return "NDimensionalGrid: Generates an n-dimensional grid with a given number of points in each dimension. Each node is connected to its neighbors.";
}
public NDimensionalGrid()
throws Exception
{
super();
}
/**
* Calls graph initialize and also sets up the nodes Vector,
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
long dimensionSize = 0;
int dimensions = 0;
try {
dimensionSize = getLongParameter(pDimSize.name);
dimensions = (int) getLongParameter(pN.name);
} catch (Exception e) {
Global.handleError(e, "Unable to get parameters to " +
"initialize NDimensionalGrid");
}
int numNodes = (int) Math.pow(dimensionSize, dimensions);
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Resets the range of all parameters so that random graph
* will not be too large to work with most games, then randomize.
*/
public void randomizeParameters()
{
if(!parameters.setByUser(pN.name)) {
pN.high = new Long(4);
parameters.randomizeParameter(pN.name);
}
if(!parameters.setByUser(pDimSize.name)) {
pDimSize.high = new Long(4);
parameters.randomizeParameter(pDimSize.name);
}
}
/**
* Makes sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(pN.name) <= 0)
throw new Exception("num_dimensions <= 0");
if (getLongParameter(pN.name) > 10)
throw new Exception("num_dimensions > 10");
if (getLongParameter(pDimSize.name) <= 0)
throw new Exception("dim_size <= 0");
if (getLongParameter(pDimSize.name) > 20)
throw new Exception("dim_size > 20");
}
/**
* Translate an array of indices into a single integer
* index of a Vector. Assumes that each index in the
* array is between 0 and dimensionSize.
*/
protected int translateIndices(int[] indices, long dimSize,
int numDimensions) {
int index = 0;
try {
for (int i = 0; i + 1 < numDimensions; i++) {
index += indices[i];
index *= dimSize;
}
index += indices[numDimensions-1];
} catch (Exception e) {
Global.handleError(e, "Error translating indices");
}
return index;
}
/**
* It is always the case in N-dimensional grids that for every
* edge a to b there is also an edge b to a
*/
public boolean hasSymEdges() {
return (true);
}
/**
* It is never the case in N-dimensional grids that reflexive edges
* are allowed
*/
public boolean reflexEdgesOk() {
return (false);
}
/**
* Generate an N-dimensional grid graph
*/
public void doGenerate() {
int n = (int) getLongParameter(pN.name);
long dimSize = getLongParameter(pDimSize.name);
boolean hasMore = true;
int currNode[] = new int[n];
// Set the index in each dimension to be 0 first
for (int i = 0; i < n; i++)
currNode[i] = 0;
// Systematically loop through all nodes indexed by their
// position in the n-dimensional grid, adding edges
// between adjacent nodes
while (hasMore) {
// First find the next node
for (int i = 0; i < n; i++) {
if (currNode[i] < dimSize - 1) {
currNode[i]++;
break;
} else {
currNode[i] = 0;
if(i == n - 1)
hasMore = false;
}
}
int node1 = translateIndices(currNode, dimSize, n);
// Now add one to each dimension in the node and
// add edges back and forth
for (int i = 0; i < n; i++) {
if (currNode[i] + 1 < dimSize) {
currNode[i]++;
int node2 = translateIndices(currNode, dimSize, n);
// Add the edges to the graph
addEdge(node1, node2);
addEdge(node2, node1);
// Reset currNode to the currentNode
currNode[i]--;
}
}
}
}
}
| 6,042 | 24.824786 | 287 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/NDimensionalWrappedGrid.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a graph on an n-dimensional grid that wraps
* around at the edges, i.e. 1D is a ring, 2D is a torus, and so
* on. Currently all dimensions are the same length to keep
* parameterization from getting out of hand.
*
* NDimensionalWrappedGrid is built as a subclass of
* NDimensionalGrid as it uses many of the same functions
* (initialize, checkParameters, translateIndices, etc.)
* but more edges are generated.
*/
public class NDimensionalWrappedGrid extends NDimensionalGrid
{
// ---------------------------------------------------
// Parameters: For now all parameters which are used are
// inherited from the NDimensionalGrid class so no new
// parameters are necessary.
static {
Global.registerParams(NDimensionalWrappedGrid.class, ndgParam);
}
// ---------------------------------------------------
//
// Constructed in same way as NDimensionalGrid
//
public NDimensionalWrappedGrid()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "NDimensionalWrappedGrid: Generates an n-dimensional grid on a sphere with a given number of points in each dimension. Each node is connected to its neighbors.";
}
//
// Generate an N-dimensional wrapped grid graph. Is
// generated in exactly the same way as NDimensionaGrid
// except that edges that wrap around the outsides of the
// grids are also added.
//
public void doGenerate() {
int n = (int) getLongParameter("num_dimensions");
long dimSize = getLongParameter("dim_size");
long currEdges = 0;
boolean hasMore = true;
int currNode[] = new int[n];
// Set the index in each dimension to be 0 first
for (int i = 0; i < n; i++)
currNode[i] = 0;
// Systematically loop through all nodes indexed by their
// position in the n-dimensional grid, adding edges
// between adjacent nodes
while (hasMore) {
// First find the next node
for (int i = 0; i < n; i++) {
if (currNode[i] < dimSize - 1) {
currNode[i]++;
break;
} else {
currNode[i] = 0;
if(i == n - 1)
hasMore = false;
}
}
int node1 = translateIndices(currNode, dimSize, n);
// Now add one to each dimension in the node and
// add edges back and forth
for (int i = 0; i < n; i++) {
if (currNode[i] + 1 < dimSize) {
currNode[i]++;
} else {
// wrap around
currNode[i] = 0;
}
int node2 = translateIndices(currNode, dimSize, n);
// Add the edges to the graph
addEdge(node1, node2);
addEdge(node2, node1);
// Reset currNode to the currentNode
if (currNode[i] > 0) {
currNode[i]--;
} else {
// for the case of the wrap-arounds
currNode[i] = (int) dimSize - 1;
}
}
}
}
}
| 3,546 | 25.871212 | 172 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/PLODGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generetes a power-law out-degree graph using PLOD algorithm by
* Palmer and Steffan (Generating Network Topologies That Obey Power Laws).
*
* If symmetric flag is set to false, generates undirected version of this.
*/
public class PLODGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: The PLOD graph is parameterized on the
// numbers of nodes and edges as well as a flag that can
// be set when it should be true that every time there is
// an edge from a to b there is an edge from b to a.
//
private static Parameters.ParamInfo pNumEdges;
private static Parameters.ParamInfo pAlpha;
private static Parameters.ParamInfo pBeta;
private static Parameters.ParamInfo[] plodParam;
static {
pNumEdges = new Parameters.ParamInfo("edges", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(10000), "The total number of directed/or undirected edges.");
pAlpha = new Parameters.ParamInfo("alpha", Parameters.ParamInfo.DOUBLE_PARAM, new Double(1), new Double(5), "Alpha parameter (power) in the power law, defaults to 2.1.", false, new Double(2.1));
pBeta = new Parameters.ParamInfo("beta", Parameters.ParamInfo.DOUBLE_PARAM, new Double(1), new Double(100000), "Beta parameter (multiplier) in the power law, defaults to 5.", false, new Double(5));
plodParam = new Parameters.ParamInfo[] {Graph.pNumNodes, pNumEdges, pAlpha, pBeta,
Graph.pSymEdges };
Global.registerParams(PLODGraph.class, plodParam);
}
// ----------------------------------------------
public PLODGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "PLODGraph: Generates a power-law out-degree graph via PLOD algorithm of Palmer and Stefan.";
}
/**
* Calls graph initialize and also sets up the nodes Vector.
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
int numNodes = 0;
try {
numNodes = (int) getLongParameter(Graph.pNumNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameter to " +
"initialize PLODGraph");
}
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Resets the range of the number of nodes and randomizes.
*/
public void randomizeParameters()
{
parameters.randomizeParameter(Graph.pSymEdges.name);
if(!parameters.setByUser(Graph.pNumNodes.name)) {
if (parameters.setByUser(pNumEdges.name)) {
long edges = getLongParameter(pNumEdges.name);
if(getBooleanParameter(Graph.pSymEdges.name))
edges*=2;
double x = Math.sqrt(1+4*edges);
x=(1+x)/2;
Graph.pNumNodes.low = new Long(Math.round(Math.ceil(x)));
}
Graph.pNumNodes.high = new Long(20);
if (((Long)Graph.pNumNodes.high).longValue() <
((Long)Graph.pNumNodes.low).longValue()) {
Global.handleError("Cannot randomize parameter nodes because " +
"edges was set too high. Try a smaller " +
"value of edges, or try randomizing both " +
"parameters together.");
}
parameters.randomizeParameter(Graph.pNumNodes.name);
}
if(!parameters.setByUser(pNumEdges.name)) {
long nodes=getLongParameter(Graph.pNumNodes.name);
long high = nodes*(nodes-1);
if(getBooleanParameter(Graph.pSymEdges.name))
high = high/2;
pNumEdges.high=new Long(high);
parameters.randomizeParameter(pNumEdges.name);
return;
}
}
/**
* Makes sure that the parameters are in the proper range.
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(Graph.pNumNodes.name) <= 0)
throw new Exception("nodes <= 0");
if (getLongParameter(pNumEdges.name) <= 0)
throw new Exception("edges <= 0");
if (getBooleanParameter(Graph.pSymEdges.name)) {
if (getLongParameter(pNumEdges.name) >
((getLongParameter(Graph.pNumNodes.name) - 1) *
getLongParameter(Graph.pNumNodes.name)) / 2)
throw new Exception("edges is too large for nodes");
} else {
if (getLongParameter(pNumEdges.name) >
((getLongParameter(Graph.pNumNodes.name) - 1) *
getLongParameter(Graph.pNumNodes.name)))
throw new Exception("edges is too large for nodes");
}
}
/**
* Returns true if it must be the case that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return (getBooleanParameter(Graph.pSymEdges.name));
}
/**
* Returns true if reflexive edges are allowed.
*/
public boolean reflexEdgesOk() {
return false;
}
/**
* Generates a random graph with given parameters.
*/
public void doGenerate() {
System.err.println("WARNING: Generating PLODGraph may take a very long time. Consider using BAGraph instead");
int numNodes = (int)getLongParameter(pNumNodes.name);
int numEdges = (int)getLongParameter(pNumEdges.name);
double alpha = getDoubleParameter(pAlpha.name);
double beta = getDoubleParameter(pBeta.name);
boolean sym=hasSymEdges();
// -- initialize degrees
int[] degrees=new int[numNodes];
int total=0;
for(int i=0; i<degrees.length; i++) {
int x=Global.randomInt(1,numNodes);
degrees[i] = (int)Math.round(beta*Math.pow(x, -alpha));
total+=degrees[i];
}
// -- add edges
int cond=(sym ? 2 : 1);
for(int i=0; i<numEdges; i++) {
if(total<cond) {
System.err.println("WARNING: Failed to generated requested number of edges in PLOD!");
return;
}
while(true) {
int s=Global.randomInt(0, numNodes-1);
int t=Global.randomInt(0, numNodes-1);
boolean ok= (s!=t) && (degrees[s]>0) && !areNeighbours(s,t);
if(sym)
ok = ok && degrees[t]>0;
if ( ok ) {
addEdge(s,t);
degrees[s]--;
if(sym) {
addEdge(t,s);
degrees[t]--;
}
total-=cond;
break;
}
}
}
}
}
| 6,715 | 25.234375 | 198 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/RandomGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a random graph with the specified number of
* nodes and edges.
*
* If the sym flag is set, then every time there is an edge
* from a to b, there will also be an edge from b to a, and the
* number of edges will really be twice the number specified.
*/
public class RandomGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: The random graph is parameterized on the
// numbers of nodes and edges as well as a flag that can
// be set when it should be true that every time there is
// an edge from a to b there is an edge from b to a.
//
private static Parameters.ParamInfo pNumEdges;
private static Parameters.ParamInfo[] rgParam;
static {
pNumEdges = new Parameters.ParamInfo("edges", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(10000000000L), "If symmetric_edges is not set, the total number of directed edges in the random graph. If symmetric_edges is set, the number of pairs of directed edges.");
rgParam = new Parameters.ParamInfo[] {Graph.pNumNodes, pNumEdges,
Graph.pSymEdges,
Graph.pReflexEdges};
Global.registerParams(RandomGraph.class, rgParam);
}
// ----------------------------------------------
public RandomGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "RandomGraph: Generates a (uniformly) random graph according to G(n,m) model.";
}
/**
* Calls graph initialize and also sets up the nodes Vector.
* if it has not yet been set up
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
int numNodes = 0;
try {
numNodes = (int) getLongParameter(Graph.pNumNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameter to " +
"initialize RandomGraph");
}
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Makes sure that the parameters are in the proper range.
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(Graph.pNumNodes.name) <= 0)
throw new Exception("nodes <= 0");
if (getLongParameter(pNumEdges.name) <= 0)
throw new Exception("edges <= 0");
if (getBooleanParameter(Graph.pSymEdges.name)) {
if (getBooleanParameter(Graph.pReflexEdges.name)) {
if (getLongParameter(pNumEdges.name) >
(((getLongParameter(Graph.pNumNodes.name) - 1) *
getLongParameter(Graph.pNumNodes.name)) / 2) +
getLongParameter(Graph.pNumNodes.name))
throw new Exception("edges is too large for nodes");
} else {
if (getLongParameter(pNumEdges.name) >
((getLongParameter(Graph.pNumNodes.name) - 1) *
getLongParameter(Graph.pNumNodes.name)) / 2)
throw new Exception("edges is too large for nodes");
}
} else {
if (getBooleanParameter(Graph.pReflexEdges.name)) {
if (getLongParameter(pNumEdges.name) >
((getLongParameter(Graph.pNumNodes.name) - 1) *
getLongParameter(Graph.pNumNodes.name)) +
getLongParameter(Graph.pNumNodes.name))
throw new Exception("edges is too large for nodes");
} else {
if (getLongParameter(pNumEdges.name) >
((getLongParameter(Graph.pNumNodes.name) - 1) *
getLongParameter(Graph.pNumNodes.name)))
throw new Exception("edges is too large for nodes");
}
}
}
/**
* Returns true if it must be the case that for every edge
* a to b there is also an edge b to a
*/
public boolean hasSymEdges() {
return (getBooleanParameter(Graph.pSymEdges.name));
}
/**
* Returns true if reflexive edges are allowed.
*/
public boolean reflexEdgesOk() {
return (getBooleanParameter(Graph.pReflexEdges.name));
}
/**
* Resets range of parameters and randomizes.
*/
public void randomizeParameters()
{
parameters.randomizeParameter(Graph.pSymEdges.name);
parameters.randomizeParameter(Graph.pReflexEdges.name);
if(!parameters.setByUser(Graph.pNumNodes.name)) {
if (parameters.setByUser(pNumEdges.name)) {
long edges = getLongParameter(pNumEdges.name);
if(getBooleanParameter(Graph.pSymEdges.name))
edges*=2;
if(getBooleanParameter(Graph.pReflexEdges.name))
Graph.pNumNodes.low = new Long(Math.round(Math.ceil(Math.sqrt(edges))));
else {
double x = Math.sqrt(1+4*edges);
x=(1+x)/2;
Graph.pNumNodes.low = new Long(Math.round(Math.ceil(x)));
}
}
Graph.pNumNodes.high = new Long(20);
if (((Long)Graph.pNumNodes.high).longValue() <
((Long)Graph.pNumNodes.low).longValue()) {
Global.handleError("Cannot randomize parameter nodes because " +
"edges was set too high. Try a smaller " +
"value of edges, or try randomizing both " +
"parameters together.");
}
parameters.randomizeParameter(Graph.pNumNodes.name);
}
if(!parameters.setByUser(pNumEdges.name)) {
long nodes=getLongParameter(Graph.pNumNodes.name);
long high = nodes*(nodes-1);
if(getBooleanParameter(Graph.pSymEdges.name))
high = high/2;
if(getBooleanParameter(Graph.pReflexEdges.name))
high = high + nodes;
pNumEdges.high=new Long(high);
parameters.randomizeParameter(pNumEdges.name);
return;
}
}
/**
* Generates a random graph with given parameters.
*/
public void doGenerate() {
long numNodes = getLongParameter(Graph.pNumNodes.name);
long numEdges = getLongParameter(pNumEdges.name);
long currEdges = 0;
if (hasSymEdges()) {
// Add numEdges pairs of edges in both directions
// between nodes randomly
while (currEdges < numEdges) {
int i = (int) Global.randomLong(0, numNodes-1);
int j = (int) Global.randomLong(0, numNodes-1);
if (!areNeighbours(i, j)) {
if ((i != j) || (reflexEdgesOk())) {
addEdge(i, j);
if (i != j) addEdge(j, i);
currEdges++;
}
}
}
} else {
// Add numEdges undirected edges randomly
while (currEdges < numEdges) {
int i = (int) Global.randomLong(0, numNodes-1);
int j = (int) Global.randomLong(0, numNodes-1);
if (!areNeighbours(i, j)) {
if ((i != j) || (reflexEdgesOk())) {
addEdge(i, j);
currEdges++;
}
}
}
}
}
}
| 7,127 | 25.4 | 274 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/RingGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a ring structured graph with the specified number
* of nodes.
*/
public class RingGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: The ring structured graph is parameterized by
// the number of inner nodes and the number of outernodes.
//
private static Parameters.ParamInfo pInnerNodes;
private static Parameters.ParamInfo pOuterNodes;
private static Parameters.ParamInfo[] rgParam;
static {
// arbitrary choice for the max number of nodes in inner and
// outer circles.. just don't want these to be too big or
// the graph will blow up in size
pInnerNodes = new Parameters.ParamInfo("inner_nodes", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(50), "Number of nodes in the inner circle of the ring graph. May be set up to 50 by hand, but when randomized will be set to something no larger than 6 since many games cannot handle large graphs.");
pOuterNodes = new Parameters.ParamInfo("outer_nodes", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(50), "Number of nodes in each of the outer circles of the ring graph. May be set up to 50 by hand, but when randomized will be set to something no larger than 6 since many games cannot handle large graphs.");
rgParam = new Parameters.ParamInfo[] {pInnerNodes, pOuterNodes};
Global.registerParams(RingGraph.class, rgParam);
}
// ----------------------------------------------
/**
* Constructor
*/
public RingGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "RingGraph: Generates a ring-of-ring graphs. Consists of a central ring of nodes, each of which participates in a separate outer ring of nodes.";
}
/**
* Calls graph initialize and also sets up the nodes Vector.
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
long innerNodes = 0, outerNodes = 0;
try {
innerNodes = getLongParameter(pInnerNodes.name);
outerNodes = getLongParameter(pOuterNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameters to " +
"initialize RingGraph");
}
int numNodes = (int) (innerNodes * outerNodes);
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Makes sure that the parameters are in the proper range
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(pInnerNodes.name) <= 0)
throw new Exception("inner_nodes <= 0");
if (getLongParameter(pOuterNodes.name) <= 0)
throw new Exception("outer_nodes <= 0");
}
/**
* Resets the range of the number of nodes and randomize
*/
public void randomizeParameters()
{
if(!parameters.setByUser(pInnerNodes.name)) {
pInnerNodes.high = new Long(6);
parameters.randomizeParameter(pInnerNodes.name);
}
if(!parameters.setByUser(pOuterNodes.name)) {
pOuterNodes.high = new Long(6);
parameters.randomizeParameter(pOuterNodes.name);
}
}
/**
* It is always the case in ring graphs that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return (true);
}
/**
* It is never the case in ring graphs that reflexive edges
* are allowed.
*/
public boolean reflexEdgesOk() {
return (false);
}
/**
* Generates a ring structured graph getting the number
* of nodes from the parameters
*/
public void doGenerate() {
int innerNodes = (int) getLongParameter(pInnerNodes.name);
int outerNodes = (int) getLongParameter(pOuterNodes.name);
for (int i = 0; i < innerNodes; i++) {
// Add two edges on the graph between the current
// inner node and the next inner node
if (i < innerNodes - 1) {
try {
addEdge(i * outerNodes, (i+1) * outerNodes);
addEdge((i+1) * outerNodes, i * outerNodes);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
} else {
try {
addEdge(i * outerNodes, 0);
addEdge(0, i * outerNodes);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
}
// Also add a loop of size outerNodes starting with
// the node (i * outerNodes)
for (int j = (i * outerNodes);
j < ((i + 1) * outerNodes); j++) {
if (j < ((i + 1) * outerNodes) - 1) {
try {
addEdge(j, j + 1);
addEdge(j + 1, j);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
} else {
try {
addEdge(j, i * outerNodes);
addEdge(i * outerNodes, j);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
}
}
}
}
}
| 5,566 | 25.764423 | 319 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/RoadGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a road graph with the specified number
* of nodes.
*/
public class RoadGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: The road graph is specified only by the
// number of nodes.
//
private static Parameters.ParamInfo[] rgParam;
static {
rgParam = new Parameters.ParamInfo[] {Graph.pNumNodes};
Global.registerParams(RoadGraph.class, rgParam);
}
// ----------------------------------------------
/**
* Constructor
*/
public RoadGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "RoadGraph: Generates a road graph: consists of a two sets of n nodes each connected in a line, with additional n edges connecting corresponding nodes in two sets.";
}
/**
* Calls graph initialize and also sets up the nodes Vector.
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
int numNodes = 0;
try {
numNodes = (int) getLongParameter(Graph.pNumNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameter " +
"to initialize RoadGraph");
}
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Resets the range of the number of nodes and randomize.
*/
public void randomizeParameters()
{
if(!parameters.setByUser(Graph.pNumNodes.name)) {
// Do not want to allow very large graphs when we
// are randomizing since these are not always appropriate.
Graph.pNumNodes.high = new Long(20);
parameters.randomizeParameter(Graph.pNumNodes.name);
}
}
/**
* Makes sure that the parameters are in the proper ranges.
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(Graph.pNumNodes.name) <= 0)
throw new Exception("nodes <= 0");
}
/**
* It is always the case in road graphs that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return (true);
}
/**
* It is never the case in road graphs that reflexive edges
* are allowed.
*/
public boolean reflexEdgesOk() {
return (false);
}
/**
* Generates a road structured graph getting the number
* of nodes from the parameters.
*/
public void doGenerate() {
long numNodes = getLongParameter(Graph.pNumNodes.name);
// Now add edges in the graph in the appropriate places.
// For all node i, add edges to i-2 and i+2. For even
// numbered nods, also add i+1 and for odd numbered
// nodes also add i-1, unless of course some of these
// nodes do not exist.
for (int i = 0; i < numNodes; i++) {
if (i-2 >= 0) {
try {
addEdge(i, i-2);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
}
if (i+2 < numNodes) {
try {
addEdge(i, i+2);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
}
if (i%2 == 0) {
// For nodes on the even side of the road
if (i + 1 < numNodes) {
try {
addEdge(i, i+1);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
}
} else {
// For nodes on the odd side of the road
try {
addEdge(i, i-1);
} catch (Exception e) {
Global.handleError(e, "Error adding edge");
}
}
}
}
}
| 4,228 | 21.983696 | 173 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/SmallWorldGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a random graph using the Watts-Strogatz model
* Nature 1998.
*
* Taken from Albert and Barabasi Tutorial.
*/
public class SmallWorldGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: The random graph is parameterized on the
// numbers of nodes, paremer K indicating connectedness of the
// original ring lattice, and probability p of rewiring
//
private static Parameters.ParamInfo pKParam;
private static Parameters.ParamInfo pRewireParam;
private static Parameters.ParamInfo[] wsParam;
static {
pKParam = new Parameters.ParamInfo("K", Parameters.ParamInfo.LONG_PARAM, new Long(1), new Long(10), "Each node will have 2K neighbours in the original ring lattice. Defaults to 2 or can be randomized.", false, new Long(2));
pRewireParam = new Parameters.ParamInfo("p", Parameters.ParamInfo.DOUBLE_PARAM, new Double(0), new Double(1), "Probability of rewiring each edge", false, new Double(0.5));
wsParam = new Parameters.ParamInfo[] {Graph.pNumNodes, pKParam, pRewireParam};
Global.registerParams(SmallWorldGraph.class, wsParam);
}
// ----------------------------------------------
public SmallWorldGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "SmallWorldGraph: Generates a small-world graph according to the Watts-Strogatz model. Starts with a ring lattice of degree 2k, and then randomly rewires each edge with some probability.";
}
/**
* Calls graph initialize and also sets up the nodes Vector.
*/
public void initialize()
throws Exception
{
super.initialize();
if (nodes.isEmpty()) {
int numNodes = 0;
try {
numNodes = (int) getLongParameter(Graph.pNumNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get parameter to " +
"initialize SmallWorldGraph");
}
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Resets parameter ranges and randomize.
*/
public void randomizeParameters()
{
parameters.randomizeParameter(pRewireParam.name);
if(!parameters.setByUser(Graph.pNumNodes.name)) {
// Do not want to allow very large graphs when we
// are randomizing since these are not always appropriate.
Graph.pNumNodes.high = new Long(20);
parameters.randomizeParameter(Graph.pNumNodes.name);
}
if(!parameters.setByUser(pKParam.name)) {
pKParam.high = new Long(Math.max(getLongParameter(Graph.pNumNodes.name)/2 - 1, 1));
parameters.randomizeParameter(pKParam.name);
}
}
/**
* Makes sure that the parameters are in the proper range.
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(Graph.pNumNodes.name) <= 0)
Global.handleError("nodes <= 0");
if (getLongParameter(pKParam.name) >= Math.max(getLongParameter(Graph.pNumNodes.name)/2, 2) )
Global.handleError("K must be < nodes /2");
}
/**
* Returns true if it must be the case that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return true;
}
/**
* Returns true if reflexive edges are allowed.
*/
public boolean reflexEdgesOk() {
return false;
}
/**
* Generates a random graph with given parameters.
*/
public void doGenerate() {
int numNodes = (int)getLongParameter(Graph.pNumNodes.name);
int K = (int)getLongParameter(pKParam.name);
double p = getDoubleParameter(pRewireParam.name);
// -- First set-up original ring
// -- need to do that because rewiring prohibits duplication
for(int i=1; i<=K; i++)
for(int n=0; n<numNodes; n++) {
int t= (n + i) % numNodes;
addEdge(n,t);
addEdge(t,n);
}
// -- now do rewiring
for(int i=1; i<=K; i++)
for(int n=0; n<numNodes; n++) {
double d = Global.randomDouble();
if(getNumNeighbours(n)>=numNodes-1)
continue; // -- cannot rewire
if(d<=p) {
// -- rewire
int t;
do {
t=Global.randomInt(1, numNodes - 1);
t= (n+t) % numNodes;
}
while(areNeighbours(n, t));
int s = (n+i) % numNodes;
removeEdge(n, s);
removeEdge(s, n);
addEdge(n, t);
addEdge(t, n);
}
}
}
}
| 5,098 | 24.623116 | 224 |
java
|
null |
DRStackelberg-main/gamut/edu/stanford/multiagent/gamer/graphs/StarGraph.java
|
/*
* Copyright (C) 2004 Jennifer Wortman, Eugene Nudelman, Kevin Leyton-Brown, Yoav Shoham.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.stanford.multiagent.gamer.graphs;
import java.util.*;
import edu.stanford.multiagent.gamer.*;
/**
* Generates a star graph with n nodes total.
*/
public class StarGraph extends ALGraph
{
// ---------------------------------------------------
// Parameters: the StarGraph is parameterized only by the
// total number of nodes.
//
private static Parameters.ParamInfo[] starParam;
static {
starParam = new Parameters.ParamInfo[] {Graph.pNumNodes};
Global.registerParams(StarGraph.class, starParam);
}
// ----------------------------------------------
public StarGraph()
throws Exception
{
super();
}
protected String getGraphHelp()
{
return "StarGraph: Generates a star graph: a single center node connected to all other nodes.";
}
/**
* Initializes the graph with the correct number of nodes.
*/
public void initialize()
throws Exception
{
super.initialize();
int numNodes = 0;
if (nodes.isEmpty()) {
try {
numNodes = (int) getLongParameter(Graph.pNumNodes.name);
} catch (Exception e) {
Global.handleError(e, "Could not get number of nodes.");
}
for(int i = 0; i < numNodes; i++)
addNode();
}
}
/**
* Resets the range of the number of nodes and randomize.
*/
public void randomizeParameters()
{
if(!parameters.setByUser(Graph.pNumNodes.name)) {
// Do not want to allow very large graphs when we
// are randomizing since these are not always appropriate.
Graph.pNumNodes.high = new Long(20);
parameters.randomizeParameter(Graph.pNumNodes.name);
}
}
/**
* Makes sure that the parameters are in the proper range.
*/
protected void checkParameters() throws Exception
{
if (getLongParameter(Graph.pNumNodes.name) <= 0)
throw new Exception("nodes <= 0");
}
/**
* It is always the case in star graphs that for every edge
* a to b there is also an edge b to a.
*/
public boolean hasSymEdges() {
return (true);
}
/**
* It is never the case in star graphs that reflexive edges
* are allowed
*/
public boolean reflexEdgesOk() {
return (false);
}
/**
* Generate the Star graph
*/
public void doGenerate() {
int numNodes = (int) getLongParameter(Graph.pNumNodes.name);
// Set node 0 to be the root. Add edges from the root to
// all other nodes and from all other nodes to the root.
for (int i = 1; i < numNodes; i++) {
try {
addEdge(0, i);
addEdge(i, 0);
} catch (Exception e) {
Global.handleError(e, "Error adding edge to tree.");
}
}
}
}
| 3,342 | 21.436242 | 96 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/KerberosTestUtils.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import java.io.File;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.UUID;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
/**
* Test helper class for Java Kerberos setup.
*/
public class KerberosTestUtils {
private static String keytabFile = new File(System.getProperty("test.dir", "target"),
UUID.randomUUID().toString()).toString();
public static String getRealm() {
return "EXAMPLE.COM";
}
public static String getClientPrincipal() {
return "[email protected]";
}
public static String getServerPrincipal() {
return "HTTP/[email protected]";
}
public static String getKeytabFile() {
return keytabFile;
}
private static class KerberosConfiguration extends Configuration {
private String principal;
public KerberosConfiguration(String principal) {
this.principal = principal;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<String, String>();
options.put("keyTab", KerberosTestUtils.getKeytabFile());
options.put("principal", principal);
options.put("useKeyTab", "true");
options.put("storeKey", "true");
options.put("doNotPrompt", "true");
options.put("useTicketCache", "true");
options.put("renewTGT", "true");
options.put("refreshKrb5Config", "true");
options.put("isInitiator", "true");
String ticketCache = System.getenv("KRB5CCNAME");
if (ticketCache != null) {
options.put("ticketCache", ticketCache);
}
options.put("debug", "true");
return new AppConfigurationEntry[]{
new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
options),};
}
}
public static <T> T doAs(String principal, final Callable<T> callable) throws Exception {
LoginContext loginContext = null;
try {
Set<Principal> principals = new HashSet<Principal>();
principals.add(new KerberosPrincipal(KerberosTestUtils.getClientPrincipal()));
Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal));
loginContext.login();
subject = loginContext.getSubject();
return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
@Override
public T run() throws Exception {
return callable.call();
}
});
} catch (PrivilegedActionException ex) {
throw ex.getException();
} finally {
if (loginContext != null) {
loginContext.logout();
}
}
}
public static <T> T doAsClient(Callable<T> callable) throws Exception {
return doAs(getClientPrincipal(), callable);
}
public static <T> T doAsServer(Callable<T> callable) throws Exception {
return doAs(getServerPrincipal(), callable);
}
}
| 4,173 | 32.934959 | 101 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestAuthenticatedURL.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.client;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestAuthenticatedURL {
@Test
public void testToken() throws Exception {
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
Assert.assertFalse(token.isSet());
token = new AuthenticatedURL.Token("foo");
Assert.assertTrue(token.isSet());
Assert.assertEquals("foo", token.toString());
}
@Test
public void testInjectToken() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
token.set("foo");
AuthenticatedURL.injectToken(conn, token);
Mockito.verify(conn).addRequestProperty(Mockito.eq("Cookie"), Mockito.anyString());
}
@Test
public void testExtractTokenOK() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
String tokenStr = "foo";
Map<String, List<String>> headers = new HashMap<String, List<String>>();
List<String> cookies = new ArrayList<String>();
cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr);
headers.put("Set-Cookie", cookies);
Mockito.when(conn.getHeaderFields()).thenReturn(headers);
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
AuthenticatedURL.extractToken(conn, token);
Assert.assertEquals(tokenStr, token.toString());
}
@Test
public void testExtractTokenFail() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED);
String tokenStr = "foo";
Map<String, List<String>> headers = new HashMap<String, List<String>>();
List<String> cookies = new ArrayList<String>();
cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr);
headers.put("Set-Cookie", cookies);
Mockito.when(conn.getHeaderFields()).thenReturn(headers);
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
token.set("bar");
try {
AuthenticatedURL.extractToken(conn, token);
Assert.fail();
} catch (AuthenticationException ex) {
// Expected
Assert.assertFalse(token.isSet());
} catch (Exception ex) {
Assert.fail();
}
}
@Test
public void testConnectionConfigurator() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
Mockito.when(conn.getResponseCode()).
thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED);
ConnectionConfigurator connConf =
Mockito.mock(ConnectionConfigurator.class);
Mockito.when(connConf.configure(Mockito.<HttpURLConnection>any())).
thenReturn(conn);
Authenticator authenticator = Mockito.mock(Authenticator.class);
AuthenticatedURL aURL = new AuthenticatedURL(authenticator, connConf);
aURL.openConnection(new URL("http://foo"), new AuthenticatedURL.Token());
Mockito.verify(connConf).configure(Mockito.<HttpURLConnection>any());
}
@Test
public void testGetAuthenticator() throws Exception {
Authenticator authenticator = Mockito.mock(Authenticator.class);
AuthenticatedURL aURL = new AuthenticatedURL(authenticator);
Assert.assertEquals(authenticator, aURL.getAuthenticator());
}
}
| 4,161 | 33.97479 | 89 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestPseudoAuthenticator.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.client;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler;
import org.junit.Assert;
import org.junit.Test;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
public class TestPseudoAuthenticator {
private Properties getAuthenticationHandlerConfiguration(boolean anonymousAllowed) {
Properties props = new Properties();
props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple");
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, Boolean.toString(anonymousAllowed));
return props;
}
@Test
public void testGetUserName() throws Exception {
PseudoAuthenticator authenticator = new PseudoAuthenticator();
Assert.assertEquals(System.getProperty("user.name"), authenticator.getUserName());
}
@Test
public void testAnonymousAllowed() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(true));
auth.start();
try {
URL url = new URL(auth.getBaseURL());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
} finally {
auth.stop();
}
}
@Test
public void testAnonymousDisallowed() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(false));
auth.start();
try {
URL url = new URL(auth.getBaseURL());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
Assert.assertTrue(conn.getHeaderFields().containsKey("WWW-Authenticate"));
Assert.assertEquals("Authentication required", conn.getResponseMessage());
} finally {
auth.stop();
}
}
@Test
public void testAuthenticationAnonymousAllowed() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(true));
auth._testAuthentication(new PseudoAuthenticator(), false);
}
@Test
public void testAuthenticationAnonymousDisallowed() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(false));
auth._testAuthentication(new PseudoAuthenticator(), false);
}
@Test
public void testAuthenticationAnonymousAllowedWithPost() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(true));
auth._testAuthentication(new PseudoAuthenticator(), true);
}
@Test
public void testAuthenticationAnonymousDisallowedWithPost() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(false));
auth._testAuthentication(new PseudoAuthenticator(), true);
}
}
| 4,095 | 37.280374 | 105 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestKerberosAuthenticator.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.client;
import org.apache.hadoop.minikdc.KerberosSecurityTestcase;
import org.apache.hadoop.security.authentication.KerberosTestUtils;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler;
import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import org.junit.Test;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.Callable;
@RunWith(Parameterized.class)
public class TestKerberosAuthenticator extends KerberosSecurityTestcase {
private boolean useTomcat = false;
public TestKerberosAuthenticator(boolean useTomcat) {
this.useTomcat = useTomcat;
}
@Parameterized.Parameters
public static Collection booleans() {
return Arrays.asList(new Object[][] {
{ false },
{ true }
});
}
@Before
public void setup() throws Exception {
// create keytab
File keytabFile = new File(KerberosTestUtils.getKeytabFile());
String clientPrincipal = KerberosTestUtils.getClientPrincipal();
String serverPrincipal = KerberosTestUtils.getServerPrincipal();
clientPrincipal = clientPrincipal.substring(0, clientPrincipal.lastIndexOf("@"));
serverPrincipal = serverPrincipal.substring(0, serverPrincipal.lastIndexOf("@"));
getKdc().createPrincipal(keytabFile, clientPrincipal, serverPrincipal);
}
private Properties getAuthenticationHandlerConfiguration() {
Properties props = new Properties();
props.setProperty(AuthenticationFilter.AUTH_TYPE, "kerberos");
props.setProperty(KerberosAuthenticationHandler.PRINCIPAL, KerberosTestUtils.getServerPrincipal());
props.setProperty(KerberosAuthenticationHandler.KEYTAB, KerberosTestUtils.getKeytabFile());
props.setProperty(KerberosAuthenticationHandler.NAME_RULES,
"RULE:[1:$1@$0](.*@" + KerberosTestUtils.getRealm()+")s/@.*//\n");
return props;
}
@Test(timeout=60000)
public void testFallbacktoPseudoAuthenticator() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
Properties props = new Properties();
props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple");
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false");
AuthenticatorTestCase.setAuthenticationHandlerConfig(props);
auth._testAuthentication(new KerberosAuthenticator(), false);
}
@Test(timeout=60000)
public void testFallbacktoPseudoAuthenticatorAnonymous() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
Properties props = new Properties();
props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple");
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "true");
AuthenticatorTestCase.setAuthenticationHandlerConfig(props);
auth._testAuthentication(new KerberosAuthenticator(), false);
}
@Test(timeout=60000)
public void testNotAuthenticated() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
AuthenticatorTestCase.setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration());
auth.start();
try {
URL url = new URL(auth.getBaseURL());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
Assert.assertTrue(conn.getHeaderField(KerberosAuthenticator.WWW_AUTHENTICATE) != null);
} finally {
auth.stop();
}
}
@Test(timeout=60000)
public void testAuthentication() throws Exception {
final AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration());
KerberosTestUtils.doAsClient(new Callable<Void>() {
@Override
public Void call() throws Exception {
auth._testAuthentication(new KerberosAuthenticator(), false);
return null;
}
});
}
@Test(timeout=60000)
public void testAuthenticationPost() throws Exception {
final AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration());
KerberosTestUtils.doAsClient(new Callable<Void>() {
@Override
public Void call() throws Exception {
auth._testAuthentication(new KerberosAuthenticator(), true);
return null;
}
});
}
@Test(timeout=60000)
public void testAuthenticationHttpClient() throws Exception {
final AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration());
KerberosTestUtils.doAsClient(new Callable<Void>() {
@Override
public Void call() throws Exception {
auth._testAuthenticationHttpClient(new KerberosAuthenticator(), false);
return null;
}
});
}
@Test(timeout=60000)
public void testAuthenticationHttpClientPost() throws Exception {
final AuthenticatorTestCase auth = new AuthenticatorTestCase(useTomcat);
AuthenticatorTestCase.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration());
KerberosTestUtils.doAsClient(new Callable<Void>() {
@Override
public Void call() throws Exception {
auth._testAuthenticationHttpClient(new KerberosAuthenticator(), true);
return null;
}
});
}
}
| 6,536 | 38.379518 | 103 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/AuthenticatorTestCase.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.client;
import org.apache.catalina.deploy.FilterDef;
import org.apache.catalina.deploy.FilterMap;
import org.apache.catalina.startup.Tomcat;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.SystemDefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.FilterHolder;
import org.mortbay.jetty.servlet.ServletHolder;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.URL;
import java.security.Principal;
import java.util.Properties;
import org.junit.Assert;
public class AuthenticatorTestCase {
private Server server;
private String host = null;
private int port = -1;
private boolean useTomcat = false;
private Tomcat tomcat = null;
Context context;
private static Properties authenticatorConfig;
public AuthenticatorTestCase() {}
public AuthenticatorTestCase(boolean useTomcat) {
this.useTomcat = useTomcat;
}
protected static void setAuthenticationHandlerConfig(Properties config) {
authenticatorConfig = config;
}
public static class TestFilter extends AuthenticationFilter {
@Override
protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException {
return authenticatorConfig;
}
}
@SuppressWarnings("serial")
public static class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = req.getInputStream();
OutputStream os = resp.getOutputStream();
int c = is.read();
while (c > -1) {
os.write(c);
c = is.read();
}
is.close();
os.close();
resp.setStatus(HttpServletResponse.SC_OK);
}
}
protected int getLocalPort() throws Exception {
ServerSocket ss = new ServerSocket(0);
int ret = ss.getLocalPort();
ss.close();
return ret;
}
protected void start() throws Exception {
if (useTomcat) startTomcat();
else startJetty();
}
protected void startJetty() throws Exception {
server = new Server(0);
context = new Context();
context.setContextPath("/foo");
server.setHandler(context);
context.addFilter(new FilterHolder(TestFilter.class), "/*", 0);
context.addServlet(new ServletHolder(TestServlet.class), "/bar");
host = "localhost";
port = getLocalPort();
server.getConnectors()[0].setHost(host);
server.getConnectors()[0].setPort(port);
server.start();
System.out.println("Running embedded servlet container at: http://" + host + ":" + port);
}
protected void startTomcat() throws Exception {
tomcat = new Tomcat();
File base = new File(System.getProperty("java.io.tmpdir"));
org.apache.catalina.Context ctx =
tomcat.addContext("/foo",base.getAbsolutePath());
FilterDef fd = new FilterDef();
fd.setFilterClass(TestFilter.class.getName());
fd.setFilterName("TestFilter");
FilterMap fm = new FilterMap();
fm.setFilterName("TestFilter");
fm.addURLPattern("/*");
fm.addServletName("/bar");
ctx.addFilterDef(fd);
ctx.addFilterMap(fm);
tomcat.addServlet(ctx, "/bar", TestServlet.class.getName());
ctx.addServletMapping("/bar", "/bar");
host = "localhost";
port = getLocalPort();
tomcat.setHostname(host);
tomcat.setPort(port);
tomcat.start();
}
protected void stop() throws Exception {
if (useTomcat) stopTomcat();
else stopJetty();
}
protected void stopJetty() throws Exception {
try {
server.stop();
} catch (Exception e) {
}
try {
server.destroy();
} catch (Exception e) {
}
}
protected void stopTomcat() throws Exception {
try {
tomcat.stop();
} catch (Exception e) {
}
try {
tomcat.destroy();
} catch (Exception e) {
}
}
protected String getBaseURL() {
return "http://" + host + ":" + port + "/foo/bar";
}
private static class TestConnectionConfigurator
implements ConnectionConfigurator {
boolean invoked;
@Override
public HttpURLConnection configure(HttpURLConnection conn)
throws IOException {
invoked = true;
return conn;
}
}
private String POST = "test";
protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
URL url = new URL(getBaseURL());
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
Assert.assertFalse(token.isSet());
TestConnectionConfigurator connConf = new TestConnectionConfigurator();
AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf);
HttpURLConnection conn = aUrl.openConnection(url, token);
Assert.assertTrue(connConf.invoked);
String tokenStr = token.toString();
if (doPost) {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.connect();
if (doPost) {
Writer writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(POST);
writer.close();
}
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
if (doPost) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String echo = reader.readLine();
Assert.assertEquals(POST, echo);
Assert.assertNull(reader.readLine());
}
aUrl = new AuthenticatedURL();
conn = aUrl.openConnection(url, token);
conn.connect();
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
Assert.assertEquals(tokenStr, token.toString());
} finally {
stop();
}
}
private SystemDefaultHttpClient getHttpClient() {
final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY, use_jaas_creds);
return httpClient;
}
private void doHttpClientRequest(HttpClient httpClient, HttpUriRequest request) throws Exception {
HttpResponse response = null;
try {
response = httpClient.execute(request);
final int httpStatus = response.getStatusLine().getStatusCode();
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpStatus);
} finally {
if (response != null) EntityUtils.consumeQuietly(response.getEntity());
}
}
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
SystemDefaultHttpClient httpClient = getHttpClient();
doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));
// Always do a GET before POST to trigger the SPNego negotiation
if (doPost) {
HttpPost post = new HttpPost(getBaseURL());
byte [] postBytes = POST.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);
// Important that the entity is not repeatable -- this means if
// we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
// the test will fail.
Assert.assertFalse(entity.isRepeatable());
post.setEntity(entity);
doHttpClientRequest(httpClient, post);
}
} finally {
stop();
}
}
}
| 9,577 | 31.14094 | 115 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestAuthToken.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.util;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.junit.Assert;
import org.junit.Test;
public class TestAuthToken {
@Test
public void testConstructor() throws Exception {
try {
new AuthToken(null, "p", "t");
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
try {
new AuthToken("", "p", "t");
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
try {
new AuthToken("u", null, "t");
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
try {
new AuthToken("u", "", "t");
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
try {
new AuthToken("u", "p", null);
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
try {
new AuthToken("u", "p", "");
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
new AuthToken("u", "p", "t");
}
@Test
public void testGetters() throws Exception {
long expires = System.currentTimeMillis() + 50;
AuthToken token = new AuthToken("u", "p", "t");
token.setExpires(expires);
Assert.assertEquals("u", token.getUserName());
Assert.assertEquals("p", token.getName());
Assert.assertEquals("t", token.getType());
Assert.assertEquals(expires, token.getExpires());
Assert.assertFalse(token.isExpired());
Thread.sleep(70); // +20 msec fuzz for timer granularity.
Assert.assertTrue(token.isExpired());
}
@Test
public void testToStringAndParse() throws Exception {
long expires = System.currentTimeMillis() + 50;
AuthToken token = new AuthToken("u", "p", "t");
token.setExpires(expires);
String str = token.toString();
token = AuthToken.parse(str);
Assert.assertEquals("p", token.getName());
Assert.assertEquals("t", token.getType());
Assert.assertEquals(expires, token.getExpires());
Assert.assertFalse(token.isExpired());
Thread.sleep(70); // +20 msec fuzz for timer granularity.
Assert.assertTrue(token.isExpired());
}
@Test
public void testParseValidAndInvalid() throws Exception {
long expires = System.currentTimeMillis() + 50;
AuthToken token = new AuthToken("u", "p", "t");
token.setExpires(expires);
String ostr = token.toString();
String str1 = "\"" + ostr + "\"";
AuthToken.parse(str1);
String str2 = ostr + "&s=1234";
AuthToken.parse(str2);
String str = ostr.substring(0, ostr.indexOf("e="));
try {
AuthToken.parse(str);
Assert.fail();
} catch (AuthenticationException ex) {
// Expected
} catch (Exception ex) {
Assert.fail();
}
}
}
| 3,766 | 28.429688 | 80 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestJaasConfiguration.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.util;
import java.util.Map;
import javax.security.auth.login.AppConfigurationEntry;
import org.junit.Assert;
import org.junit.Test;
public class TestJaasConfiguration {
// We won't test actually using it to authenticate because that gets messy and
// may conflict with other tests; but we can test that it otherwise behaves
// correctly
@Test
public void test() throws Exception {
String krb5LoginModuleName;
if (System.getProperty("java.vendor").contains("IBM")) {
krb5LoginModuleName = "com.ibm.security.auth.module.Krb5LoginModule";
} else {
krb5LoginModuleName = "com.sun.security.auth.module.Krb5LoginModule";
}
ZKSignerSecretProvider.JaasConfiguration jConf =
new ZKSignerSecretProvider.JaasConfiguration("foo", "foo/localhost",
"/some/location/foo.keytab");
AppConfigurationEntry[] entries = jConf.getAppConfigurationEntry("bar");
Assert.assertNull(entries);
entries = jConf.getAppConfigurationEntry("foo");
Assert.assertEquals(1, entries.length);
AppConfigurationEntry entry = entries[0];
Assert.assertEquals(AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
entry.getControlFlag());
Assert.assertEquals(krb5LoginModuleName, entry.getLoginModuleName());
Map<String, ?> options = entry.getOptions();
Assert.assertEquals("/some/location/foo.keytab", options.get("keyTab"));
Assert.assertEquals("foo/localhost", options.get("principal"));
Assert.assertEquals("true", options.get("useKeyTab"));
Assert.assertEquals("true", options.get("storeKey"));
Assert.assertEquals("false", options.get("useTicketCache"));
Assert.assertEquals("true", options.get("refreshKrb5Config"));
Assert.assertEquals(6, options.size());
}
}
| 2,410 | 42.053571 | 80 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestFileSignerSecretProvider.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.util;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Properties;
public class TestFileSignerSecretProvider {
@Test
public void testGetSecrets() throws Exception {
File testDir = new File(System.getProperty("test.build.data",
"target/test-dir"));
testDir.mkdirs();
String secretValue = "hadoop";
File secretFile = new File(testDir, "http-secret.txt");
Writer writer = new FileWriter(secretFile);
writer.write(secretValue);
writer.close();
FileSignerSecretProvider secretProvider
= new FileSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET_FILE,
secretFile.getAbsolutePath());
secretProvider.init(secretProviderProps, null, -1);
Assert.assertArrayEquals(secretValue.getBytes(),
secretProvider.getCurrentSecret());
byte[][] allSecrets = secretProvider.getAllSecrets();
Assert.assertEquals(1, allSecrets.length);
Assert.assertArrayEquals(secretValue.getBytes(), allSecrets[0]);
}
}
| 1,902 | 35.596154 | 77 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestSigner.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.util;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.junit.Assert;
import org.junit.Test;
public class TestSigner {
@Test
public void testNullAndEmptyString() throws Exception {
Signer signer = new Signer(createStringSignerSecretProvider());
try {
signer.sign(null);
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
try {
signer.sign("");
Assert.fail();
} catch (IllegalArgumentException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
}
@Test
public void testSignature() throws Exception {
Signer signer = new Signer(createStringSignerSecretProvider());
String s1 = signer.sign("ok");
String s2 = signer.sign("ok");
String s3 = signer.sign("wrong");
Assert.assertEquals(s1, s2);
Assert.assertNotEquals(s1, s3);
}
@Test
public void testVerify() throws Exception {
Signer signer = new Signer(createStringSignerSecretProvider());
String t = "test";
String s = signer.sign(t);
String e = signer.verifyAndExtract(s);
Assert.assertEquals(t, e);
}
@Test
public void testInvalidSignedText() throws Exception {
Signer signer = new Signer(createStringSignerSecretProvider());
try {
signer.verifyAndExtract("test");
Assert.fail();
} catch (SignerException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
}
@Test
public void testTampering() throws Exception {
Signer signer = new Signer(createStringSignerSecretProvider());
String t = "test";
String s = signer.sign(t);
s += "x";
try {
signer.verifyAndExtract(s);
Assert.fail();
} catch (SignerException ex) {
// Expected
} catch (Throwable ex) {
Assert.fail();
}
}
private StringSignerSecretProvider createStringSignerSecretProvider() throws Exception {
StringSignerSecretProvider secretProvider = new StringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, -1);
return secretProvider;
}
@Test
public void testMultipleSecrets() throws Exception {
TestSignerSecretProvider secretProvider = new TestSignerSecretProvider();
Signer signer = new Signer(secretProvider);
secretProvider.setCurrentSecret("secretB");
String t1 = "test";
String s1 = signer.sign(t1);
String e1 = signer.verifyAndExtract(s1);
Assert.assertEquals(t1, e1);
secretProvider.setPreviousSecret("secretA");
String t2 = "test";
String s2 = signer.sign(t2);
String e2 = signer.verifyAndExtract(s2);
Assert.assertEquals(t2, e2);
Assert.assertEquals(s1, s2); //check is using current secret for signing
secretProvider.setCurrentSecret("secretC");
secretProvider.setPreviousSecret("secretB");
String t3 = "test";
String s3 = signer.sign(t3);
String e3 = signer.verifyAndExtract(s3);
Assert.assertEquals(t3, e3);
Assert.assertNotEquals(s1, s3); //check not using current secret for signing
String e1b = signer.verifyAndExtract(s1);
Assert.assertEquals(t1, e1b); // previous secret still valid
secretProvider.setCurrentSecret("secretD");
secretProvider.setPreviousSecret("secretC");
try {
signer.verifyAndExtract(s1); // previous secret no longer valid
Assert.fail();
} catch (SignerException ex) {
// Expected
}
}
class TestSignerSecretProvider extends SignerSecretProvider {
private byte[] currentSecret;
private byte[] previousSecret;
@Override
public void init(Properties config, ServletContext servletContext,
long tokenValidity) {
}
@Override
public byte[] getCurrentSecret() {
return currentSecret;
}
@Override
public byte[][] getAllSecrets() {
return new byte[][]{currentSecret, previousSecret};
}
public void setCurrentSecret(String secretStr) {
currentSecret = secretStr.getBytes();
}
public void setPreviousSecret(String previousSecretStr) {
previousSecret = previousSecretStr.getBytes();
}
}
}
| 5,034 | 29.70122 | 90 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestStringSignerSecretProvider.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.util;
import java.util.Properties;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.junit.Assert;
import org.junit.Test;
public class TestStringSignerSecretProvider {
@Test
public void testGetSecrets() throws Exception {
String secretStr = "secret";
StringSignerSecretProvider secretProvider
= new StringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, -1);
byte[] secretBytes = secretStr.getBytes();
Assert.assertArrayEquals(secretBytes, secretProvider.getCurrentSecret());
byte[][] allSecrets = secretProvider.getAllSecrets();
Assert.assertEquals(1, allSecrets.length);
Assert.assertArrayEquals(secretBytes, allSecrets[0]);
}
}
| 1,541 | 38.538462 | 77 |
java
|
hadoop
|
hadoop-master/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/StringSignerSecretProviderCreator.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.util;
import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.classification.InterfaceStability;
/**
* Helper class for creating StringSignerSecretProviders in unit tests
*/
@InterfaceStability.Unstable
@VisibleForTesting
public class StringSignerSecretProviderCreator {
/**
* @return a new StringSignerSecretProvider
* @throws Exception
*/
public static StringSignerSecretProvider newStringSignerSecretProvider()
throws Exception {
return new StringSignerSecretProvider();
}
}
| 1,174 | 33.558824 | 75 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.