+ All Categories
Home > Documents > Gambit - CiteSeerX

Gambit - CiteSeerX

Date post: 10-Nov-2023
Category:
Upload: khangminh22
View: 0 times
Download: 0 times
Share this document with a friend
218
Gambit Software Tools for Game Theory Richard McKelvey California Institute of Technology Andrew McLennan University of Minnesota Theodore Turocy Texas A&M University
Transcript

Gambit

Software Tools for Game Theory

Richard McKelveyCalifornia Institute of Technology

Andrew McLennanUniversity of Minnesota

Theodore TurocyTexas A&M University

Gambit: Software Tools for Game Theoryby Richard McKelvey, Andrew McLennan, and Theodore Turocy

Version 0.97.0 EditionPublished 2002Copyright © 2002 The Gambit Project

Table of Contents1. Introduction .............................................................................................................................................................??

1.1. History and acknowledgements....................................................................................................................??1.2. Gambit versions and version numbers.........................................................................................................??1.3. Gambit release history..................................................................................................................................??1.4. Getting and installing Gambit......................................................................................................................??1.5. Contacting or contributing to the Gambit Project........................................................................................??1.6. About this manual........................................................................................................................................??

2. Getting Started with the Graphical Interface ......................................................................................................??

2.1. A simple game of poker...............................................................................................................................??2.2. Finding Nash equilibria using the extensive form........................................................................................??2.3. Finding Nash equilibria using the normal form...........................................................................................??

3. How do I do X with the graphical interface?........................................................................................................??

3.1. How can I use Gambit to make figures of my games?.................................................................................??3.2. How do I get payoffs into my game?...........................................................................................................??3.3. How do I get Gambit to compute equilibria in my game?...........................................................................??3.4. How do I manage the strategy profiles Gambit has computed?...................................................................??3.5. What’s a support, and what is it good for?...................................................................................................??3.6. How do I change the layout of a game tree?................................................................................................??

4. The Gambit Command Language.........................................................................................................................??

4.1. Introduction to the command language........................................................................................................??4.1.1. Command line editing......................................................................................................................??4.1.2. Meaning of the prompt....................................................................................................................??

4.2. Basic concepts..............................................................................................................................................??4.3. Data types.....................................................................................................................................................??

4.3.1. Boolean............................................................................................................................................??4.3.2. Numeric data types..........................................................................................................................??4.3.3. Text..................................................................................................................................................??4.3.4. Input and output...............................................................................................................................??4.3.5. Normal form data types...................................................................................................................??4.3.6. Extensive form data types................................................................................................................??4.3.7. Lists..................................................................................................................................................??4.3.8. Conglomerate data types..................................................................................................................??

4.4. Expressions...................................................................................................................................................??4.5. Functions......................................................................................................................................................??

4.5.1. Constants..........................................................................................................................................??4.5.2. Variables..........................................................................................................................................??4.5.3. Built-in functions.............................................................................................................................??4.5.4. User-defined functions.....................................................................................................................??4.5.5. Aliases for function calls.................................................................................................................??

4.6. Getting and suppressing console output.......................................................................................................??4.7. Lists..............................................................................................................................................................??

4.7.1. Building and modifying lists...........................................................................................................??4.8. Listability of functions.................................................................................................................................??4.9. Online documentation..................................................................................................................................??4.10. Advanced topics.........................................................................................................................................??

iii

4.10.1. Including files................................................................................................................................??4.10.2. Flow control structures..................................................................................................................??4.10.3. Input and output.............................................................................................................................??4.10.4. Null values.....................................................................................................................................??4.10.5. System information........................................................................................................................??4.10.6. Variables pointing to deleted objects.............................................................................................??4.10.7. Errors.............................................................................................................................................??

4.11. Constructing and manipulating games.......................................................................................................??4.11.1. Normal form games.......................................................................................................................??4.11.2. Extensive forms.............................................................................................................................??4.11.3. Solving games................................................................................................................................??4.11.4. Supports and dominance elimination.............................................................................................??4.11.5. Subgames.......................................................................................................................................??4.11.6. Mixed and behavior strategy profiles.............................................................................................??

5. Command Language Function Reference............................................................................................................??

5.1. Built-in functions..........................................................................................................................................??Accuracy....................................................................................................................................................??ActionNumber...........................................................................................................................................??ActionProb.................................................................................................................................................??Actions.......................................................................................................................................................??ActionValue...............................................................................................................................................??AddAction..................................................................................................................................................??AddMove...................................................................................................................................................??AddNode....................................................................................................................................................??AddStrategy...............................................................................................................................................??AgentForm.................................................................................................................................................??And ............................................................................................................................................................??ArgMax......................................................................................................................................................??Assign........................................................................................................................................................??Basis...........................................................................................................................................................??Behav.........................................................................................................................................................??Behav.........................................................................................................................................................??Belief..........................................................................................................................................................??Chance.......................................................................................................................................................??ChanceProb................................................................................................................................................??Children.....................................................................................................................................................??Clear...........................................................................................................................................................??Comment....................................................................................................................................................??CompressEfg..............................................................................................................................................??CompressNfg.............................................................................................................................................??Concat........................................................................................................................................................??Contains.....................................................................................................................................................??CopyTree...................................................................................................................................................??Creator.......................................................................................................................................................??Date............................................................................................................................................................??DeleteAction..............................................................................................................................................??DeleteEmptyInfoset...................................................................................................................................??

iv

DeleteMove................................................................................................................................................??DeleteOutcome..........................................................................................................................................??DeleteTree..................................................................................................................................................??Divide.........................................................................................................................................................??Dot .............................................................................................................................................................??ElapsedTime..............................................................................................................................................??EnumMixedSolve......................................................................................................................................??EnumPureSolve.........................................................................................................................................??Equal..........................................................................................................................................................??ExePath......................................................................................................................................................??Exp.............................................................................................................................................................??Filter...........................................................................................................................................................??Flatten........................................................................................................................................................??Float...........................................................................................................................................................??For..............................................................................................................................................................??Format........................................................................................................................................................??Game..........................................................................................................................................................??GetEnv.......................................................................................................................................................??GetFormat..................................................................................................................................................??GetListFormat............................................................................................................................................??GetPath......................................................................................................................................................??Greater.......................................................................................................................................................??GreaterEqual..............................................................................................................................................??Help............................................................................................................................................................??HelpVars....................................................................................................................................................??If .................................................................................................................................................................??Include.......................................................................................................................................................??Index..........................................................................................................................................................??Infoset........................................................................................................................................................??InfosetProb.................................................................................................................................................??Infosets.......................................................................................................................................................??InfosetValue...............................................................................................................................................??Input...........................................................................................................................................................??InsertAction...............................................................................................................................................??InsertMove.................................................................................................................................................??Integer........................................................................................................................................................??IntegerDivide.............................................................................................................................................??Inverse........................................................................................................................................................??IsConsistent................................................................................................................................................??IsConstSum................................................................................................................................................??IsDefined....................................................................................................................................................??IsDominated...............................................................................................................................................??IsEof...........................................................................................................................................................??IsList ..........................................................................................................................................................??IsNash........................................................................................................................................................??IsNull .........................................................................................................................................................??IsPerfect.....................................................................................................................................................??IsPerfectRecall...........................................................................................................................................??

v

IsPredecessor.............................................................................................................................................??IsSequential................................................................................................................................................??IsSubgamePerfect......................................................................................................................................??IsSuccessor................................................................................................................................................??IsWatchRunning.........................................................................................................................................??LcpSolve....................................................................................................................................................??Length........................................................................................................................................................??Less............................................................................................................................................................??LessEqual...................................................................................................................................................??LiapSolve...................................................................................................................................................??LiapValue...................................................................................................................................................??List .............................................................................................................................................................??ListFormat..................................................................................................................................................??LoadEfg.....................................................................................................................................................??LoadNfg.....................................................................................................................................................??Log.............................................................................................................................................................??LpSolve......................................................................................................................................................??Manual.......................................................................................................................................................??MarkSubgame............................................................................................................................................??MarkedSubgame........................................................................................................................................??Members....................................................................................................................................................??MergeInfosets............................................................................................................................................??Minus.........................................................................................................................................................??Mixed.........................................................................................................................................................??Modulus.....................................................................................................................................................??MoveToInfoset...........................................................................................................................................??MoveTree...................................................................................................................................................??Name..........................................................................................................................................................??Negate........................................................................................................................................................??NewEfg......................................................................................................................................................??NewFunction..............................................................................................................................................??NewInfoset.................................................................................................................................................??NewNfg......................................................................................................................................................??NewOutcome.............................................................................................................................................??NewPlayer..................................................................................................................................................??NextSibling................................................................................................................................................??Nfg .............................................................................................................................................................??NodeNumber..............................................................................................................................................??NodeValue..................................................................................................................................................??Nodes.........................................................................................................................................................??Not .............................................................................................................................................................??NotEqual....................................................................................................................................................??NthChar......................................................................................................................................................??NthChild ....................................................................................................................................................??NthElement................................................................................................................................................??Null ............................................................................................................................................................??NumChars..................................................................................................................................................??NumElements............................................................................................................................................??

vi

Or...............................................................................................................................................................??Outcome.....................................................................................................................................................??Outcomes...................................................................................................................................................??Output........................................................................................................................................................??Parent.........................................................................................................................................................??Parentheses................................................................................................................................................??Payoff.........................................................................................................................................................??Platform.....................................................................................................................................................??Player.........................................................................................................................................................??Players........................................................................................................................................................??Plus............................................................................................................................................................??PolEnumSolve...........................................................................................................................................??PossibleNashSupports................................................................................................................................??Power.........................................................................................................................................................??Precision....................................................................................................................................................??Print............................................................................................................................................................??PriorAction................................................................................................................................................??PriorSibling................................................................................................................................................??QreGridSolve.............................................................................................................................................??QreLambda................................................................................................................................................??QreSolve....................................................................................................................................................??Quit ............................................................................................................................................................??Randomize.................................................................................................................................................??Rational......................................................................................................................................................??Read...........................................................................................................................................................??ReadText....................................................................................................................................................??RealizProb..................................................................................................................................................??Regret.........................................................................................................................................................??Regrets.......................................................................................................................................................??Remove......................................................................................................................................................??RemoveAction...........................................................................................................................................??RemoveNode.............................................................................................................................................??RemoveStrategy.........................................................................................................................................??Reveal........................................................................................................................................................??RootNode...................................................................................................................................................??SaveEfg......................................................................................................................................................??SaveNfg.....................................................................................................................................................??SequenceForm...........................................................................................................................................??SequenceFormConstraints.........................................................................................................................??SequenceFormStrats..................................................................................................................................??SetActionProb............................................................................................................................................??SetActionProbs..........................................................................................................................................??SetChanceProbs.........................................................................................................................................??SetComment..............................................................................................................................................??SetEnv........................................................................................................................................................??SetName.....................................................................................................................................................??SetOutcome................................................................................................................................................??SetPayoff....................................................................................................................................................??

vii

SetStrategyProb.........................................................................................................................................??SetStrategyProbs........................................................................................................................................??Shell...........................................................................................................................................................??SimpDivSolve............................................................................................................................................??Sort.............................................................................................................................................................??StartWatch..................................................................................................................................................??StopWatch..................................................................................................................................................??Strategies....................................................................................................................................................??StrategyNumber.........................................................................................................................................??StrategyProb..............................................................................................................................................??StrategyProbs.............................................................................................................................................??StrategyValue.............................................................................................................................................??StrategyValues...........................................................................................................................................??Subgames...................................................................................................................................................??Support.......................................................................................................................................................??Text............................................................................................................................................................??Times.........................................................................................................................................................??Transpose...................................................................................................................................................??UnAssign...................................................................................................................................................??UnDominated.............................................................................................................................................??UnMarkSubgame.......................................................................................................................................??UnSetEnv...................................................................................................................................................??Version.......................................................................................................................................................??While..........................................................................................................................................................??Write ..........................................................................................................................................................??WriteSequenceForm..................................................................................................................................??

5.2. Categorical listing of functions....................................................................................................................??5.2.1. General functionality.......................................................................................................................??5.2.2. Basic data types...............................................................................................................................??5.2.3. Input and output...............................................................................................................................??5.2.4. Building games................................................................................................................................??5.2.5. Solving games..................................................................................................................................??

A. Reference: Algorithms to Compute Nash Equilibria..........................................................................................??

A.1. Tips on getting started.................................................................................................................................??A.1.1. Common algorithm parameters......................................................................................................??A.1.2. Pure strategy equilibria...................................................................................................................??A.1.3. Two Person Constant Sum Games..................................................................................................??A.1.4. Two Person Games.........................................................................................................................??A.1.5. Games With More Than Two Players.............................................................................................??A.1.6. Sequential Equilibria.......................................................................................................................??

A.2. EnumMixedSolve........................................................................................................................................??A.3. EnumPureSolve...........................................................................................................................................??A.4. QreSolve......................................................................................................................................................??A.5. QreGridSolve...............................................................................................................................................??A.6. LcpSolve......................................................................................................................................................??A.7. LiapSolve.....................................................................................................................................................??A.8. LpSolve........................................................................................................................................................??

viii

A.9. PolEnumSolve.............................................................................................................................................??A.10. SimpDivSolve............................................................................................................................................??

B. A GCL program to build and solve the holdout game........................................................................................??

Bibliography ................................................................................................................................................................??

Index.............................................................................................................................................................................??

ix

List of Tables4-1. Data types in GCL.................................................................................................................................................??4-2. Conglomerate types in GCL..................................................................................................................................??4-3. Function types........................................................................................................................................................??4-4. Constants...............................................................................................................................................................??4-5. Operators in GCL..................................................................................................................................................??4-6. Order of precedence...............................................................................................................................................??4-7. Overview of normal form manipulation functions................................................................................................??4-8. Overview of functions on extensive forms............................................................................................................??4-9. Functions for modifying extensive form games....................................................................................................??

x

Chapter 1. Introduction

An introduction to Gambit

1.1. History and acknowledgements

The Gambit Project is a project for the development of computer code for the solution of extensive and normal formgames. The software developed under the project is distributed under the GNU General Public License. The GambitProject has been funded in the past by National Science Foundation grants SBR-9308637 and SBR-9617854 to theCalifornia Institute of Technology and SBR-9308862 to the University of Minnesota.

The Gambit Project was founded in the mid-1980s by Richard McKelvey. The original implementation was agraphical interface written in BASIC. The code was ported to C around 1990 with the help of Bruce Bell, and thisversion was distributed publicly as version 0.13 in 1991 and 1992.

A major step in the evolution of Gambit took place with the awarding of the NSF grants in 1994, with McKelvey andAndrew McLennan as principal investigators. The grants sponsored a complete rewrite of Gambit in C++, with thecode taking essentially the organization it has today. The graphical interface was made portable across platformsthrough the use of the wxWindows library (http://www.wxwindows.org), and a scripting language, the GambitCommand Language, was developed. Version 0.94 of Gambit was released in the late summer of 1994, and version0.96 followed in 1999.

Many other individuals have contributed to the project, by coding, documenting, and testing, especially students atCaltech and the University of Minnesota. We wish to acknowledge their contributions alphabetically here:

Bruce Bell Todd KaplanAnand Chelian Geoff MattersMatthew Derer Brian TrotterNelson Escobar Michael VanierBen Freeman Roberto WeberEugene Grayver Gary Wu

The project especially wishes to thank Bernhard von Stengel, of the London School of Economics, for help andadvice on implementation of the sequence form and for contributing his "clique" code for identification ofequilibrium components in two person games.

Version 0.97.0.1 of Gambit was released on September 1, 2002. This release featured

• A completely redesigned graphical user interface, built with the wxWindows 2.3.2 cross-platform toolkit. Previousreleases of Gambit used the older 1.xx series of wxWindows. The new version provides substantially greaterfunctionality and stability. The interface redesign should make many game creation tasks easier.

• An implementation of a new algorithm for computing the logistic quantal response equilibrium correspondence, asdescribed in [Tur02]. This algorithm is now essentially unlimited in the size of lambda it can compute, and is

1

Chapter 1. Introduction

much faster than the previous implementation provided by Gambit. This algorithm is now recommended forcomputing one Nash equilibrium, especially in games with more than two players.

• A new function minimization implementation, derived from that available in the GNU Scientific Library, is used inthe Lyapunov function minimization algorithm (LiapSolve ). It appears this implementation is at least somewhatsuperior to that provided in previous versions.

• The command language interface for Windows has been replaced with a new one built with wxWindows.Additionally, this windowed interface is also available under *nix (called wxgcl).

1.2. Gambit versions and version numbers

Beginning with version 0.97, Gambit versions will be numbered in the form0.x.y.z , wherex is the "major"version number,y is the "minor" version number, andz is the "micro" (or "patch") version number. The initial zeroin the version number is there for historical reasons. Gambit follows the Linux kernel numbering style: releasesdeemed "stable" will have even minor version numbers, and releases deemed "unstable" will have odd minor versionnumbers. So, version 0.97.0.1 is the first release in the stable 0.97.0 series; version 0.97.1.1 will be the first release inthe unstable 0.97.1 series.

The goal is to release a new initial stable version in a series on a schedule roughly corresponding to the academicyear (at least, for those on the semester system), for the benefit of those who like to use Gambit for instructionalpurposes. So, for example, version 0.97.0.1 was released on September 1, 2002; this is a stable release, and anyfuture releases of 0.97.0.z will correspond to bug fixes and patches. At some point in the fall, releases numbered0.97.1.z will begin to appear; these will contain relatively major innovations and changes relative to the 0.97.0 series.Finally, when the 0.97.1 series stabilizes, it will be released, hopefully over the holidays, as version 0.97.2.0.

Which version of Gambit you should use depends on your needs. For classroom use, we’d certainly recommend thecurrent stable version, since nothing will frustrate your students faster than having the program crash on them in themiddle of their homework. For research use, you may find either of them appropriate; while the "unstable" seriesmight be a bit buggy, it may also have some features you’ll find useful. Finally, if you’re interested in contributing toGambit, you’ll definitely want to work with the unstable series, since that represents the latest-and-greatest on thebleeding edge of computational game theory development.

1.3. Gambit release history

This is an outline of the release history of Gambit (at least in the "postmodern" era beginning with release 0.97.0.1).

• Version 0.97.0.1, released September 1, 2002: Initial public release, with rebuilt graphical interface, newimplementations ofQreSolve andLiapSolve , and a new windowed interface for the command language.

2

Chapter 1. Introduction

1.4. Getting and installing Gambit

The development and testing of Gambit takes place primarily on the following platforms:

• Microsoft Windows 95, 98 and NT, using the free Borland C++ 5.5 compiler. The binary distributions forWindows should work on other versions of Windows, but may not be tested. Reports are always welcome.

• RedHat Linux 6.x and 7.x, using wxWindows, the GTK toolkit and gcc. The wxWindows library also supportsMotif/Lesstif, and the code should compile on other flavors of Linux and Unix; again, however, these may not betested. Again, reports are always welcome.

The latest stable and unstable releases of Gambit can always be found at the Gambit website athttp://www.hss.caltech.edu/gambit. You can build Gambit from source, in which case you will need one of thecompilers mentioned above, and the appropriate version of wxWindows. Build instructions are found in the fileINSTALL in the main directory of the source distribution. Gambit is also distributed in binary form for Windows, inwhich case you don’t need the compiler or wxWindows installed. There currently are not any prebuilt binaries for*nix.

Important: If you build the wxWindows libraries on *nix, make sure to grab the correct version for the toolkityou’re using. Gambit is currently tested using wxGTK. You should also be able to build using the wxMotif port, butwe currently have no reports whether or not this works correctly. Make sure you don’t get the base librarywxBase; this does not contain the GUI classes needed to build the Gambit graphical interfaces.

1.5. Contacting or contributing to the Gambit Project

All email correspondence to the Gambit Project can be addressed togambit (at) hss (dot) caltech (dot)

edu . We welcome all manner of suggestions, including feature requests, documentation improvements, bug reports,bug fixes, and interest in contributing new code to the Gambit library.

If you encounter a bug in Gambit, we want to hear about it. It will be most helpful if, in reporting your problem, youinclude the following information:

1. The version number

2. The platform(s) on which you experienced the problem

3. As complete a description of the circumstances of the problem as possible. It is especially helpful if you canprovide a sequence of steps which reproduces the problem.

Mailing lists also exist for getting information about Gambit. See the Gambit website for details.

3

Chapter 1. Introduction

Should you need to contact the Gambit developers by physical mail, send your correspondence to

The Gambit Projectc/o Prof. Theodore TurocyDepartment of EconomicsTexas A&M UniversityCollege Station, TX 77843

1.6. About this manual

This manual is written with the assumption the reader is familiar with the basic terms and concepts of game theory.Where possible, Gambit uses terminology standard in game theory; definitions of game-theoretic concepts will onlybe introduced where confusion may occur. Game theory novices should supplement this manual with a standard texton the topic; a list of some of these is given in thebibliography.

Beginning with version 0.97, the Gambit manual is written using DocBook. This manual can always be browsedonline at the Gambit website, and can be downloaded in HTML and PDF formats for local use.

Changes from previous versions:This manual, particularly the graphical interface sections, has been substantiallyoverhauled since the last release. As a result, it is still in flux. Please report any areas in which the manual isunclear or lacking to the Gambit address.

Throughout the manual, changes from previous versions are highlighted in notes, such as this one.

4

Chapter 2. Getting Started with the GraphicalInterface

This section gives a quick overview of the graphical interface, using a simplified game of poker to illustrate the mainfeatures and concepts.

2.1. A simple game of poker

This chapter takes a high-level tour of the Gambit graphical interface using as an example the simple one-card pokergame appearing in [Mye91]. This game is included in the Gambit distribution aspoker.efg , and can be found intheefg subdirectory of the directory in which Gambit is installed. (For example, in the standard installation underMicrosoft Windows, this would bec:/Program Files/Gambit/efg/poker.efg .) By convention, files ending in.efg store extensive form games, and files ending in.nfg store normal form games.

When launched, Gambit displays a window similar to this:1

5

Chapter 2. Getting Started with the Graphical Interface

6

Chapter 2. Getting Started with the Graphical Interface

This window contains a trivial extensive form game, containing exactly one node, which is both root and terminal.

There are three equivalent ways to open a saved game from any window in Gambit:

1. Select theOpen menu item from theFile menu;

2. Use the shortcut key combinationCtrl -O;

3. Click on the file folder icon on the toolbar.

Any of these actions leads to a dialog box for selecting a file to open. Use the dialog to locate and select thepoker.efg file. After doing so, Gambit will display the opened game in a new window:

7

Chapter 2. Getting Started with the Graphical Interface

8

Chapter 2. Getting Started with the Graphical Interface

The screenshot shows the game as rendered by Gambit using the default settings. Many display options are availableto customize the appearance of game trees; see theFormat menu to parameterize the layout.

The extensive form game tree is drawn with the root node at far left, with branches going from left to right, andsuccessive nodes to the right of their predecessors. Each node is represented as a horizontal line. Every non-terminalnode is a decision node and is represented by the color of the player who makes a decision at that node. Nodes areconnected by branches, which are represented by two connected line segments, which can be thought of as the "fork"and the "tine". The fork is used in the graphics display to indicate graphically the probabilities of taking each branch.The tine is used as a location at which to display textual information about the branch.

The poker game begins with Chance selecting either a Red card or a Black card to deal to Player 1. This isrepresented in the tree by the grey node and subsequent branches labeled "Red" and "Black". The forks of thebranches have superimposed black lines stretching halfway along the fork, indicating a probability of one-half thateach card is chosen. After each of the two possible draws, Player 1, whose nodes are colored in red, has the option toeither "Raise" or "Fold". If Player 1 folds, the game ends; if he raises, Player2, with nodes colored in blue, then hasthe option to either "Meet" or "Pass" in either case, the game ends after Player 2’s choice. All terminal nodes aredrawn in black in this picture.

In this game, outcomes are attached to each of the six terminal nodes, and payoffs to the two players are indicated tothe right of the corresponding node, with Player 1’s payoff listed first, then Player 2’s. Outcomes are indicated to theright of nodes, but may be attached to nonterminal nodes, in which case their payoffs are interpreted as incrementalpayoffs. Outcomes may also be displayed by textual name rather than by their payoff vector.

Information sets are identified by a pair of numbers. The first number indicates the number of the player who has thechoice at the information set. The second number provides an identifying number for the information set which isunique among that player’s information sets. Whenever possible, information sets are also represented by verticallines connecting the nodes that are members of the same information set. In this game, Player 1 observes which cardhe has drawn prior to making his choice to "Raise" or "Fold" ; therefore, the node following Chance’s "Red" move isin a separate information set, numbered (1,1), from the node following Chance’s "Black" move, which is ininformation set (1,2). Player 2, on the other hand, does not observe Player 1’s card, and so Player 2 has oneinformation set, numbered (2,1), with two member nodes connected by a vertical line.

The analytical features of Gambit are located on theTools menu.

9

Chapter 2. Getting Started with the Graphical Interface

10

Chapter 2. Getting Started with the Graphical Interface

These include:

• Dominance, which interfaces to routines for identifying and eliminating dominanted actions;

• Equilibrium, which provedes access to algorithms provided by Gambit to compute Nash equilibria of the game;

• Qre, which organizes Gambit’s facilities for computing and manipulating quantal response equilibria;

• Normal form, which contains items to create normal forms corresponding to the extensive form game.

TheDominance, Equilibrium, andNormal form items will be discussed in the next sections.

2.2. Finding Nash equilibria using the extensive form

The analysis begins by searching for actions which might be dominated by other actions at the same move. TheDominance item on theTools menu presents a dialog box giving options for finding dominated actions:

There are four sets of options:

• Type: Actions can be removed based upon either strong (or strict) dominance, or weak dominance;

• Conditional: Chooses whether actions are considered dominated overall, or only conditional on their informationset being reached;

• Depth: One round of dominance elimination can be performed; or, Gambit can continue to eliminate strategiesuntil no more strategies are dominated;

• Players: Actions for all, or only some, of the players in the game may be considered in doing elimination.

In this example, we will look for one Nash equilibrium of this game, so we will conditionally eliminat weaklydominated strategies iteratively for all players, as shown in the screenshot.2

After clicking OK, a progress dialog briefly appears, and then the game display appears like this:

The action "Fold" is weakly dominated for Player 1 when he has the Red card; therefore, in this display, the "Fold"action is erased from the game tree.

Gambit keeps track of all the sets of actions computed. On theView menu is an itemSupports. Selecting this itemdisplays an additional panel on the extensive form display, as shown below. (You may need to resize your window abit to be able to see the whole tree as in this screenshot.)

11

Chapter 2. Getting Started with the Graphical Interface

TheSupports tab in the information pane on the left schematically displays the current support. The action "Fold" inFred’s first information set is light grey, indicating it is not in the support called "Support2". All other actions are inblack, indicating they are included in the support. The drop-down box at the top of the support display lists all thesupports that have been computed; if you click on it now, you’ll see the support "Full Support", which is the supportcontaining all actions for all players, and "Support2", the support we obtained by our dominance elimination. If youselect "Full Support" from the dropdown, the tree display will return to its original form, and the "Fold" action inFred’s first information set will appear in black in the schematic display.

To compute Nash equilibria for the game, use theEquilibrium item on theTools menu. This menu item shows adialog box listing the available algorithms for computing equilibria. The list of algorithms will vary depending on thegame, as some algorithms apply only to constant-sum games, or to games with two players. In this case, since thepoker game is a two-person constant-sum game, all the available algorithms are shown.

Algorithms are divided into two groups:

• Standard algorithms. These are algorithms and parameter settings chosen as being recommended for computingthe given number and type of equilibria shown.

• Custom algorithms. These are the actual algorithms implemented in Gambit. Selecting these displays acorresponding panel presenting the options available to configure the algorithm’s behavior.

For this example, select "one Nash equilibrium" which uses the sequence form formulation (the custom algorithmLcpSolve ) of Koller, Megiddo, and von Stengel [KolMegSte94] to compute one Nash equilibrium on the extensiveform.

After clicking OK, a progress box briefly appears. When the algorithm completes, the profiles panel is now shown atthe bottom of the tree window, with one profile shown. The profile is also displayed schematically on the game tree.The profiles panel presents information about the profile:

• Name: A label for the profile. This is automatically generated, and can be changed by double-clicking theprofile’s entry in the profile list to display theProperties dialog.

• Creator: The algorithm which created the profile, orUser if the profile was created or modified by the user.

• Nash: Indicates if the profile is a Nash equilibrium; in this case, this field displaysY to indicate it is.

• Perfect: Indicates if the profile is a subgame perfect Nash equilibrium; in this case, this field displaysY to indicateit is. (Since there are no proper subgames in this game, any Nash equilibrium must be subgame perfect.)

• Sequential: Indicates if the profile is a sequential Nash equilibrium; in this case, this field displaysDK to indicatethis is unknown. Some algorithms can be shown to compute only sequential equilibria, but there is noimplemented test for whether a given profile is sequential.

• Liap value: Displays the Lyapunov value (see [McK91]) of the profile. The Lyapunov value is zero exactly whenthe profile is a Nash equilibrium.

The remaining fields in the profile list display the probabilities assigned to each action by the profile. These arelabeled in the format(x,y):z, wherex gives the player number,y gives the information set number for the player, andz gives the action number at the information set.

12

Chapter 2. Getting Started with the Graphical Interface

In this case, the equilibrium involves Player 1, raising with probability one at his first information set, which followshis drawing the Red card. At his second information set, following a draw of a black card, he raises with probabilityone-third, and folds with probability two-thirds. Player 2, at her only information set, meets Player 1’s raise withprobability two-thirds, and passes with probability one-third.

These probabilities are represented schematically on the tree. At each information set, black segments proportional tothe probability each action is played are plotted along the branch for each action. Additionally, by default, actionprobabilities are shown below each branch. (Which labels are shown at nodes and actions can be customized usingthe dialog accessed from theLegends item on theDisplay submenu on theFormat menu.

Additional information about profiles is displayed on the navigation panel. This is displayed using theNavigationitem on theView menu. When a node is selected in the tree (by clicking on it, or by using arrow keys to navigate toit), this panel displays the following information computed from the profile:

• The node value: A vector of payoffs showing the expected payoff to each player, conditional on having reachedthis node in the play of the game.

• The probability the information set to which this node belongs is reached.

• The belief: the probability the choosing player assigns to being at this node, conditional on finding out he is at thisinformation set.

• The expected payoff of the choosing player, conditional on reaching this information set.

• The expected payoff of choosing the action which leads to this node, evaluated from the perspective of the playerwho chooses that action.

The custom algorithms available in the Nash equilibrium algorithm dialog give the option, where appropriate, ofusing the extensive form or normal form for computing equilibria. Therefore, one can compute equilibria usingnormal-form based algorithms without having to explicitly create and display the normal form of the game. The nextsection will cover how to view the normal form of the game, and how to compute Nash equilibria in mixed profiles.

2.3. Finding Nash equilibria using the normal form

Given an extensive form game, the (reduced) normal form is computed and displayed using theReduced item ontheNormal form submenu of theTools menu.

Notes1. All the screenshots contained in this manual were taken on a Linux system using the Sawfish window manager.

If you use a different operating system or window manager, your windows may appear slightly differently.

2. For an overview of tips and techniques for finding Nash equilibria, seeSection A.1.

13

Chapter 3. How do I do X with the graphicalinterface?

This section attempts to get you pointed in the right direction with the graphical interface, by answering somefrequently asked questions.

3.1. How can I use Gambit to make figures of my games?

In both the extensive and normal form game windows (normal form games starting with version 0.97.0.6) there is anExport submenu on theFile menu. These commands export the game to various graphical formats.

Four formats are available for extensive form games: BMP (Windows bitmaps), JPEG, PNG (portable networkgraphic), and PostScript. These export images of the game tree, laid out according the current settings. Theparameters for how the tree is laid out can be modified using the commands on theFormat menu.

For the raster output formats (BMP, JPEG, PNG), the output should closely match the layout depicted on the screen,except the output is not scaled according to the current zoom setting. PostScript output may vary slightly from theimage on the screen, but has the advantage of being more cleanly scalable.

Note: GIF images are not available due to patenting restrictions on the compression algorithm used in the GIF fileformat.

Two formats are available for normal form games. The game table can be exported as either a set of HTML tables, ora set of tables using Martin Osborne’s sgame environment for LaTeX. (Seehttp://www.chass.utoronto.ca/~osborne/latex/ to obtain the LaTeX style file and documentation for this usefulpackage.)

Both these formats export fragmentary output which is suitable for pasting/inserting into documents, although somemassaging may be needed for optimal presentation. Both export games with more than two players as a series oftables, with labels indicating the strategies of the players choosing the tables. These formats are new in 0.97.0.6 andmay need some polish; suggestions for improvements are encouraged.

3.2. How do I get payoffs into my game?

Gambit has a flexible interpretation of outcomes, particularly in extensive form games. Gambit permits outcomes toappear in more than one place in a tree or normal form. Additionally, outcomes may appear at nonterminal nodes in agame tree, in which case payoffs are interpreted as the incremental payoffs of reaching that point in the tree.

14

Chapter 3. How do I doX with the graphical interface?

This flexibility makes it possible to do some powerful manipulations of games. The current design of the graphicalinterface makes it a little awkward to get started, however. This section offers some orientation for how to manipulateoutcomes and payoffs in your game.

Each game has a predefined "null" outcome. The payoff to all players at a null outcome is defined to be zero. Newextensive form games are created with only the null outcome; when creating a normal form game, the New Gamedialog box offers by default to create one outcome per contingency in the normal form game.

Outcomes are manipulated using a grid interface accessible by theOutcomes item on theView menu. Theoutcomes grid functions similar to a spreadsheet.

Note: There is some variance in the grid behavior between the GTK and Windows versions of Gambit, due tovariance in the wxWindows implementation. Hopefully this will standardize in future versions.

A new outcome is automatically created whenever theEnter key is pressed while on the last row of the outcomestable. Alternately, a new outcome can be created by right-clicking in the grid, which generates a context menu for theoutcomes window, and selectNew.

Note: For GTK users: A quirk in GTK causes a CTRL-N shortcut to appear on this menu item. The shortcut doesnot create an outcome, but rather a new game.

Editing outcome payoffs and labels is done in-place in the grid. Note that editing payoffs may cause computedprofiles to cease being Nash equilibria (or, perhaps, cause them to become Nash equilibria); these changes will occurautomatically in the Profiles window, if displayed. Strategy, action, and node values similarly will recompute afterany payoff change.

Outcomes may be deleted using theDelete on the context menu. Deleting an outcome results in any nodes (in theextensive form) or contingencies (in the normal form) with that outcome having their outcome reset to the nulloutcome, with zero payoffs.

Outcomes are attached to nodes or contingencies in one of two ways. In either case, first select the node orcontingency where the outcome will go.

• Using theEdit menu, selectNode or Contingency, as appropriate. The presented dialogs have a drop-downchoice listing all outcomes and their payoffs; select the desired outcome, and press OK to dismiss the dialog.

• Using the outcomes window, select the outcome and right-click to get the context menu. SelectAttach, and theoutcome will be attached to the selected node or contingency.

15

Chapter 3. How do I doX with the graphical interface?

In a similar way, outcomes may be detached from nodes or contingencies, either by selecting the null outcome whenediting the node or contingency, or by selectingDetach from the context menu in the outcomes window.

3.3. How do I get Gambit to compute equilibria in my game?

In most cases, the first task a user will ask Gambit to do after entering a game is to compute some Nash equilibria. Ingeneral, it is not possible to "black box" the process of computing a Nash equilibrium, or a refinement thereof. Thealgorithm best suited to a particular task depends upon both the properties of the game, such as whether it iszero-sum, or how many players it has, the number of equilibria the user wants to find, and what refinements, if any,the equilibria should satisfy. However, both theory and experience can inform choices for algorithms and parametersettings which work "well" in general.

For both extensive and normal forms, Gambit provides a set of standard Nash equilibrium computation algorithmsettings. These standard procedures are run from the Nash equilibrium dialog (accessible with theEquilibrium itemon theTools menu). Standard algorithms to compute one, two, or all Nash equilibria are available for both extensiveand normal forms, as well as for selected refinements as appropriate. Refinements currently supported by Gambit aresequential and subgame perfect Nash equilibria on the extensive form, and (trembling-hand) perfect equilibria on thenormal form.1

Be aware that the general computational problem of finding Nash equilibria is difficult. It is quite easy to constructgames that will take Gambit quite a while to solve, especially with games with more than two players. More detailedanalysis of a game may require more customized control over the solution methods used; for more information onthis, see the more complete reference on the available methods for computing Nash equilibria inAppendix A.

3.4. How do I manage the strategy profiles Gambit hascomputed?

The profile table organizes all mixed or behavior strategy profiles, as appropriate, that have been computed byalgorithms or entered by the user. Display of the profile table is togged by the checkable menu itemProfiles on theView menu. The profile table is also automatically displayed when an algorithm returns solutions.

Each row in the table corresponds to one strategy profile. When a profile is selected, its row is highlighted; theselected profile is used by the game window to display strategy or action probabilities, values, or other information.Information about the current profile also appears in theNavigate window. Selecting a profile is done byleft-clicking on the row corresponding to the profile.

A variety of data dependent on the generating algorithm are available for most mixed or behavior profiles. Not everycategory is relevant for every profile. If a certain data member is either not relevant or not available, it will bedisplayed as----.

16

Chapter 3. How do I doX with the graphical interface?

Clicking with the right mouse button within the profile table accesses a popup menu with the following items:

• New creates a new profile and opens a dialog to edit its properties. All profiles created with theNew command aretagged with a creator field ofUser.

• Duplicate creates a copy of the currently selected profile.

• Delete deletes the currently selected profile from the list of profiles.

• Properties displays a dialog to view and edit properties of the profile, including the probabilities assigned toactions or strategies. Profiles which are edited using this dialog have their creator field reset toUser.

TheProperties dialog also appears when a profile’s entry in the table is double-clicked.

When both the extensive and normal form representations of a game are displayed, the profile lists in the twowindows are coordinated. Corresponding profiles are listed in the same order in the two windows, and operationssuch as changing the currently-selected profile, or deleting a profile, change the profile list accordingly in bothwindows. The mapping from normal form mixed strategies to extensive form behavior strategies is done usingKuhn’s Theorem; as such, the results are unpredictable if the extensive form game is not of perfect recall.

When a game is edited and payoffs are changed, the equilibrium fields such asNash will be reset. In some cases,these will be updated to yes or no answers; in others for which no definitive test is available, the fields will reset toDK (for "don’t know"). When a game is edited to change the number of information sets, actions, or strategies, allprofiles are deleted.

Changes from previous versions:In versions prior to 0.97, this was referred to as the Solutions window, andappeared as a separate frame. The nomenclature has been changed to reflect the usefulness of investigating theproperties of profiles which might not satisfy any particular solution concepts. Additionally, in prior versions,solutions had to be manually mapped from a normal form back to its corresponding extensive form, and the twosolution lists were separate.

3.5. What’s a support, and what is it good for?

A support is a subset of the actions (for extensive forms) or strategies (for normal forms) of a game. Supports aremost commonly generated as the result of computing the dominated actions or strategies in a game, but may also bemanually edited for specific purposes.

The supports currently defined on a game are accessible via theSupports menu item on theView menu. Thesupport panel is in the same notebook window as the outcome and navigation panels.

The main body of the support panel shows, in tree form, the actions or strategies in the currently selected support. Inextensive form games, the window is organized hierarchically by player, then information set; in normal form games,by player. Strategies or actions not present in the current support are shown in light grey.

17

Chapter 3. How do I doX with the graphical interface?

At the top of the support panel is a drop-down list of all supports currently defined. The first support is always the"full support", which cannot be edited. Selecting a support from this list makes the support the new current support,and changes the display of the game accordingly. The arrow buttons next to the drop-down change the currentsupport to the previous or next support in the list, respectively.

TheDominance item on theTools is used to identify actions or strategies which are dominated. For each iterationof elimination of dominated strategies this algorithm performs, the corresponding support is added to the list ofsupports. Therefore, using the arrow keys to scroll through the supports after finding dominated actions or strategiesis a useful way of seeing which actions or strategies were removed at each iteration.

Supports may be constructed and edited by hand as well. Right-clicking in the support panel displays a menu withthe following options:

• Duplicate support creates a new support with the same actions or strategies as the current support. The newsupport becomes the current support.

• Delete support deletes the current support from the support list. Note that the "full support" cannot be deleted.

The actions or strategies in any support other than the "full support" may be edited by left-clicking on the entry in thetree for the action or strategy, and pressing the space bar.

The algorithms in theEquilibrium dialog on theTools menu compute Nash equilibria on the currently selectedsupport. This is useful, since cutting down on the number of actions or strategies the algorithm must consider canhelp substantially in efficiency. So long as the current support differs from the full support only in the (possiblyiterative) removal of strictly dominated actions or strategies, algorithms will be able to find all Nash equilibria. Solong as the current support differs from the full support only in the (possibly iterative) removal of weakly dominatedactions or strategies, algorithms will find only Nash equilibria (but can possibly miss equilibria involving weaklydominated actions or strategies). For any other support, algorithms may return profiles which are not Nash equilibriaon the whole game, but which are Nash equilibria on the game defined by restricting the original game to actions orstrategies found in the current support. Note that such profiles will be indicated in the profiles window with anN intheNash column.

3.6. How do I change the layout of a game tree?

The graphical interface offers a number of options which allow the user to customize the display of game trees to hisor her own tastes. These features are grouped on theFormat menu.

The layout of a game tree can be customized using the Layout Parameters dialog, which is accessible by way of theLayout item on theFormat menu.

All lengths are in pixels. TheShow Infoset Lines choicebox is used to select a mode for display of information setson the extensive form.None means no lines are drawn connecting members of information sets.Same Level meansonly members of an information set at the same level of the tree are connected with lines.All Levels means that allnodes are connected, using lagged lines if necessary.

18

Chapter 3. How do I doX with the graphical interface?

The text labels displayed on nodes and branches can be customized using the Legends dialog (Format menu,Legends item).

There are two positions where information can be displayed for each branch (above and below.) In each of thesepositions, you can select to display information about the game tree (such as branch numbers or action names), orinformation about the currently selected solution (such as action probabilities or action values). Similarly, there arethree positions at which information can be displayed for a node (above, below, and to the right). In the positionsabove and below the node, you can select to display information about the game tree (such as infoset name or ID), orinformation about the currently selected solution (such as realization probabilities, node values, belief probabilities).The position to the right of the node is reserved for information relating to outcomes, and here you can select todisplay the outcome name or outcome vector.

Notes1. An implementation of Yamamoto’s algorithm [Yam93] for finding one proper equilibrium in a normal form

game is currently planned for release 0.97.1.x.

19

Chapter 4. The Gambit Command Language

This chapter is an introduction to the Gambit Command Language (GCL). The GCL provides a method of directingthe operation of Gambit that is analagous to that of a high level general purpose programming language.

The purpose of the GCL is to provide a simple, but powerful and flexible language by which one can performcomplicated or repetitive operations and procedures on games in extensive or normal form. The language hasfacilities for building and editing an extensive or normal form game, converting back and forth between the extensiveand normal form representations, and solving the resulting games for various equilibria of interest. Standardarithmetic, logic, text and input-output operations are provided, as well as vectorizable functions which supportmany vector and matrix operations. Flow control statements allow for repetitive operations (such as investigatinggames as one changes various parameters) or conditional operations. Thus the GCL is also suitable for certain typesof econometric analysis of games.

4.1. Introduction to the command language

When the GCL starts, it first looks for the initialization filegclini.gcl which is a file containing GCL functions,including function to load the standard user defined functions that are documented in this manual. If the file cannotbe found, a warning will be issued. Control is then turned over to you, and you will receive the GCL prompt

GCL1:= <<

The interpreter is ready for your input. Note that your prompt may be different from the above depending on settingsin your gclini.gcl file.

4.1.1. Command line editing

You can edit the command line by using the arrow keys. The left and right arrow key move the cursor, the back spaceor delete key can be used to delete characters, and the typing characters will enter the characters in insert mode. Theup and down arrow keys can be used to recall previous lines.

4.1.2. Meaning of the prompt

The GCL prompt is of the formGCLnn:= <<. The prompt is actually a valid part of a GCL expression, and can bedeleted or modified by the command line editor if so desired. The<< part of the prompt is the short form of thePrint function, which causes its argument to be displayed. Backspacing over this part of the command will suppressoutput. TheGCLnn:= part of the prompt assigns the evaluation of the expression to the variableGCLnn. Backspacingover this will prevent saving of the output into a variable.

20

Chapter 4. The Gambit Command Language

4.2. Basic concepts

The design motifs for GCL come from two principal families of programming languages. The first is traditionalimperative programming languages such as Pascal, C, and Modula-3. In particular, the GCL’s concept of types drawsheavily from these languages, although the number of predefined types in GCL is much larger due to the specializednature of the language. The second is more specialized programming languages such as Mathematica, from whichthe GCL’s grammar is partially drawn. Users with experience using any of these languages should find the GCL easyto learn; however, no programming experience is necessary to begin using the language effectively.

The GCL is a language designed primarily for building, solving and doing econometric analysis of non-cooperativegames. Because the GCL is a specialized language, it has several features that are designed to make computing aseasy and flexible as possible in this kind of environment. Some of the main features of the GCL are:

• Specialized built-in data types with implicit typing: The GCL has a number of specialized built-in data types torepresent various parts of games. For example for extensive form games, there are built in data types to representplayers, strategies, nodes in an extensive form game tree, information sets, actions, outcomes, behavior strategyprofiles, and an entire extensive form game. These data types are used internally by the GCL to organizecomputation, and keep track of important features of the objects that these data types represent.

Despite the large number of specialized data types, the GCL uses {\it implicit typing}. Implicit typing means thatyou never have to explicitly declare what the data type of a variable is before you use it. Variables can thus beeasily created in an interactive mode to refer to any object that is a valid data type, and to save intermediate stepsof computations on these data structures.

• Everything is a function: Almost every statement in the GCL is built up from function calls. Briefly, a function inthe GCL is a procedure that takes objects of specified data types, and uses them to construct and return an objectof a (possibly different) specified data type. The GCL provides a set of Built-In Functions (BIFs), which aredocumented in the function reference section of this manual.

The GCL provides functions that construct simple objects of any given data type, and other functions that operateon objects of given data types to modify them or create a new object that is guaranteed to be a valid object of thegiven data type. A GCL program typically consists of using output from one function as input to a second, whoseoutput is then used as input to the next, and so on. In this way, very complicated objects, such as extensive formgames, can be built, all the while guaranteeing their internal consistency. In this fashion, one can construct anyvalid extensive form game, and (barring bugs) it is impossible in the GCL to construct an invalid extensive formgame.

In addition to the built-in functions, the GCL also allows you to construct your own functions, which have exactlythe same behavior as any built-in function (listablity, recursion, optional arguments, and accessible via online help)

• Listability: Many objects of interest in game theory are {\it sets} (the set of players, of information sets for aplayer, of actions for an information set, etc.) All objects in the GCL (including lists) can be put in lists. Further,when a GCL function (with a few exceptions noted in the Function reference section) is called with a list for oneof its arguments, the function is run “listably”. This means that the function is executed for each element of the list

21

Chapter 4. The Gambit Command Language

and generates a list (or nested list) of the corresponding dimension as output. This makes it quite easy to generateobjects of game theoretic interest. It also makes it easy to perform certain repetitive operations usually performedby flow control statements.

4.3. Data types

The built-in data types for the GCL are given in Table 1. The Table is divided into four sections. The data types in thefirst section are standard data types that are supported in many languages. The data types in the next two sections aremore specialized data types that are used to represent elements of normal and extensive form games, respectively.The last section contains only one type, lists, which play an important role in the GCL.

The data types INTEGER and EFBASIS are subtypes of another, parent type. They are indicated in the table as theindented entries following their parent type. A subtype is a data type which has all of the properties of its parent type,plus some additional characteristics. For example, an integer is a rational number, with the additional restriction thatits denominator is one.

Table 4-1. Data types in GCL

Type name Description

BOOLEAN a boolean value

NUMBER a floating-point or rational number

INTEGER an integer

TEXT a string of arbitrary length

INPUT input stream

OUTPUT output stream

NFG normal form game

NFPLAYER a player in a normal form game

STRATEGY a strategy in a normal form game

NFOUTCOME an outcome in a normal form game

NFSUPPORT a support of strategies in a normal form game

MIXED a mixed strategy profile for a normal form game

EFG an extensive form game

EFPLAYER a player in an extensive form game

NODE a node in an extensive form game

INFOSET an information set in an extensive form game

ACTION an action at an information set

EFOUTCOME an outcome in an extensive form game

EFSUPPORT a support of actions in an extensive form game

EFBASIS an EFSUPPORT that is a basis for an assessment

22

Chapter 4. The Gambit Command Language

Type name Description

BEHAV a behavior strategy profile for an extensive form game

LIST(T) a list of objects of type T (T is any data type

The remainder of this section details the rules concerning the standard types BOOLEAN, NUMBER, TEXT, INPUTand OUTPUT, as well as general rules for typing. The extensive form and normal form types, and their related types,are detailed later in special sections.

4.3.1. Boolean

The BOOLEAN type is used to represent the boolean values. The BOOLEAN type is implemented in tri-state logic,and has the three values "true", "false" and "unknown". The command language predefines three constants torepresent these:True , False , andUnknown.

4.3.2. Numeric data types

The GCL supports one basic numeric data type, NUMBER, with a subtype of INTEGER.

• Number: The NUMBER type may contain numbers whose internal representation is either floating point orrational. The internal representation of the number is referred to as the precision of the number. Whether theprecision of the number is floating point or rational depends on how the number is initially input. It can be inputeither as a floating point constant, or a rational constant.

Floating point numbers are implemented as the machine’s double-precision floating point type. Computation withthese numbers is subject to rounding of least significant digits, and hence these numbers can be imprecise; forexample, operations usually associated with being inverses of each other may not be with floating point numbers.However, since arithmetic operations on floating point numbers are implemented in hardware, use floating-pointprecision when speed is important.

Rational numbers are implemented as the ratios of two arbitrary-length integers. Rational numbers are capable ofprecisely representing any rational number, and arithmetic operations on rationals are exact. However, arithmeticoperations on rational numbers are implemented in software. Hence, computations with rational numbers can beslow, and output from them may be unreadably large.

Floating point constants are represented in the GCL by any string of digits (where a digit is an element of{0,1,2,3,4,5,6,7,8,9} ) containing exactly one decimal point (. ). Rational constants are represented in theGCL by andy string of digits containing at most one division sign (/ ). Any NUMBER in the GCL is assumed to bein base ten representation.

23

Chapter 4. The Gambit Command Language

• Integer: The INTEGER type is a subtype of NUMBER consisting of numbers of rational precision, whosedenominator is one.

Since the GCL uses implicit data typing, the data type of a numeric constant must be identifiable by the way it iswritten. Hence, when you write a numeric constant, keep the following in mind. Floating point constants mustinclude exactly one \verb+.+ in them. Rational constants must have at most one \verb+/+ in them, and integerconstants must have neither of the above. Thus, to represent the number2 as a floating point NUMBER, you wouldwrite 2. , and to represent it as a rational NUMBER, you would use2 or 2/1 , and to represent it as an integerNUMBER, you would use2.

4.3.3. Text

The TEXT type is used to store text strings, typically labels for parts of games. It is generally encouraged to labelvarious elements of games in the command language for ease of identification; however it is not required. To specifya TEXT constant, surround the text with double-quote characters (" ). Constants may span more than one input line.Also, line feeds can be explicitly included in text constants using the C-style notation of \verb+\n+.

4.3.4. Input and output

The INPUT type is a reference to an input stream, generally a file on disk. Its principal use is to read in external data.The constant, \texttt{StdIn}, is used to refer to the standard input stream (generally the console). New INPUTstreams are created with the function \texttt{Input}, documented in the Function Reference section.

The OUTPUT type is a reference to an output stream, generally a file on disk. Its principal use is as a logging file forwriting formatted output from an extended command language job. The constants \texttt{StdOut} and\texttt{NullOut} refer to the standard output stream (generally the console) and the null output stream (the garbagecan), respectively. New OUTPUT streams are created with the function \verb+Output+, documented in the FunctionReference section.

4.3.5. Normal form data types

The data type NFG is used to represent a normal form game. No other normal form data type can exist independentlyof the normal form game to which it belongs. The NFPLAYER and STRATEGY data types are used to representplayers and strategies in a normal form game. A NFOUTCOME is an outcome for a normal form game, and anNFSUPPORT represents a support for a normal form game, which is a collection of sets of admissible strategies, onefor each player. Finally a MIXED is a mixed strategy profile over an arbitrary support.

There are no constants of any normal form data type. Objects that are of any of the normal form data types must bebuilt up using functions in the GCL. Hence, a more detailed discussion of them is deferred until later.

24

Chapter 4. The Gambit Command Language

4.3.6. Extensive form data types

The data type EFG is used to represent an extensive form game. As with normal form games, no other extensive formdata type can exist independently of the extensive form game to which it belongs. The EFPLAYER represents aplayer in an extensive form game. The types NODE, ACTION, INFOSET, EFOUTCOME represent thecorresponding parts of the extensive form representation of the game. A BEHAV is a behavior strategy profile for anextensive form game. An EFSUPPORT represents a support for a behavior strategy in an extensive form game,which is a collection of sets of admissible actions (at least one for each information set of each player). An EFBASISis a subtype of EFSUPPORT, representing a support for an assessment in an extensive form game. This is acollection of sets of admissible actions together with a collection of sets of admissible members of information sets(at least one member for each information set).

As with normal form games, there are no constants of any extensive form data type. Objects that are of any ofextensive form data types must be built up using functions in the GCL. Hence, a more detailed discussion of them isdeferred until later.

4.3.7. Lists

The LIST(T) data type can be used to represent lists of any data type T (including \verb+T=LIST(R)+, where\verb+R+ is any data type). Lists are represented in GCL statements by including objects of a given data type in curlybraces and separated by commas. For example, the following is how to represent a list containing the first fiveintegers:{ 1, 2, 3, 4, 5 } . The data type T of a list is determined by the data type of its first element. All otherelements of the list must be of the same type as the first element. The only exception to this rule is that subsequentelements can be listed to a different depth than the first element. For example if \verb+T+ is a basic data type, thenthen the second and subsequent elements of a LIST(T) can be of type LIST(T) or LIST(LIST(T)), etc. Similarly, thesecond and subsequent elements of a LIST(LIST(T)) can be of type T.

We refer to the elements at the bottom levels of a nested list as the basic elements of the list. Then lists can be ofheterogeneous depth. However, lists must be of homogeneous type. In other words, all basic elements of the list mustbe of the same type. Hence,{ 1, { 2, 3 }, 4 } is a legal list of type LIST(NUMBER), since all the basicelements are of type NUMBER, and{ { 2.0, 3/2 }, 1, 4 } is a legal list of type LIST(LIST(NUMBER)). Onthe other hand,{ 1, { 2, "3" }, 4 } is not a legal list, since the second element of the nested list is not aNUMBER.

Lists are distinct in type from each other and from their scalar equivalents. That is to say, LIST(BOOLEAN) is adistinct data type from LIST(NUMBER), and is also a distinct data type from BOOLEAN.

4.3.8. Conglomerate data types

In some of the function prototypes in the Function Reference section, you will notice certain data types which are notlisted as supported data types in the section on GCL data types. These are referred to as conglomerate data types.

25

Chapter 4. The Gambit Command Language

Conglomerate types are not actually data types, but are names used in GCL function prototypes to represent subsetsof data types. Following is a list of the conglomerate data types along with the types they include:

Table 4-2. Conglomerate types in GCL

Conglomerate type Includes

ANYTYPE Any type except LIST

NLIST(T) Nested LIST(T) of any depth (i.e., LIST(LIST( ... LIST(T)... ))

T* T, or a null value of T, for any T except LIST

4.4. Expressions

A GCL program consists of a series of expressions. An expression is typically a GCL command built up out offunction calls. Expressions can be entered interactively, at the command prompt, or can be entered from files, via theInclude["filename"] directive (see the section on including files).

Expressions are terminated by an end-of-line character (the carriage return) at a point where all brackets, braces, andquotes are matched (cloed). Expressions can be explicitly continued on additional lines by using the continuationcharacter,\ .

Comments can be included in GCL statements by preceeding the comments with the characters// . Anything afterthe // and before a linefeed is ignored by the GCL interpreter.

Some statements can lead to computations which may take a long time to complete. A control-C, typed at theconsole, is used to halt execution of the GCL and return to the command prompt. Note that the effect of a control-Cmay not always be immediate, as the control-C is only polled for at convenient stages during computation.

4.5. Functions

Functions in the GCL are rules for taking objects of specified data types, and using them to construct and return anobject of a (possibly different) specified data type. All statements in the GCL are built up out of function calls. In thissection, we desribe the rules for using functions in the GCL.

A function call consists of the name of a function followed (if the function has parameters) by a list of parameters tothe function, enclosed in brackets. Functions return a value, which may in turn be used as a parameter to anotherfunction call, allowing more complex computations to be expressed.

26

Chapter 4. The Gambit Command Language

Functions in the GCL can be either built-in or user defined. Also functions can either require arguments or not. Thisleads to four combinations. We label these as follows

Table 4-3. Function types

Description Built-in Parameters

Constant Yes No

Built-in Function Yes Yes

Variable No No

User-defined Function No Yes

4.5.1. Constants

The simplest type of a function in the GCL is a constant. A constant is a built-in function that has no arguments, andreturns the same value whenever it is called. How to construct constants for the basic data types is described in thesection on data types. Some examples of constants follow:

Table 4-4. Constants

Data type Constant

BOOLEAN True, False

NUMBER (rational precision) 1, -1234567/563

NUMBER (float precision) 1., -1.234567

TEXT "Hello, world!"

OUTPUT StdOut, NullOut

INPUT StdIn

You typically don’t think of a constant as a function, but it is. It is a function with no arguments, whose name is theconstant itself. You can “execute” a constant by simply typing its name. When you do so, it returns a value,corresponding to the object that the constant represents.

You are now ready to write your first GCL program:

GCL1:= << "Hello, world!""Hello, world!"

It is important to note that like all functions in the GCL, constants have a data type, which is determined by thefunction name. If you try and use a NUMBER constant, say123 , where a TEXT or other data type is expected, you

27

Chapter 4. The Gambit Command Language

will get an error.

4.5.2. Variables

A variable is like a constant in that it has no arguments. It stores one object of a particular data type, and returns itwhen called. The difference between a constant and a variable is that a variable must be created before it can be used,and once it is created, it can be deleted or redefined if you want. To create a new variable, or to redefine an existingvariable, one can use the built-in function,Assign , which has the prototype:

Assign[name->TEXT, value<->T] =: T

for any type T. (How to read a function’s prototype is described in more detail in the section of function calls. Fornow, suffice it to say thatAssign takes two parameters, the first of which is the name of the variable, and the secondof which is the value to be assigned to the variable.) The variable name can be any string of alphanumeric characters(a-z , A-Z , or 0-9 ) beginning with a letter. So, to create a variable with namex which returns the NUMBER1, wecan useAssign as follows:

GCL1:= << Assign["x",1]1

TheAssign function also has an infix operator form, written:= . In this form, the quotes are not needed around thevariable name, and the function is not “listable” (see the section on Lists, later in this chapter). So, equivalently, andmore compactly,

GCL1:= << x := 11

TheAssign function can be used to either create a new variable or modify an existing one. However, it cannot beused to change the type of a variable. Consider the sequence

y:=2y:=3y:="3"

The first call creates a new variabley of type NUMBER, with value of2. The second modifies \verb+y+ to havevalue3. Since the new assignment does not change the type of \verb+y+, this command is fine. The third statementattempts to change the data type of \verb+y+. This statement will result in an error, sinceAssign cannot be used tochange the type of a variable. To change the data type of a variable, it must first be deleted, and then reassigned.

An existing variable may be deleted by the use of theUnAssign function, with the following prototype:

UnAssign[name->TEXT] =: BOOLEAN

After UnAssign is called on a variable, the variable is no longer defined. A subsequent call ofAssign may redefinethe variable to be of any type.UnAssign has a short form of:= followed immediately by a linefeed or semicolon.

28

Chapter 4. The Gambit Command Language

Hence, if \verb+y+ is a variable of type BOOLEAN you can change it to NUMBER with value3.0 in two steps asfollows:

y:=y:= 3.0

4.5.2.1. Global and static variables

Variables in the GCL are by default only visible in the the part of the program in which they are defined. Inotherwords, a variable defined outside of a function will not be visible inside a GCL function (unless it is passed byreference), and a variable defined in a function will not be visible from outside the function. Secondly, variablesdefined inside a function are deallocated when control leaves the function. Thus, when a function is called a secondtime, variables defined within that function will not “remember” the values they were assigned in the last call to thefunction.

To modify the default scope and visibility of variables, the GCL uses the prefix$ in a variable name to represent a“static” variable and the prefix$$ to represent a global variable. A static variable is only visible in the function inwhich it is defined, but remains allocated after program control leaves the function, and retains its last value when thefunction is called again. A global variable remains allocated and visible when control passes to any function. Thefollowing example illustrates the use of static variables:

NewFunction[Foo[x->NUMBER]=:NUMBER,If[!IsDefined[$y],$y:=x];$y;];GCL2:= << Foo[3]3GCL3:= << Foo[2]3

and the following illustrates the use of global variables:

$$x:=5NewFunction[Foo[],$$x;];GCL1:= << Foo[]5

4.5.3. Built-in functions

Built-in functions in the GCL are just like the mathematical notion of a function. They are rules which associate witheach point in the domain, a point in the range. In the case of the GCL functions, each function has a list ofarguments. Each argument must be of a specific data type. A point in the domain is specified by specifying a value ofthe correct data type for each argument of the function.

29

Chapter 4. The Gambit Command Language

To execute a GCL function you write the function name, followed (if the function is not a constant) by a commaseparated list of the arguments, enclosed in square brackets.

All of the built-in functions in the GCL are listed in the Function Reference section of the manual. For each function,the function prototype is listed. The function prototype is a template that is used to remind you of the correct syntaxfor each function.

A function call consists of the name of a function, and a list of parameters upon which the function is to operate.Functions return a value, which may in turn be used as a parameter to another function call, allowing more complexcomputations to be expressed.

A simple example of a function call is

Plus[x->1, y->2]

This calls the function namedPlus , with parameter \verb+x+ set to the value 1 and \verb+y+ set to the value 2.SincePlus is the function for addition of two integers, the value returned would be, as you might expect, 3.

In the addition example above, we called a function which is listed in the function reference as

Plus[x->NUMBER, y->NUMBER] =: NUMBER

This listing of a function is called its {\it prototype}. It contains the function’s name, its list of parameters, and itsreturn value. In this case, the functionPlus takes two parameters, the first named \verb+x+ and taking a value oftype NUMBER and the second named \verb+y+ and taking a value of type NUMBER, and returns a value of typeNUMBER.

Because the parameters have explicit names, it is possible to rearrange the order in which parameters are listed whena function is called. Thus, we could write out sample call equivalently as

Plus[y->2, x->1]

and achieve the same effect.

Explicitly specifying the formal names for parameters all the time will prove tedious and can hinder readability. Forthese reasons, it is also legal to specify parameters without their associated formal names. These are called passing{\it anonymous} parameters. Our addition example could thus also be written

Plus[1, 2]

When used without specifying the formal names, however, function calls are restricted to specifying parameters inexactly the same order as listed in the function prototype. In our example, the GCL interpreter would have no way ofdistinguishing whether we meant 1 to be the value of \verb+x+ or the value of \verb+y+, and vice versa. While in the

30

Chapter 4. The Gambit Command Language

case of addition we may flip the values of the parameters without having an effect on the result, in general this is notthe case.

It is permitted to mix the two styles of parameter specification, subject to the following rules: \begin{itemize} \itemAll anonymous parameters must be specified before any named parameters \item No parameters may be omitted inthe anonymous parameter list. If $k$ parameters are specified anonymously, they must match one-for-one the first$k$ parameters in the function’s prototype. \item Once a named parameter has been specified, all succeedingparameters must be named, even if the first named parameter appeared in the same place in the parameter list as itdoes in the prototype. \end{itemize} \noindent Therefore, it would be legal to write

Plus[1, y->2]

but

Plus[x->1, 2]

is illegal since it violates the third condition.

To be more precise, the functionPlus comes in several different variations listed in the function reference:\begin{verbatim} Plus[x->NUMBER, y->NUMBER] =: NUMBER Plus[x->TEXT, y->TEXT] =: TEXTPlus[x->MIXED, y->MIXED] =: MIXED Plus[x->BEHAV, y->BEHAV] =: BEHAV \end{verbatim} This is anexample of function {\it overloading}. This means that one function name may have several possible parameter lists,sometimes called {\it signatures}. The GCL interpreter is capable of determining which version of the function touse by analyzing the names and types of the parameters used.

Since a function may have multiple signatures, it is conceivable that a function call might be ambiguous, in the sensethat its parameters match more than one signature for that function. However, no function call that is complete maybe ambiguous from the way that signatures have been chosen for the predefined functions. Any function call flaggedby the interpreter as ambiguous must be missing at least one parameter.

Some functions have parameters which are optional, in the sense that they need not be specified in order to call thefunction. These parameters are indicated in the function’s prototype by being surrounded by curly braces. (Note thatthese braces should not be included in the function call when specifying an optional parameter.) If an optionalparameter is left unspecified in a function call, a default value is assumed, as given in the function’s documentation.

For a function, all required parameters always precede any optional parameters. Optional parameters may also bespecified anonymously, subject to the above rules on parameter specification.

All parameters so far have been passed by {\it value}, that is, a copy of the value of the parameter is given to thefunction to which it is passed. These parameters may not be modified by the function. It is also possible to haveparameters to a function passed by {\it reference}. This means that the function does not receive a copy of the value,but rather the memory location of the value itself. Thus, the function may modify the value of a parameter passed byreference.

31

Chapter 4. The Gambit Command Language

The symbol for passing a parameter by reference, both in a function’s prototype and in a function call, is<-> .Constants may not be passed by reference. Reference parameters may be specified anonymously just like a valueparameter, subject to the usual rules. It is a run-time error to attempt to pass a value to a reference parameter, or viceversa.

In the case where functions have parameters which are subtypes, it is preferred to match to the subtype over theparent type. For example, suppose the following two signatures have been defined: \begin{verbatim}Foo[x->INTEGER] =: INTEGER Foo[x->NUMBER] =: NUMBER \end{verbatim} Then, a call ofFoo[3] resolvesto the first signature (since the value passed is an integer), andFoo[3.5] resolves to the second (since it is a number,but not specifically an integer).

4.5.4. User-defined functions

As GCL programs become more and more complex, frequently there are complicated operations which must beperformed repeatedly. The command language therefore supports user-defined functions, which allow for definingsections of code which may be called later.

A new function can be created using the functionNewFunction . For example, one might define a function tocompute the absolute value of an NUMBER as such:

NewFunction[Abs[n->NUMBER],If[n > 0, n, If[n < 0, -n, 0]];

];

After defining theAbs function, it may be called in exactly the same way a system-supplied predefined function may.The return value of the function is the value of the last statement executed.

Parameter type matching rules apply to user defined functions in exactly the same way as to predefined functions.From the function’s point of view, the parameter list is a list of variables on which assignments are automaticallydone at the beginning of the function execution. So, taking theAbs example above, in executing the call

Abs[42]

\noindent an assignment \verb+n := 42+ is implicitly performed before the body of the function is executed.

It is also possible to pass variables by “reference” to a user-defined function in the same way as a predefinedfunction. In this case, the function’s “local” variable is stored in the same physical location in the computer, andmodifying the value locally also takes effect on the variable passed to the function. For example, it might be usefulinstead to define \verb+Abs+ as:

NewFunction[Abs[n<->NUMBER],If[n > 0, n, If[n < 0, n := -n, 0]]]

in which case the function would still return the absolute value of \verb+n+, but also modify the variable passed to\verb+n+ to be the absolute value of the input \verb+n+. So,

32

Chapter 4. The Gambit Command Language

q := -37;Abs[q]

would result in the variable \verb+q+ containing the value 37 at the conclusion of execution.

Each function has its own “scope”, or set of variables. Within a function body, the only variables which are visibleare those which are declared in the parameter list of the function (this is \verb+n+ in theAbs example above), andthose which are created during the function’s execution. That is, no “global” or outside variables may be accesseddirectly by the function. For example, if the user typed in the following:

i := 4;NewFunction[FooFunc[x->NUMBER], x * i]

later execution of theFooFunc would yield an “undefined variable i” error message, since \verb+i+ is never definedwithin the function. If insteadFooFunc had been defined as follows:

NewFunction[FooFunc[x->NUMBER], i := 13, x * i]

FooFunc would always return 13 times the value of the parameter \verb+x+, since the value of \verb+i+ insideFooFunc is always 13, regardless of the value of \verb+i+ outside of the function.

4.5.5. Aliases for function calls

There are several functions which are so commonly used that special “short forms” are defined for them. We alreadysaw one example with the functionAssign , which has the short form:= . Most functions with short forms are thestandard arithmetic and logic operators, for which the usual binary infix or unary prefix notations are supported. Theexample of addition used in a previous section may more familiarly be written

1 + 2

which expression is converted to the “long form” function call by the interpreter. Note that formal names may not bespecified in a “short form” call, and the order of parameters is therefore significant.

Here is a list of the functions thus abbreviated, and their “short form” equivalents:

Table 4-5. Operators in GCL

Function Operator(s)

And[x,y] x && y, x AND y

Assign[x,y] x := y

Concat[x,y] x & y

Divide[x,y] x / y

Dot[x,y] x . y

Equal[x,y] x = y

Greater[x,y] x > y

33

Chapter 4. The Gambit Command Language

Function Operator(s)

GreaterEqual[x,y] x >= y

IntegerDivide[x,y] x DIV y

Less[x,y] x < y

LessEqual[x,y] x <= y

Minus[x,y] x - y

Modulus[x,y] x & y , x MOD y

Not[x] NOT x, !x

NotEqual[x,y] x != y

NthChar[text,n] text[[n]] , text_n

NthChild[node,n] node#n

NthElement[list,n] list[[n]] , list_n

Or[x,y] x || y , x OR y

Parentheses[x] (x)

Plus[x] x + y

Power[x] x ^ y

Print[x] << x

Read[in,x] in >> x

Times[x,y] x * y

UnAssign[x,y] x :=

Write[out,x] out << x

When functions are written in their canonical forms, no ambiguity arises in the order of evaluation: In order toevaluate a function, all arguments must be evaluated first. Arguments are evaluated from left-to-right as specified inthe function call. This leads to a recursive structure of evaluation, which stops only when an argument beingevaluated is a constant function (i. e., a function with no arguments).

When short form forms are used, then ambiguity can arise in the intended order of evaluation. For example, thestatement \verb & a + b * c& , could be meant as \verb+Plus[a,Times[b,c]]+ or as \verb+Times[Plus[a,b],c]+. Inorder to resolve such ambiguities, all functions that have a short form representation are given an order ofprecedence. When a statement is parsed by the GCL, it is first scanned from left to right, replacing each short formexpression at the top level of precedence with its canonical form. Then it is scanned again replacing each short formexpression at the second level of precedence with its canonical form, and so on, until all short form expressions havebeen eliminated.

The order of precedence for built-in functions is as follows:

Table 4-6. Order of precedence

()

34

Chapter 4. The Gambit Command Language

:=

>> <<

||

&&

NOT

= != < <= > >=

+ - &

* . / DIV MOD ^

(unary)+ -

[[ ]] _

Thus, the statementa + b * c would become

Plus[a,b*c]Plus[a,Times[b,c]]

On the other hand, the statement( a + b ) * c would become

Parentheses[a+b]*cParentheses[Plus[a,b]]*cTimes[Parentheses[Plus[a,b]],c]

which, sinceParentheses is just the identity mapping, is equivalent to

Times[Plus[a,b],c]

4.6. Getting and suppressing console output

The GCL will only print output at the console if you explicity ask for it with the built-in functionPrint . Thisfunction has the prototype

Print[x->T] =: T

for any data type T, and has the short form<< x . You may have noticed that the GCL prompt concludes with a<<.In fact, this is not part of the prompt, but rather is a “pre-typed” part of your GCL command.

Once you have become accustomed to the GCL, you may prefer to supress output from some or all commands typedat the GCL command line. This can be done for individual commands by using the backspace or delete keys to erasethe<< part of the prompt. The built-in functionSetVerbose controls whether<< is pretyped at every prompt. Thecommand

SetVerbose[False]

35

Chapter 4. The Gambit Command Language

will turn off this feature, so that your prompt will then look as follows:

GCL1:=

Now, the default is that no output is printed. If you want to have the output of specific commands printed, then youcan start your command with<<. For example,

GCL1:= 1+1GCL2:= << 1+12

Note that error messages will be reported at the console regardless of the setting of the verbose mode.

4.7. Lists

4.7.1. Building and modifying lists

Lists play a special role in the GCL. Variables can be created to contain lists in the same fashion as for any other datatype:

list:={1,{2,3},4}

The built in function \verb+List[x,n]+ can be used to create a list of length \verb+n+ all of whose elements have thevalue \verb+x+. For numeric data types, a third parameter forList allows each successive entry to be incremented.

GCL1:= << List["Help",3]{ "Help", "Help", "Help" }GCL2:= << List[List[0,3],3]{ { 0, 0, 0 },

{ 0, 0, 0 },{ 0, 0, 0 } }

GCL3:= << List[0/1, 5, 1/4]{ 0, 1/4, 1/2, 3/4, 1 }

Lists of any data type can be created withList . So if \verb+n+ is a normal form game, then \verb+List[n,5]+ is a listof five copies of \verb+n+.

The functionNthElement can be used to get \verb+n+th element of the list, \verb+list+. This function has two shortforms,list[[n]] andlist_n . Since the function returns the \verb+n+th element of the list, it can be usedrecursively to get the elements of nested lists. So \verb+list_i_j+ returns the \verb+j+th element of the \verb+i+thelement of \verb+list+. Also, since \verb+list+ is passed by reference, the function can be used to modify thecorresponding element of a list. Thus, you can constuct your own 3-by-3 identity matrix as follows:

GCL1:= list:=List[List[0,3],3]GCL2:= list_1_1:=list_2_2:=list_3_3:=1;GCL3:= << list

36

Chapter 4. The Gambit Command Language

{ { 1, 0, 0 },{ 0, 1, 0 },{ 0, 0, 1 } }

4.8. Listability of functions

Almost all of the functions in the GCL are “listable”. This means that if there is a version of the function which takesa type T as the data type for a parameter, then it can be called with LIST(T) as well. This results in the functiongenerating a list of the corresponding length and data type as its output. For example, consider a function

Foo[x->T,y->S] =: R

where T, S, and R represent arbitrary data types. Then if \verb+a+ is a LIST(T), and \verb+b+ is of type S, then\verb+c := Foo[a,b]+ generates \verb+c+ of type LIST(R), where the length of \verb+c+ is equal to the length of\verb+a+, and where \verb+c[[i]] = Foo[a[[i]],b]+.

If Foo[] is called with both \verb+a+ and \verb+b+ being lists of the correct data type, then the GCL checks whetherthe length of \verb+a+ and \verb+b+ is the same. If not, it generates a dimensionality error. If they are of the samedimension, then \verb+c := Foo[a,b]+ generates \verb+c+ of type LIST(R), where the length of \verb+c+ is equal tothe length of \verb+a+, and where \verb+c[[i]] = Foo[a[[i]],b[[i]]]+.

Note that the above rules implicitly define versions ofFoo of the following forms:

Foo[x->LIST(T),y->S] =: LIST(R)Foo[x->T,y->LIST(S)] =: LIST(R)Foo[x->LIST(T),y->LIST(S)] =: LIST(R)

The same rules apply recursively using these function prototypes as well. So if \verb+a+ is of type LIST(LIST(T)),and \verb+b+ is of type \verb+S+, the command \verb+c := Foo[a, b]+ results in a listable call to\verb+Foo[x->LIST(T),y->S]+. Thus, \verb+c+ is of type LIST(LIST(R)), where \verb+c[[i]] = +\verb+Foo[a[[i]],b]+. Hence, \verb+c[[i]][[j]] = + \verb+Foo[a[[i]][[j]],b]+.

Note that many vector and matrix math operations follow directly as listable calls to the basic arithmetic functions. Inthis example, listability ofTimes is used to provide scalar multiplication of a scalar and a matrix, and listability ofPlus is used to add two conformable matrices:

GCL1:= a:={{1,2},{3,4}};GCL2:= << 2*a{{2,4},{6,8}}GCL3:= << a+Transpose[a]{{2,5},{5,8}}

37

Chapter 4. The Gambit Command Language

Here listability ofPower is used to create a list of the first ten perfect squares:

GCL4:= << List[1,10,1]^2{ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }

While most functions in the GCL are listable, there are some exceptions. Built-in functions that are not listable arenoted as such in the Function Reference section of this document.

Listability of functions is a powerful tool of the GCL. Many GCL programs using flow control statements can bewritten using listable function calls instead. It is encouraged to use listable functions as much as possible because ittypically leads to more concise, easier to read GCL programs, and in addition the programs typically run faster thanthey would if flow control satements were used instead. This is because listable calls to functions are executed incompiled code, while flow control statements are executed in interpreted code.

4.9. Online documentation

The functionsHelp andManual are used to obtain online documentation of any function in the GCL, including userdefined functions that you created with theNewFunction command.

If the Help function is called with a string that is an exact match for a GCL function name, then it returns a list offunction prototypes for that function name (there can be more than one prototype for a function name since GCLfunctions can be overloaded.) For example,

GCL1:= << Help["help"]{ Help[x->TEXT, {udf->True}, {bif->True}] =: LIST(TEXT) }

returns the function prototype forHelp . Note thatHelp has two optional BOOLEAN parameters, \verb+udf+ and\verb+bif+. By default, both user defined functions and built-in functions are included in the search. To exclude oneor the other of these, set the corresponding parameter toFalse .

The required text parameter forHelp can also contain the regular-expression style wildcards* and?. In this case, ifthere is not an exact match, a list of function names matching \verb+x+ is returned. For example, The command

GCL1:= << Help["*efg"]{ CompressEfg, LoadEfg, NewEfg, SaveEfg }

returns a list of all function names ending with “efg”

38

Chapter 4. The Gambit Command Language

Note that the functionHelp is listable (see section on listability), so that we can do \verb+Help[Help["*efg"]]+ to geta list of function prototypes for all functions whose names end with \verb+efg+. Similarly, \verb+Help["*"]+ gives alist of all function names in the GCL, and {\tt Help[Help["*"]]} gives a list of all function prototypes in the GCL.

The functionManual is used to obtain a more complete description of a GCL function. IfManual is called with anargument that is an exact match for a GCL function name, it returns the manual entry for that function. For a built-infunction a textual description of the function and its parameters is returned.

4.10. Advanced topics

4.10.1. Including files

The functionInclude[file->TEXT] is used to insert the contents of the file given into the input stream, as if theyhad been typed directly by the user. This can be particularly useful in conjunction with user defined functions, in thata library of useful functions can be constructed and included into the program asily.

Include may only appear at the “top level” of the program. That is to say, it cannot be used inside a loop, functiondeclaration, or expression. However, files may be nested arbitrarily deep usingInclude , so you can include a filewhich in turn includes other files.

When a file is included, the GCL looks for a file with that name in the following locations, in order.

1. The current directory;

2. The directory specified by the \verb+HOME+ environment variable, if any;

3. The directory specified by the \verb+GCLLIB+ environment variable, if any;

4. The directory where the executable is located.

This search order applies also to thegclini.gcl file that is loaded whenever the GCL is started. Hence, you cankeep a standard version of a file that is frequently included in the same directory as the GCL executable, and thenmodify it for use on a particular project by keeping a modified copy of it in the directory associated with that project.

It is good practice to have included files identify themselves when they are included. This can be done by using theGetPath function, which returns the full pathname of the file from which the command is executed. For example, ifthe following line is placed as the first line in an included file (say with filenamepath/myfile.gcl )

StdOut << "Include[\""&GetPath[]&"\"]\n"

39

Chapter 4. The Gambit Command Language

(Note that the standard escape sequences\" and\n are used within a text string to represent a quotation mark and acarriage return, respectively.) Then when the file is included, it will identify itself by writing the following messageto the standard output stream:

Include["path/myfile.gcl"]

4.10.2. Flow control structures

The GCL contains three functions which allow flow control within a program. These functions are “special” in thattheir parameters are evaluated in a special way (since their parameters are expressions and sequences of statements);they also have no “formal” names for their parameters.

4.10.2.1. Conditional execution withIf

The functionIf allows execution of a sequence of statements only under certain conditions. The syntax of thefunction is

If[boolean-expression, statement-list {, statement-list}]

The function is interpreted as follows: If theboolean-expression evaluates toTrue , then the first list ofstatements is executed. If it evaluates toFalse and the second (optional) list of statements is present, that list isexecuted; if it is not present, theIf expression evaluates toFalse . For example, the statement

If[i = 2, j := 1, j := 2]

sets \verb+j+ to \verb+1+ if the value of \verb+i+ is \verb+2+, and sets \verb+j+ to \verb+2+ if the value of \verb+i+is not \verb+2+. It would also be perfectly legitimate to write

If[i = 2, j := 1]

in which case \verb+j+ would be set to \verb+1+ if \verb+i+ is equal to \verb+2+, but if \verb+i+ were not \verb+2+,the expression evaluates to \verb+False+.

This last example brings up an important note about conditional execution. Expressions which appear in the branchof an If expression which is not taken are treated as if they did not exist. So, were this the first mention of \verb+j+in this scope, the last example would leave \verb+j+ defined only if \verb+i+ was equal to \verb+2+. However,\verb+j+ wouldnot be defined otherwise. It is therefore necessary to be careful in constructingIf expressions whichresult in the definition of new variables.

4.10.2.2. Repetitive execution withWhile

Often in writing programs it is necessary to execute a block of statements repeatedly, usually with different values forvariables. To this end the GCL provides a special functionWhile as a generalized looping construct. The syntax of

40

Chapter 4. The Gambit Command Language

the function is

While[boolean-expression, statement-list]

The function is interpreted as follows: Whileboolean-expression evalutes toTrue , execute the statements instatement-list . Note that the evaluation of the boolean takes place at the beginning of the execution of a block,so it is only important whether the value isTrue or False at the beginning of the block, and not at some point in themiddle.

This simple loop creates a list of the first ten perfect squares:

i := 1;list := { };While[i <= 10, list := list & { i^2 }; i := i + 1;]

As with If , be wary of declaring a variable implicitly inside a loop. A variable is declared only when thecorresponding statement is executed; so, if theboolean-expression is False the first time it is evaluated, thebody of the loop never executes, and no variables which appear in the loop are considered to be defined.

4.10.2.3. Indexed looping withFor

The functionFor is a specialized looping construct, useful mostly in cases where some index variable is used toiterate a list or some sequence. The general syntax forFor is

For[statement-list, boolean-expression, statement-list, statement-list]

The call is interpreted as follows:

1. Execute the statements in the firststatement-list (initialization);

2. Evaluate theboolean-expression (or guard);

3. If the boolean-expression is False , terminate the loop and continue with the first statement after theloop. If it is True , execute the thirdstatement-list , which is the body of the loop;

4. Execute the secondstatement-list , which is usually used to increment a counter, and return to theevaluation of the guard in step 2.

Returning to the example in theWhile section, here is another way of writing the loop to create a list of the first tensquares:

For[i:=1; list:={}, i<=10, i:=i+1, list:=list&{i^2}]

41

Chapter 4. The Gambit Command Language

The two methods are completely equivalent, but it is often more convenient to use the structure afforded by theFor

function.

4.10.3. Input and output

Data can be read from an input stream by theRead function. So if \verb+in+ is an input stream (i. e., of type INPUT)then a successful call of \verb+Read[in,x]+ will read the exposed data (see function reference for definition of“exposed data”) from the input stream, \verb+in+, assign \verb+x+ to have that type and value, and position the filepointer at the end of the exposed data, to be ready for the next call ofRead+. \verb+Read[in,x]+ has the short form\verb+in >> x+. Since the return value of \verb+Read[in,x]+ is \verb+in+, these commands can be chained. In otherwords,

in >> x >> y

is equivalent to

Read[in,x]Read[in,y]

In the statement \verb+Read[in,x]+, if \verb+x+ is undefined, then its data type is determined from the exposed datain the input stream. On the other hand if \verb+x+ is previously defined, then theRead function will expect to findthe corresponding data type in the input stream, and a file read error will be generated if the exposed data is of thewrong data type. If \verb+x+ is previously defined to be a \verb+LIST(T)+, then \verb+Read[in,x]+ will successivelyread elements into each element of the list. If the wrong data type is found for any element of the list, a file read errorwill be returned. Thus, if the filefile.dat contains the following data

25 1/3 "This is a text string!" False 3.14159{{1, 0},{0, 1}}1 2 3 4 5

then the following GCL code

in:=Input["file.dat"]x:=List[0,5]in >> i >> r >> t >> b >> f >> l >> x

opens an input stream, consisting of the contents offile.dat , and then reads data from the input stream into thecorresponding variables. After the last statement, \verb+i+ is a NUMBER with value \verb+25+, \verb+r+ is aNUMBER with value \verb+1/3+, \verb+t+ is a TEXT with value"This is a text string!" , \verb+b+ is aBOOLEAN with valueFalse , \verb+f+ is a NUMBER with value \verb+3.14159+, \verb+l+ is aLIST(LIST(NUMBER)) with value \verb+{{1,0},{0,1}}+, and \verb+x+ is a LIST(NUMBER) with value\verb+{1,2,3,4,5}+.

Data can be written to an output stream by the use of theWrite function. Thus, the following commands

42

Chapter 4. The Gambit Command Language

out:=Output["file.out"]x:=0/1;y:={0.0,0.0}Write[out,x]Write[out,y]

creates an output stream, \verb+out+, and then writes out a NUMBER, followed by a list of two NUMBERs.\verb+Write[out,x]+ has the short form \verb+out << x+. Since the return value ofWrite is \verb+out+, thesecommands can be chained. So the two lines writing out \verb+x+ and \verb+y+ in the above example could bewritten instead

out << x << y

TheFormat andListFormat functions can be used to control the formatting of data written to an output stream.Note that theRead andWrite functions are not listable.

TheRead andWrite functions can only be used with certain data types (see function documentation). Reading andwriting of EFG and NFG from external files can be done with theLoadEfg , SaveEfg , LoadNfg andSaveNfg

functions.

4.10.4. Null values

Certain function calls in the GCL result in either invalid or undetermined values for the required data type. Exampleswould be asking for the first child node of a terminal node, or the parent of the root node, or an outcome attached to anode with no outcome. Similar problems arise in the algorithmic and computational parts of the code. Here, forexample, algorithms that do not compute sequential equilibria do not return belief probabilities for unreachedinformation sets. Other algorithms may action probabilities for off the equilibrium path information setsundetermined.

Under certain situations such as the above, when no valid value is available for return, instead of returning an error,the GCL will a Null value for the given type. Returning a Null value instead of terminating execuation with an errormessage is frequently desirable in a setting where functions are being called listably, as it allows for computation ofelements of the list that have valid entries without aborting the GCL because some elements have invalid entries.

The situations in which Null values are returned are described in the function reference section of the manual. Mostfunctions in the GCL, when encountering a Null value as a parameter, will abort with an error message. Whether afunction will accept Null values as valid values for an argument is indicated in the function prototype with an asterisk(* ) after the relevant parameter. For example, the function prototype forIsNull is

IsNull[x->T*]=:BOOLEANfor any data type, T

Here, the* indicates that this function accepts Null values for its argument. If a built-in function accepts Null valuesfor an argument, it is documented in the function reference section what the behavior of the function is whenencountering a Null value.

43

Chapter 4. The Gambit Command Language

Note that user defined functions will accept Null values for arguments also, if the relevant parameter is designatedwith a \verb+*+, as above.

4.10.5. System information

There are several commands in the GCL that allow you to get information from or run processes on the host system.

A series of functions,StartWatch , StopWatch , andElapsedTime , provide information on the amount of cputime used by the GCL, and can be used to time computation. Another series of functions,GetEnv , SetEnv ,UnSetEnv , Platform , allow you to set and check environment variables, or check the operating system that theGCL is running on. A third series of functions,ExePath , GetPath , andGambitExe (included instdudfs.gcl ),provide path and filenames to files being used by or related to the GCL. Finally, theShell command allows you torun a child process from the GCL.

The above system functions are also used in the user defined functionDisplay , which allows you to start a childprocess that launches up the Gambit graphical interface and loads an extensive or normal form game. If \verb+game+is a variable of type NFG or EFG, then the callDisplay[game] will load the \verb+game+ in the graphicalinterface.\footnote{The user defined functionsGambitExe andDisplay assume that you used the defaultdirectories and filenames when you installed Gambit. If you deviated from the standard installation, you may have toedit these functions before they work correctly.}

4.10.6. Variables pointing to deleted objects

In the GCL, you can create variables to represent objects which may be deleted or invalidated subsequently as sideeffects of some functions. For example, suppose you define a variable to represent an element (node, information set,outcome, etc.) of an extensive form game. You may subsequently delete the part of the tree that contains thatelement. The object that the variable originally referred to is no longer valid. In this case, the variable isautomatically unassigned.

In the following example, a game is loaded, and the variable \verb+n+ is defined to be the first child of the first childof the root node. Now the part of the tree after the first branch is deleted, the variable \verb+n+ is now undefined:

GCL1:= e:=LoadEfg["poker.efg"]GCL2:= r:=RootNode[e]GCL3:= n:=r#1#1GCL4:= DeleteTree[r#1]GCL5:= << nERROR: Print[]: Undefined reference "n" passed for parameter #1

Since the node is no longer present in the tree, the variable \verb+n+ which refers to it has been unassigned. Asimilar situation occurs here, where elements of a list are deleted viaDeleteTree :

GCL1:= e:=LoadEfg["poker.efg"]GCL2:= t:=TerminalNodes[e]

44

Chapter 4. The Gambit Command Language

GCL3:= DeleteTree[RootNode[e]#1]GCL4:= << tERROR: Print[]: Undefined reference "t" passed for parameter #1

In this case, a variable \verb+t+ is defined to refer to the list of terminal nodes. The functionDeleteTree deletessome of the terminal nodes. Even though some of the nodes in the list \verb+t+ are still valid, if any element of a listis deleted, the entire list is unassigned.

Similar situations arise with mixed and behavior strategies if the underlying game to which they refer change in away to invalidate the solutions. In the following example, a solution to the game \verb+e+ is saved as a variable\verb+b+ of type BEHAV:

GCL1:= e:=LoadEfg["poker.efg"]GCL2:= << b:=EnumMixedSolve[e,asNfg->True]_1(Behav) { { 1.000 0.000 }{ 0.333 0.667 } }{ { 0.667 0.333 } }GCL3:= DeleteTree[RootNode[e]#1]GCL4:= << bERROR: Print[]: Undefined reference "b" passed for parameter #1

The game is subsequently edited, making the profile no longer valid for the changed game; therefore, the variablecontaining it is automatically unassigned.

4.10.7. Errors

Sometimes, programs contain errors. The interpreter is able to detect errors which violate rules of the language, andreports information about the error so the user can correct it. There are two main classes of errors which may arise inGCL programs: parse errors and run time errors.

A parse error occurs when the GCL interpreter cannot determine the meaning of a statement, because it does notconform to the grammatical rules of the language. This most frequently occurs when braces, brackets, or quotationmarks fail to match up or when punctuation is missing. When it encounters a parse error, the GCL interpreter willdisplay an error message giving the filename and line number of the error and the point at which it determined anerror it occurred.

A run time error occurs when a statement which obeys the grammatical rules of the language violates another rule ofthe language during its execution. Examples of this type of error include attempting to use a variable name which isnot defined, and using a value of one type where another type was expected. Also, builtin functions may generate thistype of error on invalid inputs. A run time error will result in termination of the GCL at the point where the erroroccurs, with a message indicating the type of error encountered.

45

Chapter 4. The Gambit Command Language

4.11. Constructing and manipulating games

The whole point of the GCL is to provide an environment to enable building and doing computations on games. Thischapter describes how to build and solve normal and extensive form games in the GCL.

4.11.1. Normal form games

A normal form game is a set of players, each with a strategy set, together with a function from the cartesian productof strategy sets to a set of outcomes. Each outcome results in a payoff to each of the players. To construct a normalform game, one must therefore define each of these parts. A collection of GCL functions is available for building andediting normal form games. A complete list is given in the sections on “Normal Form Manipulation” in theCategorical Function Reference section of the manual. The most generally-useful functions are given in the table.

Table 4-7. Overview of normal form manipulation functions

Function Description

DeleteOutcome[o] Deletes outcome \verb+o+ from its game

NewOutcome[n] Returns a new outcome for the game

NewOutcome[n,name] (user-defined) Returns a new outcome namedname for gamen

NewOutcome[p] (user-defined) Attaches a new outcome with zero payoffs to the pureprofile p

Outcome[p] The outcome attached to the pure strategy profilep

OutcomeForm[n] The game form for gamen

Outcomes[n] List of outcomes defined for gamen

SetOutcome[p,o] Attach outcomeo to pure strategy profilep

NewNfg[dim] A new normal form with dimensionsdim

NewNfg[dim,True] (user-defined) A new normal form with dimensionsdim , outcomes in allcells

Nfg[e] Converts extensive form gamee to normal form

Nfg[x] (user-defined) Converts nested list of numbersx to normal form

Payoff[o,pl] Payoff of outcomeo to playerpl

Payoff[m,pl] Payoff of mixed profilemto playerpl

Payoffs[p] (user-defined) Payoffs of pure strategyp

Payoffs[n] (user-defined) Normal form game payoffs ofn as a nested list

Payoffs[o] (user-defined) Payoffs of outcomeo

Payoffs[m] (user-defined) Payoffs of mixed profilem

Randomize[n,j] (user-defined) Randomizes the payoffs inn with seedj

Strategies[pl] (user-defined) Strategies for playerpl

Strategies[n] (user-defined) Strategies for gamen

SetPayoff[o,pl,pay] Set payoff to playerpl in outcomeo to pay

46

Chapter 4. The Gambit Command Language

4.11.1.1. Creating a normal form game

The functionNewNfg is used to create a new normal form game. Thus, the expression

GCL1:= NewNfg[{2,3,2}]

will create a new normal form game with three players, where the first player has two strategies, the second playerhas three strategies, and the third player has two strategies. Since no outcomes have been defined, all strategy tuplesof pure strategies result in the null outcome, which has payoff of zero for all players.

The game created byNewNfg is not very interesting, because all payoffs for all strategies are zero. To make it moreinteresting, outcomes must be created and associated with strategy tuples. To create a separate outcome for each purestrategy, one can specify the second argument inNewNfg to beTrue . These outcomes will still have zero payoffsuntil they are changed. The functionRandomize can be used to randomize the payoffs of each outcome in the game.In this way,NewNfg can be used to create more interesting games by using it as an argument to other functions thataccept normal form games as arguments.

For example, to create a random two person 2 by 2 normal form game, with a seed of 34 for the random numbergenerator, you can use the functionRandomize to randomize the payoffs of the original game:

GCL2:= Randomize[NewNfg[{2,2},True],34]

You can look at the payoffs of the game by using the user-defined function fromstdudfs.gcl , Payoffs (usingFloat to convert the payoffs of the game to floating point precision first):

GCL3:= << Payoffs[Float[Randomize[NewNfg[{2,2},True],34]]]{ { { 0.159964, 0.026784 }, { 0.421515, 0.399322 } },

{ { 0.233245, 0.923402 }, { 0.039071, 0.695271 } } }

Here, the payoffs are written in a nested list, where the \verb+(i,j)+th component is the vector of payoffs when player1 takes strategyi and player 2 takes strategyj . The game can be solved for all mixed Nash equilibria by

GCL4:= << AllNash[Randomize[NewNfg[{2,2},True],34]]{ (Mixed) { 1.000000 0.000000 }{ 0.000000 1.000000 },

(Mixed) { 0.000000 1.000000 }{ 1.000000 0.000000 },(Mixed) { 0.379795 0.620205 }{ 0.839199 0.160801 } }

In all of the above examples, all work is thrown out, and the normal form game is created anew in each successivecommand. You can avoid such wasteful computation, and minimize the typing you need to do by saving intermediateresults in a variable. For example, the above could be done as follows:

GCL1:= n:=Randomize[NewNfg[{2,2},True],34];GCL2:= p:=Payoffs[n];GCL3:= m:=EnumMixedSolve[n];

47

Chapter 4. The Gambit Command Language

The first statement creates a variablen to store the normal form game. This variable is then used as an argument inthe next two function calls. The second two statements create variablesp andmto store the nested list of payoffs ofthe game, and the list of mixed strategy solutions of the game. Any of these variables can then be used as input toother function calls, as long as the data type of the variable is the same as the data type of the

The above also illustrates another important principle of the GCL. All of the functions in the GCL (with a fewexeptions, noted in the Function Reference Section) return objects of some specific data type. Any object returned bya function can be stored in a variable. While the GCL supports a large number specialized data types, the data typingis all implicit. In other words, you never have to declare what data type a variable will be before it is used. A variabletakes on the data type of the object that is first assigned to it.

4.11.1.2. Setting payoffs

The payoffs in a normal form can be set to have specific values using theSetPayoff function. The followingsequence of expressions illustrates how to build a simple prisoner’s dilemma game, by first creating a normal formgame with the appropriate number of players and strategies, and then modifying the payoffs one by one.

GCL1:= n:=NewNfg[{2,2}]GCL2:= s:=Strategies[n]GCL3:= NewOutcome[{s_1_1,s_2_1},{9.0,9.0}]GCL4:= NewOutcome[{s_1_1,s_2_2},{0.0,10.0}]GCL5:= NewOutcome[{s_1_2,s_2_1},{10.0,0.0}]GCL6:= NewOutcome[{s_1_2,s_2_2},{1.0,1.0}]GCL7:= << Payoffs[n]{ { { 9.000000, 9.000000 }, { 0.000000, 10.000000 } },

{ { 10.000000, 0.000000 }, { 1.000000, 1.000000 } } }

Note that the above can be done equivalently and more simply by using the standard user-defined function,Nfg , tocreate the game directly from a payoff list:

GCL1:= n:=Nfg[{{{9,9},{0,10}},{{10,0},{1,1}}}]GCL2:= << Payoffs[n]{ { { 9.000000, 9.000000 }, { 0.000000, 10.000000 } },

{ { 10.000000, 0.000000 }, { 1.000000, 1.000000 } } }

You can name the strategies if you want by usingStrategies to get a list of the strategies in the game, andSetName to name them.

GCL3:= s:=Strategies[n]GCL4:= SetName[s_1,{"Cooperate","Defect"}]GCL5:= SetName[s_2,{"Cooperate","Defect"}]GGCL6:= << Name[s]{ { Cooperate, Defect },

{ Cooperate, Defect } }

48

Chapter 4. The Gambit Command Language

We now give a more complicated example, in which one can use listability of vector and matrix operations to set thepayoffs in the normal form according to a formula. In this example, we create a version of the “stag hunt” game.

GCL1:= << strat:=List[1,3,1]{ 1, 2, 3 }GCL2:= << stratSets:=List[strat,2]{ { 1, 2, 3 },

{ 1, 2, 3 } }GCL3:= << effort:=CartesianProd[stratSets]{ { { 1, 1 }, { 1, 2 }, { 1, 3 } },

{ { 2, 1 }, { 2, 2 }, { 2, 3 } },{ { 3, 1 }, { 3, 2 }, { 3, 3 } } }

GCL4:= << pay:=Min[effort]-.5*effort{ { { 0.500, 0.500 }, { 0.500, 0.000 }, { 0.500, -0.500 } },

{ { 0.000, 0.500 }, { 1.000, 1.000 }, { 1.000, 0.500 } },{ { -0.500, 0.500 }, { 0.500, 1.000 }, { 1.500, 1.500 } } }

GCL5:= << n:=Nfg[pay](Nfg) ""

First, the set of effort levels for a player (consisting of the list of integers from one to 3) is constructed and stored inthe variablestrat . (While this variable is calledstrat , its data type is LIST(INTEGER), not STRATEGY.)Second, the set of strategy sets for both players is assembled instratSets . Third, the set of pure strategy profiles isassembled by taking the cartesian product of the strategy sets, and converted to NUMBER to give a vector of effortsfor each pure strategy profile. The result is stored in the variableeffort . Fourth, the vector of payoffs for each purestrategy profile is computed by taking, for vector of payoffs, the minimum effort across players, and subtracting thecost of effort for each player. Finally, a game is constructed with these payoffs, by using the functionNfg . If you nowask to see the payoffs for the game viaPayoffs[nfg] , you will see an array just likepay .

The fourth step in the above calculation illustrates a subtle but important point about listable functions. The functionMin requires an argument of type LIST(NUMBER) and returns type NUMBER. It is being called with an argumentof type LIST(LIST(LIST(NUMBER))), with dimension 3 by 3 by 2. Hence, the function will be run as a listablefunction on the innermost vectors in the nested list, generating a result of type LIST(LIST(NUMBER)), withdimension 3 by 3, each entry of which contains the minimum of the vector in that cell. Thus:

GCL6:= << Min[effort]{ { 1, 1, 1 },

{ 1, 2, 2 },{ 1, 2, 3 } }

To subtract the component .5*effort from this, the functionMinus requires data of type NUMBER for botharguments. It is being run with the first argument of type LIST(LIST(NUMBER)) with dimension 3 by 3, and thesecond of type LIST(LIST(LIST(NUMBER))), with dimension 3 by 3 by 2. The first two levels of the list for botharguments match in dimension. Then it encounters a NUMBER in the first argument, and a LIST(NUMBER) ofdimension 2 on the second. Hence, Minus runs listably on its second argument, yielding a LIST(NUMBER) ofdimension 2 for each entry in the 3 by 3 nested list ofMin[effort] .

49

Chapter 4. The Gambit Command Language

The functions used in the above construction will accept nested lists of any level. Hence, the above can be extendedinto a user defined function which allows one to build a stag hunt game for an arbitrary number of players andstrategies:

NewFunction[StagHuntNfg[n->INTEGER,maxeff->INTEGER,cost->NUMBER]=:NFG,strats:=List[1,maxeff,1];effort:=CartesianProd[List[strats,n]];Nfg[Min[effort]-cost*effort];

];

The expressions in this user defined function are analagous to the steps in the two person example above. Once theabove function has been defined, then you can then use it as follows:

n:=StagHuntNfg[4,2,.5];

to create a four person stag hunt game where each player has two strategy choices (effort levels) and the cost of effortis .5.

Once a normal form game has been defined, there are a number of solution algorithms that can be applied to solvethe game. How to solve normal form games is discussed in the next chapter. Until you get to that point, you mightwant to save your work.

4.11.1.3. Saving and loading normal form games

Once a normal form game has been constructed, it can be saved in a similar way to an extensive form game. Theexpression

SaveNfg[n, "filename.nfg"]

will save the normal form gamen to the filefilename.nfg . It is recommended that the filename extension.nfg beused when saving normal form games, as the Gambit graphical user interface recognizes this extension as containingnormal form games. Once a normal form game has been saved to an external file, it can be loaded by the commandLoadNfg , as follows:

n := LoadNfg["filename.nfg"]

4.11.2. Extensive forms

50

Chapter 4. The Gambit Command Language

4.11.2.1. Creating a new extensive form

The functionNewEfg can be used to create a new extensive form game. In order to do anything with it, a variableshould be created to be the new extensive form game. Thus, the expression

e := NewEfg[]

will create a new extensive form game stored ine. The game is a trivial game with only one node, the root node, andno players (besides the chance player used to represent the realizations of random events). You can create a gamewhich has two players, named Fred and Alice, by specifying

e := NewEfg[{"Fred", "Alice"} ]

For an arbitrary extensive form game, a number of functions are available to get information about the game. Acomplete list is given in the section on “Getting Information” in the Categorical Function Reference section of thismanual. Some of the more important functions are given in the table.

Table 4-8. Overview of functions on extensive forms

Function Description

Actions[i] (user-defined) Actions at information seti

Actions[e] (user-defined) Actions in the gamee

Chance[e] Chance player ofe

Children[n] Child nodes of noden

History[n] (user-defined) History of actions preceeding noden

Infoset[n] Information set that noden belongs to

Infoset[a] Information set that actiona belongs to

Infosets[e] Information sets in the gamee

Members[i] Member nodes of information seti

Nodes[e] Nodes in the game tree of the gamee

NonterminalNodes[e] (user-defined) Nonterminal nodes of gamee

NthChild[n,j] The j th child of noden

Outcome[n] Outcome attached to noden

Outcomes[e] Outcomes for the gamee

Parent[n] Parent node of noden

Payoff[o,p] Payoff of outcomeo for playerp

Payoffs[o] (user-defined) Payoff vector of outcomeo

Payoffs[b] (user-defined) Payoff vector of profileb

Player[i] Player of information seti

Players[e] Players of the gamee

PriorAction[n] Action preceding noden

51

Chapter 4. The Gambit Command Language

Function Description

RootNode[e] Root node ofe

TerminalNodes[e] (user-defined) Terminal nodes of gamee

TheNthChild function has a short form ofn#j . So, the second child of the third child of the root node of anextensive form gamee can be obtained (if it exists) by the expressionRootNode[e]#3#2 .

4.11.2.2. Modifying an extensive form

A series of extensive form game editing functions are available for modifying an extensive form game. A completelist is given in the section on “Extensive form manipulation” in the Categorical Function Reference section of thismanual. The more important functions for building a game are given in the table.

Table 4-9. Functions for modifying extensive form games

Function Description

AddMove[i,n] Adds a move from infoseti to noden

AddMove[i,a] (user-defined) Adds a move from infoseti to actiona

CopyTree[n1,n2] Copies tree rooted at noden1 to noden2

InsertAction[i] Inserts an action into information seti

InsertMove[i,n] Inserts a move from infoseti at noden

MergeInfosets[i1,i2] Moves nodes from infoseti2 into i1

MoveToInfoset[n,i] Moves noden into infoseti

NewInfoset[p,j] Creates a new infoset for playerp with j actions

NewInfoset[p,list] (user-defined) Creates a new infoset forp with action names as in \list

NewOutcome[e,t] (user-defined) Creates a new outcome for the gamee with namet

NewPlayer[e,t] (user-defined) Creates a new player for the gamee with namet

Randomize[e,j] (user-defined) Randomizes the payoffs ine with seedj

Reveal[i,list] Reveals infoseti to players inlist

SetChanceProbs[i,list] Sets chance probs in infoseti to values inlist

SetOutcome[n,o] Attaches outcomeo to noden

SetPayoff[o,p,v] Sets payoff of outcomeo for playerp to valuev

SetPayoffs[o,list] (user-defined) Sets payoff of outcomeo to values inlist

The functions in the table can be used to build up any valid extensive form game from a trivial game. The basicprocedure by which a more complex game is constructed from a simple game is:

1. Create a new game, and create all players.

2. Iteratively add moves to the game. This involves two steps

52

Chapter 4. The Gambit Command Language

a.Construct a “template” for a move by creating an information set for a player with the desired choices(actions).

b. Add the move to the game for the appropriate histories of actions.

3. Reveal information about the moves to players that observe them.

4. Compute payoffs and attach outcomes to the game.

The next to last step (revealing information) may require considerable care for games with complex informationstructures. It is usually easiest to wait to do this step until the entire game tree is built, since Gambit does notmaintain a game of perfect recall as you add new moves. Hence, if you reveal a move of player 1 to player 2, andthen add new moves to the game for the player 2, the move that was revealed to player 2 will not be “remembered”by player 2 at the new moves.

The following sequence of commands builds the game tree for a simple poker game as described in [Mye91], asoutlined below.

Game Description:

Fred (Player 1) and Alice (Player 2) each ante $1.00 into the pot.Fred draws a card from a deck; Fred observes the card; Alice does not.Fred moves:If Fred Folds,Fred wins the pot if his card is Red (net gain of $1.00 to Fred).Fred loses the pot if his card is Black (net loss of $1.00 to Fred).

If Fred Raises, then Fred throws a dollar in the pot, and Alice moves:If Alice Passes, then Fred wins the pot (net gain of $1.00 to Fred)If Alice Meets, she throws a dollar in the pot; Fred must show the card:If the card is Red Fred wins the pot (net gain of $2.00 to Fred).If the card is Black Alice wins the pot (net loss of $2.00 to Fred)

To construct this game, first we create a new game, and the players. We create the players separately, usingNewPlayer so that we have variables to refer to them later:

e := NewEfg[];fred := NewPlayer[ e, "Fred"];alice := NewPlayer[e,"Alice"];

Now, we iteratively add moves to the game, by creating an information set with a template for the move, and thenadding that move to the game at the appropriate histories:

deal := NewInfoset[ Chance[e], {"Red", "Black"}];AddMove[deal,RootNode[e]];fredmove := NewInfoset[ fred , {"Raise", "Fold"} ];

53

Chapter 4. The Gambit Command Language

AddMove[ fredmove, TerminalNodes[e]];alicemove := NewInfoset[ alice , {"Meet", "Pass"} ];fredraised:=Filter[t:=TerminalNodes[e],Name[PriorAction[t]]="Raise"]AddMove[alicemove,fredraised];

In the above, the first move,deal , is a chance move. It is added at the root node of the game. The second move iscalledfredmove , and is added at the terminal nodes of the tree, since Fred gets to take this move for any draw of thecard. Since there are two terminal nodes the call toAddMove here is a listable call, and adds the move to bothterminal nodes of the tree. The third move is calledalicemove . Alice only gets to move if Fred chooses to raise. Sothe step computingfredraised identifies all of the terminal nodes whose prior action was named"Raise" . Themovealicemove is added at all of these nodes, via a listable call toAddMove. At this point, if you execute theexpression

Display[e]

you can launch the graphical interview to view the game in its current state. You will see that the game tree looks likethe game in [Mye91], except there are no payoffs yet, and Fred only has one information set. This is because you didnot yet account for the fact that the deal is revealed to Fred. You can reveal the deal to Fred (but not to Alice) via

Reveal[deal,{fred}];

and if you now display the game, then except for the fact that no payoffs have yet been defined, the game tree shouldlook like that in [Mye91]. Note that an alternate way to get the information structure correct is to create separateinformation sets for Fred’s moves from the outset. So, the expressions

fredmove := NewInfoset[fred , {"Raise", "Fold"}];AddMove[fredmove, TerminalNodes[e]];

in the above example could be replaced with

fredred := NewInfoset[fred , {"Raise", "Fold"}];fredblack := NewInfoset[fred , {"Raise", "Fold"}];AddMove[ fredred, RootNode[e]#1];AddMove[ fredblack, RootNode[e]#2];

(Here, the short formn#j for NthChild is used to refer to thej th child of noden). A move from the information setfredred is added to the first child of the root node (which is the action for chance in which the red card is selected)and a move from the second information setfredblack is added to the second child of the root node. Now, sincetwo separate information sets for Fred are created from the outset, there is no need to reveal the deal to Fred. As withlife in general, in the GCL there is usually more than one way to skin a cat.

To complete construction of this game, we must now add payoffs. This can be done with the following sequence ofexpressions

ante := 1.00;raise := 1.00;win := SetPayoffs[NewOutcome[e, "Win"],{ante,-ante}];winbig := SetPayoffs[NewOutcome[e, "Win Big"],{ante+raise,-ante-raise}];lose := SetPayoffs[NewOutcome[e, "Lose"],{-ante,ante}];losebig := SetPayoffs[NewOutcome[e, "Lose Big"],{-ante-raise,ante+raise}];SetOutcome[TerminalNodes[e],{winbig,win,win,losebig,win,lose}]

54

Chapter 4. The Gambit Command Language

This example has shown how to construct a simple game without any recursive structure. This game might be just aseasily created in the graphical interface. The usefulness of the GCL in constructing games comes when the game islarger, or has some repetitive structure to it. InAppendix Bis example showing how to construct a multi stageholdout game using user defined functions.

4.11.2.3. Saving and loading extensive forms

Once an extensive form game has been constructed, it can be saved by the expression

SaveEfg[e, "filename.efg"]

wheree is the extensive form game, andfilename.efg is the filename of the file to be created. It is recommendedthat the filename extension.efg be used when saving extensive form games, as the Gambit graphical user interfacerecognizes this extension as containing extensive form games. Once an extensive form game has been saved to anexternal file, it can be loaded by the functionLoadEfg , as follows:

e := LoadEfg["filename.efg"]

4.11.2.4. Creating a normal form from an extensive form

A normal form game can also be created from an extensive form game. Ife is an extensive form game, then theexpression

n := Nfg[e]

will create a normal form gamen which is the reduced normal form game associated with the extensive form gamee.

Strategies in the reduced normal form are given default names consisting of a series of digits, where thej th digit inthe strategy name corresponds to the branch number taken at the player’sj th information set. To illustrate, here wecreate the reduced normal form of the game of poker encountered earlier.

GCL1:= e:=LoadEfg["poker.efg"]GCL2:= << Name[Actions[e]]{ { { Raise, Fold }, { Raise, Fold } },

{ { Meet, Pass } } }GCL3:= n:=Nfg[e];GCL4:= << Name[Strategies[n]]{ { 11, 12, 21, 22 },

{ 1, 2 } }

55

Chapter 4. The Gambit Command Language

In the normal form game, player 1 has four strategies. Player 1’s second strategy has name12. This indicates that theplayer took action 1 (Raise) in the first information set, and action 2 (Fold) in the second information set.

When a normal form gamen is created from an extensive form game, the GCL will “remember” the extensive formgame thatn is associated with, as long as neither the extensive or normal form game is edited. Any mixed strategysolutions computed on the normal form gamen can be converted back to a behavior strategy of the gamee by usingthe commandBehav . Thus

n := Nfg[e];m := EnumMixedSolve[n];b := Behav[m]

will convert the gamee to reduced normal form, solve it using theEnumMixedSolve algorithm, and then convert allmixed profiles found back to behavior profiles, and display the list,b of behavior profiles found. The above can alsobe done in one command without saving intermediate steps as follows:

b := Behav[EnumMixedSolve[Nfg[e]]]

4.11.3. Solving games

Every finite game has at least one Nash equilibrium in either pure or mixed strategies [Nas50]. Various refinementsof Nash equilibrium are frequently used to select reasonable equilibria in games with multiple equilibria. The mostcommonly studied refinements are perfect and proper equilibria for normal form games, and subgame perfect andsequential equilibria for extensive form games.1

The best way to compute an equilibrium depends on many factors, the most important of which are the number ofplayers, the number of equilibrium you want to find, and what kind of refinement you are looking for. For a detaileddiscussion of these issues, see [McKMcL96]. In general, it is easier to solve two person games than n-person games,it is easier to find one equilibrium than to find all, and it is easier to find a Nash equilibrium than a refinement.

The computational complexity of solving for equilibria of games also typically at least exponential in the number ofstrategies or actions. Consequently, you will find it quite easy to build games in Gambit which cannot be solved (inany reasonable amount of time) by Gambit.

When solving games of any reasonable size, it is therefore good to try and simplify things as much as possible beforelaunching into a solution algorithm. One way of simplifying a game is by reducing the size of the strategy set byelimination of dominated strategies. For extensive form games, a second way of simplifying the problem is by takingaccount of the subgame structure of the game, and then recursively solve the game from the end.

56

Chapter 4. The Gambit Command Language

4.11.4. Supports and dominance elimination

The GCL data types NFSUPPORT and EFSUPPORT are used to represent a support in a normal or extensive formgame. A support for a normal form game is a selection of non-empty subsets of strategies for all players in the game.A support for an extensive form game is a selection of non-empty subsets of actions for all information sets in thegame.

The main use of supports is to represent the sets of strategies that remain after dominated strategies have beeneliminated from the game. All of the built-in functions for solution algorithms in the GCL take an NFSUPPORT orEFSUPPORT as their first parameter, hence can be run on any support of the game.

The callSupport[g] returns the full support of the normal or extensive form gameg. The full support is the supportin which no strategies (or actions) have been eliminated. The functionUnDominated can be used to find thedominated strategies or strategies in a support of a game.UnDominated returns a support containing theundominated strategies for each player (or actions for each information set, in the case of extensive for games). Bydefault weak domination is used, and only domination by pure strategies is considered. By setting one or both of theoptional parametersstrong andmixed to True , strong domination can be used, and domination by mixedstrateies can be considered.2 The following sequence of expressions shows the computation of the full supports andthe support resulting from weak dominance elimination in the extensive and reduced normal form of the pokerexample of the previous chapter.

GCL1:= e:=LoadEfg["poker.efg"]GCL2:= efsupp:=UnDominated[e]GCL3:= << Name[Actions[e]]{ { { Raise, Fold }, { Raise, Fold } },

{ { Meet, Pass } } }GCL4:= << Name[Actions[efsupp]]{ { { Raise }, { Raise, Fold } },

{ { Meet, Pass } } }GCL5:= n:=Nfg[e];GCL6:= nfsupp:=UnDominated[n];GCL7:= << Name[Strategies[n]]{ { 11, 12, 21, 22 },

{ 1, 2 } }GCL8:= << Name[Strategies[nfsupp]]{ { 11, 12 },

{ 1, 2 } }

In the above example, for the extensive form game, the action with name "Fold" is dominated, and eliminated byUnDominated . Correspondingly, in the reduced normal form game, the strategies in which the first player takes thesecond action at the first information set is eliminated.

A user defined functionIterativeUnDominated can be used to iteratively eliminate dominated strategies in agame, until no further dominance elimination is possible. This function returns the final support. So the program

57

Chapter 4. The Gambit Command Language

n:=LoadNfg["mygame.nfg"];s:=IterativeUnDominated[n,strong->True,mixed->True];

will find the set of all strategies that remain after iterative elimination by mixed strategies of strongly dominatedstrategies in the gamen.

While the main use of supports is to represent strategies that remain after dominance elimination, you can alsoconstruct your own support for a game using the functionsRemoveStrategy andAddStrategy .

4.11.5. Subgames

For extensive form games, Gambit recognizes and supports the notion of a subgame. Ifefg is an extensive formgame, the callSubgames[efg] returns a list of nodes representing the roots of valid subgames.

You can control the way the extensive form solution algorithms deal with subgames by “marking” or “unmarking”subgames. All of the extensive form solution algorithms recursively solve the extensive form game by subgames, butonly for subgames that are marked. Terminal marked subgames are solved first, and then for any solution of thesubgame, the parent game is pruned, plugging in the continuation value generated by the terminal subgame. Themarked subgames that are now terminal are then recursively solved in a similar manner, and so on, until the gamestarting at the root node is reached. Be warned that if there are multiple equilibria to each subgame, the size of the setof solutions to the full game that are generated by this procedure can be exponential with the number of subgames.

When you first construct a game, the only subgame that is marked is the root node of the tree. This node alwaysrepresents a valid subgame, and it is not possible to unmark the root node. Ifnode is the root of a valid non-trivialsubgame, then the functionsMarkSubgame andUnMarkSubgame can be used to mark and unmark the specificsubgames starting at that node.MarkedSubgamd can be used to check if the subgame is marked. The user definedfunctionsMarkSubgames andUnMarkSubgames can be used to mark and unmark all valid subgames in the game.MarkedSubgames returns a lsit of root nodes of all currently marked subgames.

The technique of marking subgames can be used to control whether a solution algorithm that finds Nash equilibriareturns any Nash equilibrium or only subgame perfect Nash equilibria of the game. If no subgames are marked, thealgorithm will return Nash equilibria which may not be subgame perfect. If you first mark all subgames, thealgorithm will return subgame perfect equilibria.

4.11.6. Mixed and behavior strategy profiles

The data types MIXED and BEHAV are used to represent mixed and behavior strategy profiles for normal andextensive form games, respectively. Mixed and behavior strategy profiles can be defined on any support of the game.A mixed strategy profile is a specification of a numeric value (usually interpreted as a probability) for each strategyin the support. Similarly, a behavior strategy profile is a specification of a numeric value (usually interpreted as aprobability) for each action in the support.

58

Chapter 4. The Gambit Command Language

The simplest way of generating a mixed profile for a game is to use the built-in functionCentroid , which generatesa mixed or behavior strategy profile in which every player adopts each of their strategies (or each action in aninformation set) with equal probability. For example, ifg is a variable representing an extensive or normal formgame, ands is a support for the gameg, then the callsCentroid[g] or Centroid[s] generate mixed strategyprofiles for the game and support, respectively. You can use the functionSetStrategyProbs SetActionProbs tochange the strategy probabilites for a mixed or behavior profile. You can also use the standard user defined functionsMixed or Behav to generate a mixed profile from a nested list of numeric data, as long as the nested list is of thecorrect dimensions.

Basic arithmetic operations are defined on mixed and behavior profiles as well. So you can take linear combinationsof mixed profiles to create new mixed profiles, as illustrated in this example:

GCL1:= n:=Nfg[{{{3,1},{0,0}},{{0,1},{3,0}},{{1,0},{1,3}}}];GCL2:= << c:=Centroid[n](Mixed) { 1/3 1/3 1/3 }{ 1/2 1/2 }GCL3:= << cc:=Mixed[n,{{1,0,0},{1,0}}](Mixed) { 1 0 0 }{ 1 0 }GCL4:= << m:=1/2*c+1/2*cc(Mixed) { 2/3 1/6 1/6 }{ 3/4 1/4 }

In most cases, the value assigned to an action or strategy is interpreted as the probability with which a player adoptsthe corresponding action or strategy. However, the data for MIXED or BEHAV need not be legitimate probabilities.For example, it would be valid to create a mixed profile using the callMixed[n,{{1,2,3},{4,5}}] . Probabilitiesare not required to add up to one, or even to be positive. This feature is especially useful in econometric analysis, asthe MIXED and BEHAV data types can be used to represent choice frequencies of corresponding actions orstrategies.

All of the solution algorithms that operate on games or their supports return lists of mixed or behavior profiles torepresenting the solutions. Some algorithms compute important additional information about the profile that may notbe recoverable from knowledge of just the strategy probabilies. Consequently, the MIXED an BEHAV data typeskeep track of who created them, and what properties are known about them. A series of functions are available toquery profiles to return this information. These functions are listed in section on “information about solutions” in theCategorical Function Reference chapter. To view all of the information that is known about a mixed or behaviorprofile, you can change the format by which solutions are displayed using theFormat function.

Notes1. Definitions of perfect and subgame perfect equilibria are from [Sel75], proper equilibrium from [Mye78], and

sequential equilibrium from [KreWil82]. See [vanD83] or [Mye91] for general treatments of refinements.

2. Elimination by mixed strategies is only implemented for normal form games.

59

Chapter 5. Command Language Function Reference

Function reference goes here

5.1. Built-in functions

This section lists in alphabetical order all the functions which are predefined in the command language. SeeSection5.2for a listing of functions by category.

Accuracy

NameAccuracy — Returns the accuracy used by the algorithm which computed a profile

Synopsis

Accuracy[profile->BEHAV] =: NUMBERAccuracy[profile->MIXED] =: NUMBER

Description

Accuracy returns the accuracy ofprofile . The accuracy is the error that is allowed in the computation of whichNash refinements the profile satified. Thus, if the profile is marked as Nash, then no deviation by any player can yieldan improvement of more than the returned accuracy.

ActionNumber

NameActionNumber — Returns the index of an action in a support or basis

60

Chapter 5. Command Language Function Reference

Synopsis

ActionNumber[action->ACTION, sup->EFSUPPORT] =: INTEGERActionNumber[action->ACTION, basis->EFBASIS] =: INTEGER

Description

Returns the number assigned toaction in the supportsup or basisbasis . For each information set, actions arenumbered from 1 to the number of actions at the information set. If an action is not in the corresponding support orbasis,ActionNumber returns 0.

See also

Actions

ActionProb

NameActionProb — Returns the probability an action is chosen in a behavior profile

Synopsis

ActionProb[profile->BEHAV, action->ACTION] =: NUMBER

Description

ActionProb returns the probability thataction is chosen at its information set when all players are followingprofile . If action is a chance action, the probability of chance selecting the action is returned. If the probabilityis not specified by the profile, the null value is returned. It is an error ifprofile andaction are not from thesame extensive form game.

See also

SetActionProbs.

61

Chapter 5. Command Language Function Reference

Actions

NameActions — Returns the list of actions in a support at an information set

Synopsis

Actions[infoset->INFOSET*, support->EFSUPPORT] =: LIST(ACTION)Actions[infoset->INFOSET*, basis->EFBASIS] =: LIST(ACTION)

Description

Actions returns the list of actions available atinfoset in support or basis . If infoset is the nullinformation set, the empty list of actions is returned. It is an error ifinfoset andsupport (or basis ) are notfrom the same extensive form game.

ActionValue

NameActionValue — Returns the expected payoff to playing an action, given a profile

Synopsis

ActionValue[profile->BEHAV, action->ACTION] =: NUMBER

Description

ActionValue returns the expected payoff to a player (who is in control of the information set includingaction )of choosingaction when all players are followingprofile . If the value is not well-defined, the null value isreturned. It is an error ifprofile andaction are not from the same extensive form game, or ifaction is anaction at an information set owned by the chance player.

62

Chapter 5. Command Language Function Reference

See also

Belief, InfosetProb, NodeValue, RealizProb.

AddAction

NameAddAction — Adds an action to a support or basis

Synopsis

AddAction[support->EFSUPPORT, action->ACTION] =: EFSUPPORTAddAction[basis->EFBASIS, action->ACTION] =: EFSUPPORT

Description

AddAction adds the actionaction to support (or basis ). If the action is already in the support, no change ismade. A copy of the modified support is returned. It is an error ifsupport (or basis ) andaction are not fromthe same extensive form game.

See also

Basis, RemoveAction, Support.

AddMove

NameAddMove — Adds a move to a game at a terminal node

63

Chapter 5. Command Language Function Reference

Synopsis

AddMove[infoset->INFOSET, node->NODE] =: NODE

Description

AddMove places a terminalnode into the information setinfoset . The result isnode becomes a decision node,with number of branches equal to the number of actions ininfoset . New child nodes are created as successornodes to the actions in the information set. The child which succeeds the first action is returned. It is an error ifnodeandinfoset are not from the same extensive form game, or ifnode is not a terminal node.

See also

DeleteMove, InsertMove, NewInfoset.

AddNode

NameAddNode — Adds a node to a basis

Synopsis

AddNode[basis->EFBASIS, node->NODE] =: EFBASIS

Description

AddNode adds the nodenode to the basisbasis . If node is already inbasis , no change is made. A copy of themodified basis is returned. It is an error ifbasis andnode are not from the same extensive form game.

See also

AddAction, Basis, RemoveNode, Support.

64

Chapter 5. Command Language Function Reference

AddStrategy

NameAddStrategy — Adds a strategy to a support

Synopsis

AddStrategy[support->NFSUPPORT, strategy->STRATEGY] =: NFSUPPORT

Description

AddStrategy addsstrategy to thesupport . If the strategy is already in the support, no change is made. Acopy of the modified support is returned. It is an error ifsupport andstrategy are not from the same normalform game.

See also

RemoveStrategy, Support.

AgentForm

NameAgentForm — Creates the agent normal form for an extensive form game

Synopsis

AgentForm[efg->EFG, {time<->0}] =: NFG

Description

AgentForm creates and returns the agent normal form representation ofefg . The optional parametertime , ifspecified, returns the amount of time consumed by the conversion.

65

Chapter 5. Command Language Function Reference

See also

Nfg.

And

NameAnd — Returns the logical conjunction of two boolean values

Synopsis

And[x->BOOLEAN, y->BOOLEAN] =: BOOLEAN

Description

And computes the logical conjunction ofx andy , defined by the truth table:

True False Unknown

True True False Unknown

False False False False

Unknown Unknown False Unknown

Short forms

x && y, x AND y.

See also

Not, Or.

66

Chapter 5. Command Language Function Reference

ArgMax

NameArgMax — Returns the index of a maximal element of a list

Synopsis

ArgMax[x->LIST(NUMBER)] =: INTEGER

Description

ArgMax returns the index of the first element of the listx which attains the maximum value of any elements in thelist.

Assign

NameAssign — Sets the value of a variable

Synopsis

Assign[name->TEXT, value->T*] =: T

Description

Assign creates a new variablename, with valuevalue . Returns the value assigned. Ifname is already a definedvariable in the current scope, then if it is of type T, it is modified to have return value ofvalue . If it is of a differenttype, an error results.

Short form

x := value

67

Chapter 5. Command Language Function Reference

See also

Clear, UnAssign.

Basis

NameBasis — Creates a basis for an extensive form game

Synopsis

Basis[efg->EFG] =: EFBASIS

Description

Basis creates and returns a new basis for the gameefg . The basis contains all nodes and all actions in the game.

See also

AddNode, RemoveNode, Support.

Behav

NameBehav — Converts a mixed profile into the equivalent behavior profile

Synopsis

Behav[mixed->MIXED] =: BEHAV

68

Chapter 5. Command Language Function Reference

Description

Behav convertsmixed to the equivalent behavior strategy profile on the associated extensive form game usingKuhn’s Theorem. It is an error if there is no extensive form game associated with the normal form game ofprofile .Note that this function assumes that the associated extensive form game is a game of perfect recall. If it is not, thenthe resulting behavior profile is unpredictable, and may not be a valid profile.

See also

Mixed.

Behav

NameBehav — Creates a behavior profile on a support

Synopsis

Behav[support->EFSUPPORT] =: BEHAV

Description

Behav returns a behavior strategy profile with equal probabilities for all actions insupport in each sameinformation set.

See also

Mixed.

69

Chapter 5. Command Language Function Reference

Belief

NameBelief — Returns the probability of being at a node, given the information set

Synopsis

Belief[profile->BEHAV, node->NODE] =: NUMBER

Description

Belief returns the probability of being atnode , conditional on the player who chooses atnode knowing she is innode ’s information set, assuming all players followprofile . The null value is returned if the belief value is notwell-defined, or ifnode is terminal. It is an error ifprofile andnode are not from the same extensive form game.

See also

ActionValue, InfosetProb, NodeValue, RealizProb.

Chance

NameChance — Returns the chance player for an extensive form

Synopsis

Chance[efg->EFG] =: EFPLAYER

Description

Chance returns the chance, or nature, player defined onefg . Each extensive form has exactly one chance playerpredefined, and it is not possible to define any additional chance players.

70

Chapter 5. Command Language Function Reference

ChanceProb

NameChanceProb — Returns the probability an action is chosen by nature

Synopsis

ChanceProb[action->ACTION] =: NUMBER

Description

ChanceProb returns the probability ofaction being chosen at its information set by the chance player. It is anerror if action is not an action which is chosen by the chance player.

See also

SetChanceProbs.

Children

NameChildren — Returns the list of children of a node

Synopsis

Children[node->NODE] =: LIST(NODE)

Description

Children returns the list of children ofnode .

71

Chapter 5. Command Language Function Reference

See also

Parent.

Clear

NameClear — Unassigns all variables in the current scope

Synopsis

Clear[] =: BOOLEAN

Description

Clear unassigns all variables defined in the current scope. ReturnsTrue .

See also

Assign, UnAssign.

Comment

NameComment— Returns the comment associated with a game

Synopsis

Comment[efg->EFG] =: TEXTComment[nfg->NFG] =: TEXT

72

Chapter 5. Command Language Function Reference

Description

Comment returns the comment associated with the gameefg or nfg .

See also

SetComment.

CompressEfg

NameCompressEfg — Creates an extensive form containing only the actions in a support

Synopsis

CompressEfg[support->EFSUPPORT] =: EFG

Description

CompressEfg creates a copy of the extensive form game on whichsupport is defined, where all actions notpresent insupport have been removed.

CompressNfg

NameCompressNfg — Creates a normal form containing only the actions in a support

Synopsis

CompressNfg[support->NFSUPPORT] =: NFG

73

Chapter 5. Command Language Function Reference

Description

CompressNfg creates a copy of the normal form game on whichsupport is defined, where all strategies notpresent insupport have been removed.

Concat

NameConcat — Concatenates two lists

Synopsis

Concat[x->NLIST(T), y->NLIST(T)] =: LIST(T)

Description

Concat returns the concatenation of the listsx andy .

Short form

x & y

Contains

NameContains — Tests for the presence of an element in a list

Synopsis

Contains[list->NLIST(T), x->T] =: BOOLEANContains[list->NLIST(T), x->LIST(T)] =: BOOLEAN

74

Chapter 5. Command Language Function Reference

Description

Contains returnsTrue when the valuex is contained inlist .

See also

NthElement.

CopyTree

NameCopyTree — Copies a subtree to a terminal node

Synopsis

CopyTree[from->NODE, to->NODE] =: NODE

Description

CopyTree copies the subtree rooted atfrom to the terminal nodeto in the same extensive form game. The nodes inthe copied subtree belong to the same information sets as their counterparts in the original subtree. Returns the nodeto . It is an error iffrom andto are not from the same extensive form game, or ifto is not a terminal node. Thefunction has no effect if the copying operation would violate the currently marked subgame structure.

See also

MoveTree.

75

Chapter 5. Command Language Function Reference

Creator

NameCreator — Returns the algorithm that created a profile

Synopsis

Creator[profile->MIXED] =: TEXTCreator[profile->BEHAV] =: TEXT

Description

Creator returns the GCL function name (excluding theSolve suffix) of the algorithm that was called to create theprofile. For behavior profiles, the string includes an indication of whether the extensive or normal form version of thealgorithm was used. Thus,Liap[EFG] andLiap[NFG] are used to identify the extensive and normal form versionsof the algorithm. A profile created by the user is identified byUser .

Date

NameDate — Returns the current date and time

Synopsis

Date[] =: TEXT

Description

Date returns the current date and time.

76

Chapter 5. Command Language Function Reference

DeleteAction

NameDeleteAction — Removes an action from all nodes in its information set

Synopsis

DeleteAction[action->ACTION] =: INFOSET

Description

DeleteAction deletesaction from its information set. As a consequence, the corresponding subtrees associatedwith the action from each member of the information set are deleted. Returns the information set to whichactionbelonged. It is an error ifaction is the only action at its information set.

See also

Actions, InsertAction.

DeleteEmptyInfoset

NameDeleteEmptyInfoset — Removes an information set from a game

Synopsis

DeleteEmptyInfoset[infoset->INFOSET] =: BOOLEAN

Description

DeleteEmptyInfoset deletesinfoset from its extensive form game. An information set may be deleted onlywhen it has no members; otherwise, this function has no effect. ReturnsTrue when the information set wassuccessfully deleted.

77

Chapter 5. Command Language Function Reference

See also

Members, NewInfoset.

DeleteMove

NameDeleteMove — Removes a move from an extensive form game

Synopsis

DeleteMove[node->NODE, keep->NODE] =: NODE

Description

DeleteMove deletesnode from its extensive form game. The subtree rooted in nodekeep , which must be a childof node , is kept, andkeep takes the place ofnode in the tree. All other subtrees descending fromnode aredeleted. The kept nodekeep is returned. It is an error ifkeep is not a child ofnode , or if keep andnode are notfrom the same extensive form game.

See also

AddMove, DeleteTree, InsertMove.

DeleteOutcome

NameDeleteOutcome — Removes an outcome from a game

78

Chapter 5. Command Language Function Reference

Synopsis

DeleteOutcome[outcome->EFOUTCOME] =: LIST(NODE)DeleteOutcome[outcome->NFOUTCOME] =: BOOLEAN

Description

DeleteOutcome removesoutcome from its game. All nodes (for extensive forms) or contingencies (for normalforms) with the specified outcome attached are reset to having no outcome attached. The extensive form versionreturns the list of nodes to which the outcome was attached; the normal form version returnsTrue .

See also

NewOutcome.

DeleteTree

NameDeleteTree — Removes a subtree from an extensive form game

Synopsis

DeleteTree[node->NODE] =: NODE

Description

DeleteTree deletes the subtree rooted atnode . The node then becomes a terminal node, which is returned.

See also

DeleteMove.

79

Chapter 5. Command Language Function Reference

Divide

NameDivide — Returns the quotient of two numbers

Synopsis

Divide[x->NUMBER, y->NUMBER] =: NUMBER

Description

Divide returns the quotientx divided byy .

Short form

x / y

See also

IntegerDivide.

Dot

NameDot — Returns the dot product of two vectors

Synopsis

Dot[x->LIST(NUMBER), y->LIST(NUMBER)] =: NUMBER

80

Chapter 5. Command Language Function Reference

Description

Dot returns the dot product ofx andy , where the lists are treated as vectors. It is an error to attempt to multiply twolists of different lengths.

Short form

x . y

ElapsedTime

NameElapsedTime — Returns the time on the stopwatch

Synopsis

ElapsedTime[] =: NUMBER

Description

If the system stopwatch is currently running,ElapsedTime returns the time elapsed since the stopwatch was started.If the system stopwatch is not running,ElapsedTime returns the time elapsed during the last period during whichthe stopwatch was running.

See also

IsWatchRunning, StartWatch, StopWatch.

81

Chapter 5. Command Language Function Reference

EnumMixedSolve

NameEnumMixedSolve — Computes Nash equilibria via mixed strategy enumeration

Synopsis

EnumMixedSolve[support->NFSUPPORT, {stopAfter->0},{precision->Float}, {nPivots<->0},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}, {cliques->False}] =: LIST(MIXED)

EnumMixedSolve[support->EFSUPPORT, {asNfg->False},{stopAfter->0}, {precision->Float},{nPivots<->0}, {time<->0.000000},{traceFile<->(Output)}, {traceLevel->0},{cliques->False}] =: LIST(BEHAV)

Description

EnumMixedSolve returns the extreme points of the set of all Nash equilibria (pure or mixed) for a two person gameusingsupport .

The following optional parameters may be used to modify the behavior of the algorithm:

• asNfg : By default, this isFalse . If it is specified to beTrue , the extensive form game is solved by recursivelyconverting its marked subgames into normal form, solving, and reconstructing the solution as a behavior profile.Note that this algorithm is only implemented on the normal form, so this parameter must always be specified andTrue .

• stopAfter : By default, all equilibria are found. This parameter may be used to specify a maximum number ofequilibria to be found.

• precision : Determines the precision of the computation. Default is floating point precision (Float ).

• cliques : If True , then the connected components and their maximal cliques are computed. The output isprinted to the console.

See also

LcpSolve.

82

Chapter 5. Command Language Function Reference

EnumPureSolve

NameEnumPureSolve — Computes Nash equilibria via pure strategy enumeration

Synopsis

EnumPureSolve[support->NFSUPPORT, {stopAfter->0},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(MIXED)

EnumPureSolve[support->EFSUPPORT, {asNfg->False},{stopAfter->0}, {precision->Float},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(BEHAV)

Description

Returns all pure strategy Nash equilibria of a game using the givensupport . The behavior of the algorithm may bemodified by the following optional parameters:

• asNfg : By default, this isFalse . If it is specified to beTrue , the extensive form game is solved by recursivelyconverting its marked subgames into normal form, solving, and reconstructing the solution as a behavior profile.

• stopAfter : By default, all equilibria are found. This parameter may be used to specify a maximum number ofequilibria to be found.

Equal

NameEqual — Determines if two values are equal

Synopsis

Equal[x->T*, y->T*] =: BOOLEAN

83

Chapter 5. Command Language Function Reference

Description

Equal returnsTrue whenx andy are equal. For games,x andy are considered equal when they refer to the samegame (but not if they refer to two different games with exactly the same structure, payoffs, and so forth). A null valueis considered equal to the null value, but is not equal to any non-null value.

Short form

x = y

See also

NotEqual.

ExePath

NameExePath — Returns the path of the GCL executable

Synopsis

ExePath[{file->True}, {path->True}] =: TEXT

Description

ExePath returns the path of the GCL executable. Iffile is True , the filename is included. Ifpath is True , thepath to the executable is included.

See also

GetPath.

84

Chapter 5. Command Language Function Reference

Exp

NameExp — Evaluates the exponential function

Synopsis

Exp[x->NUMBER] =: NUMBER

Description

Exp returns the value of the exponential function evaluated atx . The result is always in floating-point precision,regardless of the precision ofx .

See also

Log, Power.

Filter

NameFilter — Filters a list based on a criterion

Synopsis

Filter[x->NLIST(T*), y->NLIST(BOOLEAN)] =: LIST(T)

Description

Filter returns a list with the same dimension structure aslist , with the elements for which the correspondingelements ofby areFalse removed. It is an error ifx andy do not have the same dimensionality.

85

Chapter 5. Command Language Function Reference

See also

Sort.

Flatten

NameFlatten — Removes nesting from a list

Synopsis

Flatten[x->NLIST(T*), {levels->0}] =: LIST(T)

Description

Flatten returns a list with the same elements asx , with the nesting structure flattened. By default, all levels areflattened, returning a one-dimensional list; the optional parameterlevels may be used to limit the flattening to thetopmostlevels .

Float

NameFloat — Converts a number to floating-point precision

Synopsis

Float[x->NUMBER] =: NUMBER

Description

Float returnsx converted to the machine’s floating point representation.

86

Chapter 5. Command Language Function Reference

See also

Rational.

For

NameFor — Iterates over a block of functions

Synopsis

For[statement-list, boolean-expression,statement-list, statement-list]

Description

For defines a piece of code to be executed repeatedly. See the section on control structures for complete information.

See also

While.

Format

NameFormat — Sets various formatting options

Synopsis

Format[x->NUMBER, {width<->0}, {decimals<->6}, {expmode<->False}] =: NUMBERFormat[x->TEXT, {quote<->False}] =: TEXTFormat[x->MIXED, {info<->False}, {names<->False}] =: MIXED

87

Chapter 5. Command Language Function Reference

Format[x->BEHAV, {info<->False}, {names<->False}] =: BEHAVFormat[x->EFG, {decimals<->6}] =: EFGFormat[x->NFG, {decimals<->6}] =: NFG

Description

Format sets various formatting options.

The first version sets the formatting style for output of NUMBER data types on output streams.

• width : The width for a numeric field. If the width of the data is greater thanwidth , the width is overridden.(The default is 0.)

• decimals : The number of decimal places shown for floating point numbers.

• expmode : If True , floating point numbers are printed in exponential format.

The second version sets the formatting style for output of text on output streams.

• quote : Whether opening and closing quotation marks are written. The default isTrue .

The third and fourth versions set the formatting style for output of profiles on output streams.

• info: The amount of information to be displayed. IfTrue , displays all of the information about the profile. IfFalse , only the strategy or action probabilities are displayed.

• names: If True , the profiles are printed in a sparse format, with only positive-probability strategy or actionprofiles displayed, tagged by their strategy or action labels. IfFalse , the whole vector (including zeroes) isprinted, without any labels.

The fifth and sixth versions set the formatting style for game savefiles.

• decimals : The number of decimal places to use in representing floating-point numbers.

See also

ListFormat, Write.

88

Chapter 5. Command Language Function Reference

Game

NameGame— Returns the game to which an object belongs

Synopsis

Game[player->NFPLAYER] =: NFGGame[strategy->STRATEGY] =: NFGGame[outcome->NFOUTCOME] =: NFGGame[player->EFPLAYER] =: EFGGame[node->NODE] =: EFGGame[outcome->EFOUTCOME] =: EFGGame[infoset->INFOSET] =: EFGGame[profile->MIXED] =: NFGGame[profile->BEHAV] =: EFGGame[support->NFSUPPORT] =: NFGGame[support->EFSUPPORT] =: EFGGame[support->EFBASIS] =: EFG

Description

Gamereturns the extensive or normal form game to which the parameter belongs.

GetEnv

NameGetEnv — Returns the value of an environment variable

Synopsis

GetEnv[name->TEXT] =: TEXT

89

Chapter 5. Command Language Function Reference

Description

GetEnv returns the string associated with environment variablename.

See also

SetEnv, UnSetEnv.

GetFormat

NameGetFormat — Returns information on output formatting

Synopsis

GetFormat[x->NUMBER, {width<->0}, {decimals<->6}, {expmode<->False}] =: NUMBERGetFormat[x->TEXT, {quote<->False}] =: TEXTGetFormat[x->MIXED, {info<->False}, {names<->False}] =: MIXEDGetFormat[x->BEHAV, {info<->False}, {names<->False}] =: BEHAVGetFormat[x->EFG, {decimals<->6}] =: EFGGetFormat[x->NFG, {decimals<->6}] =: NFG

Description

GetFormat returns the current formatting style.

The first version reports on output style of values of type NUMBER.

• width : The width for a numeric field.

• decimals : The number of decimal places shown for floating point numbers.

• expmode : Whether floating point numbers are printed in exponential format.

The second version reports on output formatting for values of type TEXT.

• quote : Whether opening and closing quotation marks are written.

90

Chapter 5. Command Language Function Reference

The third and fourth versions report on formatting styles for strategy profiles.

• info : Displays all information known about profile ifTrue . If False , just displays strategy or actionprobabilities.

• names: If True , the profiles are printed in a sparse format, with only positive-probability strategy or actionprofiles displayed, tagged by their strategy or action labels. IfFalse , the whole vector (including zeroes) isprinted, without any labels.

The fifth and sixth versions report on formatting of output of extensive and normal form savefiles.

• decimals : The number of decimal places to use in representing floating-point numbers.

See also

Format.

GetListFormat

NameGetListFormat — Returns information on list output formatting

Synopsis

GetListFormat[{braces<->True}, {commas<->True},{lf<->2}, {indent<->2}] =: BOOLEAN

Description

GetListFormat returns the current formatting style for output of lists on output streams.

• braces : If True , lists are delimited by braces.

• commas: If True , elements are delimited by commas.

91

Chapter 5. Command Language Function Reference

• lf : Number of levels of list that are displayed with a line feed.

• indent : Number of spaces to indent each level of a list.

See also

Format, Write.

GetPath

NameGetPath — Returns the path of the currently-read input file

Synopsis

GetPath[] =: TEXT

Description

GetPath returns the path to the file in which the command is included.

See also

ExePath, Include.

Greater

NameGreater — Determines whether a value is greater than another

92

Chapter 5. Command Language Function Reference

Synopsis

Greater[x->NUMBER, y->NUMBER] =: BOOLEANGreater[x->TEXT, y->TEXT] =: BOOLEAN

Description

Greater returnsTrue whenx is strictly greater thany . ForTEXTvalues, the ordering of the machine’s character setis used.

Short form

x > y

See also

GreaterEqual, Less, LessEqual.

GreaterEqual

NameGreaterEqual — Determines whether a value is greater than or equal to another

Synopsis

GreaterEqual[x->NUMBER, y->NUMBER] =: BOOLEANGreaterEqual[x->TEXT, y->TEXT] =: BOOLEAN

Description

GreaterEqual returnsTrue whenx is greater than or equal toy . ForTEXTvalues, the ordering of the machine’scharacter set is used.

93

Chapter 5. Command Language Function Reference

Short form

x >= y

See also

Greater, Less, LessEqual.

Help

NameHelp — Returns help on defined functions

Synopsis

Help[x->TEXT, {udf->True}, {bif->True}] =: LIST(TEXT)

Description

Help returns a list of all function names or function prototypes matchingx . If x is an exact match to a functionname, a list of corresponding function prototypes is returned.x can also contain the regular-expression stylewildcards* and?. In this case, if there is not an exact match, a list of function names matchingx is returned. Theparameterudf determines if user defined functions are listed, andbif determines if built in functions are listed.Both of these parameters areTrue by default.

See also

HelpVars.

94

Chapter 5. Command Language Function Reference

HelpVars

NameHelpVars — Returns help on defined variables

Synopsis

HelpVars[x->TEXT] =: LIST(TEXT)

Description

HelpVars returns a list of all variables matchingx . The parmeterx can contain regular-expression style wildcards*

and?. In this case, if there is not an exact match, a list of variables matchingx is returned.

See also

Help.

If

NameIf — Evaluates expressions conditionally

Synopsis

If[boolean-expression, statement-list]If[boolean-expression, statement-list, statement-list]

Description

If defines a block of statements to be executed under certain conditions. See the section on control structures forcomplete information.

95

Chapter 5. Command Language Function Reference

Include

NameInclude — Reads GCL expressions from a file

Synopsis

Include[file->TEXT] =: BOOLEAN

Description

Include includes the contents in the specified file in the running GCL program. The function returnsTrue if filewas successfully opened, andFalse otherwise.Include may only be used at the top level, that is, it cannot be usedinside ofNewFunction or flow control structures.

Index

NameIndex — Returns the indices at which a value appears in a list

Synopsis

Index[list->NLIST(T), x->T] =: LIST(INTEGER)Index[list->NLIST(T), x->LIST(T)] =: LIST(INTEGER)

Description

Index returns the list of indices inlist wherex appears.

96

Chapter 5. Command Language Function Reference

See also

NthElement.

Infoset

NameInfoset — Returns the information set to which an action or node belongs

Synopsis

Infoset[action->ACTION*] =: INFOSETInfoset[node->NODE*] =: INFOSET

Description

Infoset returns the information set to whichaction or node belongs. The null action or node is assumed tobelong to the null information set.

See also

Actions, Members.

InfosetProb

NameInfosetProb — Returns the probability of reaching an information set

Synopsis

InfosetProb[profile->BEHAV, infoset->INFOSET*] =: NUMBER

97

Chapter 5. Command Language Function Reference

Description

InfosetProb returns the probability of reachinginfoset when all players followprofile . The probability ofreaching the null information set is defined to be null. It is an error ifprofile andinfoset are not defined on thesame extensive form game.

See also

ActionValue, Belief, NodeValue, RealizProb.

Infosets

NameInfosets — Returns the information sets for a player

Synopsis

Infosets[player->EFPLAYER] =: LIST(INFOSET)

Description

Infosets returns the list of information sets at whichplayer has the decision.

See also

Player.

InfosetValue

NameInfosetValue — Returns the value of reaching an information set

98

Chapter 5. Command Language Function Reference

Synopsis

InfosetValue[profile->BEHAV, infoset->INFOSET*] =: NUMBER

Description

InfosetValue returns the value to the controlling player of reachinginfoset when all players followprofile .It is an error ifprofile andinfoset are not defined on the same extensive form game.

See also

ActionValue, Belief, NodeValue, RealizProb.

Input

NameInput — Opens an input stream for reading

Synopsis

Input[file->TEXT] =: INPUT

Description

Input opens a new input stream for reading from the filetext . An error occurs if the file is not able to be opened.

See also

Output, Read.

99

Chapter 5. Command Language Function Reference

InsertAction

NameInsertAction — Inserts an action at an information set

Synopsis

InsertAction[infoset->INFOSET, at->ACTION] =: ACTIONInsertAction[infoset->INFOSET] =: ACTION

Description

InsertAction inserts a new action intoinfoset before the actionat . If at is not specified, the new action isappended toinfoset ’s actions. The corresponding new branch is created for each node belonging toinfoset .Returns the newly created action.

See also

Actions, DeleteAction.

InsertMove

NameInsertMove — Inserts a node in an extensive form

Synopsis

InsertMove[infoset->INFOSET, node->NODE] =: NODE

100

Chapter 5. Command Language Function Reference

Description

InsertMove inserts a new node in the tree at the location ofnode . The new node is made a member ofinfoset ,and the corresponding number of branches are created from the new node. The nodenode becomes the first child ofthe new node. Returns the new node.

See also

AddMove, DeleteMove, NewInfoset.

Integer

NameInteger — Converts a number to an integer value

Synopsis

Integer[x->NUMBER] =: INTEGER

Description

Integer convertsx to an integer value by truncation.

IntegerDivide

NameIntegerDivide — Returns the quotient of two integers

Synopsis

IntegerDivide[x->INTEGER, y->INTEGER] =: INTEGER

101

Chapter 5. Command Language Function Reference

Description

IntegerDivide returns the quotientx divided byy , rounded to the next integer towards zero. It is an error toattempt to divide by zero.

Short form

x DIV y

See also

Divide, Modulus.

Inverse

NameInverse — Computes the inverse of a square matrix

Synopsis

Inverse[x->LIST(LIST(NUMBER))] =: LIST(LIST(NUMBER))

Description

Inverse returns the inverse of the matrixx . It is an error if the matrix is not square or is singular.

IsConsistent

NameIsConsistent — Checks whether a basis is consistent

102

Chapter 5. Command Language Function Reference

Synopsis

IsConsistent[basis->EFBASIS] =: BOOLEAN

Description

IsConsistent returnsTrue if basis is a consistent basis -- i. e., if it is a basis which could be a support for asequential equilibrium ([KreWil82]).

IsConstSum

NameIsConstSum — Determines whether a game is constant sum

Synopsis

IsConstSum[nfg->NFG] =: BOOLEANIsConstSum[efg->EFG] =: BOOLEAN

Description

IsConstSum ReturnsTrue when the gameefg or nfg is constant sum.

IsDefined

NameIsDefined — Returns whether a variable has been defined

Synopsis

IsDefined[x->T] =: BOOLEAN

103

Chapter 5. Command Language Function Reference

Description

IsDefined returnsTrue if x has been defined.

IsDominated

NameIsDominated — Returns whether a strategy or action is dominated

Synopsis

IsDominated[strategy->STRATEGY, support->NFSUPPORT, {strong->False},{mixed->False}, {precision->Rational}, {time<->0.000000},{traceFile<->(Output)}, {traceLevel->0}] =: BOOLEAN

IsDominated[profile->MIXED, {strong->False}, {mixed->False},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: BOOLEAN,

IsDominated[action->ACTION, support->EFSUPPORT, {strong->False},{conditional->False}, {time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: BOOLEAN }

Description

IsDominated determines if thestrategy or action is dominated insupport , or if theprofile isdominated in its support. The following optional parameters may be specified to modify the behavior of theelimination:

• strong : By default, determines if the strategy or action is weakly dominated. By specifyingTrue , strongdominance is used.

• mixed : By default, only checks for domination by pure strategies or actions. If specifiedTrue , checks fordomination by mixtures over other strategies. Note that mixed domination is only implemented for normal formgames (i.e, for the first function prototype above).

• conditional : If this is True , checks for conditional domination (only applicable to extensive form games (i.e., for the second function prototype above).

• precision : Default precision is Rational. Note that the precision parameter is only applicable for mixeddomination. Pure strategy domination always uses Rational precision.

104

Chapter 5. Command Language Function Reference

IsEof

NameIsEof — Returns whether the end of a file has been reached

Synopsis

IsEof[input->INPUT] =: BOOLEAN

Description

IsEof returnsTrue when the input streaminput has reached the end of file.

See also

Read.

IsList

NameIsList — Determines whether a value is a list

Synopsis

IsList[x->T] =: BOOLEANIsList[list->NLIST(T)] =: BOOLEAN

Description

IsList returnsTrue whenx is a list or a nested list.

105

Chapter 5. Command Language Function Reference

See also

List.

IsNash

NameIsNash — Returns whether a profile is a Nash equilibrium

Synopsis

IsNash[profile->BEHAV] =: BOOLEANIsNash[profile->MIXED] =: BOOLEAN

Description

IsNash returnsTrue whenprofile is known by Gambit to be a Nash equilibrium of the corresponding game, andFalse if profile is known to not be Nash. Otherwise, the return value isUnknown. If profile is complete(probabilities sum to one for every player, and every information set), then there is a definitive test for Nashequilibrium. However if the profile is incomplete (i. e., it does not specify actions at off the equilibrium pathinformation sets), then it is possible that a profile (or set of all completions of the profile) may be Nash, but is notknown by Gambit to be Nash.

IsNull

NameIsNull — Returns whether a variable is null

Synopsis

IsNull[x->T*] =: BOOLEAN

106

Chapter 5. Command Language Function Reference

Description

IsNull returnsTrue if x is null.

IsPerfect

NameIsPerfect — Returns whether a profile is a perfect equilibrium

Synopsis

IsPerfect[profile->MIXED] =: BOOLEAN

Description

IsPerfect returnsTrue if profile is known by Gambit to be a perfect Nash equilibrium,False if it is known tonot be perfect, andUnknown otherwise. There is currently no definitive test in Gambit for whether an arbitraryprofile is perfect. However some of the algorithms (notablyLcpSolve ) will only return perfect equilibria, which aremarked as such.

IsPerfectRecall

NameIsPerfectRecall — Returns whether an extensive form has perfect recall

Synopsis

IsPerfectRecall[profile->MIXED] =: BOOLEAN

107

Chapter 5. Command Language Function Reference

Description

IsPerfectRecall returnsTrue if efg is a game of perfect recall, andFalse otherwise.

IsPredecessor

NameIsPredecessor — Computes whether one node precedes another in a tree

Synopsis

IsPredecessor[node->NODE, of->NODE] =: BOOLEAN

Description

IsPredecessor returnsTrue whennode is a predecessor in the tree of the nodeof . A node is considered its ownpredecessor.

See also

IsSuccessor.

IsSequential

NameIsSequential — Returns whether a profile is a sequential equilibrium

Synopsis

IsSequential[profile->BEHAV] =: BOOLEAN

108

Chapter 5. Command Language Function Reference

Description

IsSequential returnsTrue if profile is known by Gambit to be an approximation to a sequential Nashequilibrium,False if it is not, andUnknown if the answer is not known. There is currently no definitive test inGambit for whether an arbitrary profile is sequential. However any Nash equilibrium of an extensive form gamewhich is computed via theLiapSolve or QreSolve algorithms is sequential.

IsSubgamePerfect

NameIsSubgamePerfect — Returns whether a profile is a subgame perfect equilibrium

Synopsis

IsSubgamePerfect[profile->BEHAV] =: BOOLEAN

Description

IsSubgamePerfect returnsTrue if profile is known by Gambit to be a subgame perfect Nash equilibrium,False if it is known not to be a subgame perfect equilibrium, andUnknown otherwise. There is currently nodefinitive test in Gambit for whether an arbitrary profile is subgame perfect. However, any Nash equilibrium of anextensive form game which is computed when all subgames are marked will only return a subgame perfectequilibrium.

IsSuccessor

NameIsSuccessor — Returns whether one node succeeds another in a tree

Synopsis

IsSuccessor[node->NODE, from->NODE] =: BOOLEAN

109

Chapter 5. Command Language Function Reference

Description

IsSuccessor returnsTrue whennode is a successor in the tree of the nodefrom . A node is considered its ownsuccessor.

See also

IsPredecessor.

IsWatchRunning

NameIsWatchRunning — Returns whether the stopwatch is running

Synopsis

IsWatchRunning[] =: BOOLEAN

Description

IsWatchRunning returnsTrue when the system stopwatch is currently running.

See also

ElapsedTime, StartWatch, StopWatch.

LcpSolve

NameLcpSolve — Computes Nash equilibria via linear complementarity program

110

Chapter 5. Command Language Function Reference

Synopsis

LcpSolve[support->NFSUPPORT, {stopAfter->1}, {precision->Float},{nPivots<->0}, {time<->0}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(MIXED)

LcpSolve[support->EFSUPPORT, {asNfg->False}, {stopAfter->1},{precision->Float}, {nPivots<->0}, {time<->0.000000},{traceFile<->(Output)}, {traceLevel->0}] =: LIST(BEHAV)

Description

LcpSolve solves a game as a linear complementarity problem, using the Lemke-Howson algorithm for normal formgames, and the Koller-Megiddo-Stengel sequence form for extensive form games.

The behavior of the algorithm may be modified by the following optional parameters:

• asNfg By default, extensive forms are solved by the sequence form. By setting this parameter toTrue , eachmarked subgame of the extensive form is converted to its corresponding reduced normal form, solved viaLemke-Howson, and the mixed strategy solutions converted back into behavior profiles.

• stopAfter : Specifies the maximum number of equilibria to find. The default is one. If set to zero then allequilibria reachable by the algorithm will be found.

• precision Determines the precision of the computation. Default is floating point precision.

See also

LpSolve.

Length

NameLength — Returns the number of elements in a list

Synopsis

Length[list->LIST(T*)] =: INTEGER

111

Chapter 5. Command Language Function Reference

Description

Length returns the number of elements inlist .

See also

NthElement, NumElements.

Less

NameLess — Determines whether a value is less than another

Synopsis

Less[x->NUMBER, y->NUMBER] =: BOOLEANLess[x->TEXT, y->TEXT] =: BOOLEAN

Description

Less returnsTrue whenx is strictly less thany . For TEXT values, the ordering of the machine’s character set isused.

Short form

x < y

See also

Greater, GreaterEqual, LessEqual.

112

Chapter 5. Command Language Function Reference

LessEqual

NameLessEqual — Determines whether a value is less than or equal to another

Synopsis

LessEqual[x->NUMBER, y->NUMBER] =: BOOLEANLessEqual[x->TEXT, y->TEXT] =: BOOLEAN

Description

LessEqual returnsTrue whenx is less than or equal toy . For TEXT values, the ordering of the machine’scharacter set is used.

Short form

x <= y

See also

Greater, GreaterEqual, Less.

LiapSolve

NameLiapSolve — Computes Nash equilibria via function minimization

Synopsis

LiapSolve[start->BEHAV, {asNfg->False}, {stopAfter->1},{nTries->10}, {accuracy->0.000000}, {time<->0},{nEvals<->0}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(BEHAV)

113

Chapter 5. Command Language Function Reference

LiapSolve[start->MIXED, {stopAfter->1}, {nTries->10},{accuracy->0.000000}, {time<->0}, {nEvals<->0},{traceFile<->(Output)}, {traceLevel->0}] =: LIST(MIXED)

Description

LiapSolve searches for a Nash equilibrium by minimizing a Lyapunov function which is zero exactly at Nashequilibria. The algorithm starts from the initial starting point determined by the parameterstart . The algorithm isnot guaranteed to find a Nash equilibrium from any fixed starting point. The algorithm thus incorporates thecapability of restarting. If a Nash equilibrium is not found, it will keep searching from new randomly chosen startingpoints until a Nash equilibrium has been found or the maximum number of tries (parameternTries ) is exceeded,whichever comes first. The list of solutions found is returned.

The behavior of the algorithm may be modified by specifying the following optional parameters:

• asNfg By default, extensive forms are solved in the extensive form. By setting this parameter toTrue , eachmarked subgame of the extensive form is converted to its corresponding reduced normal form game, solved, andthe overall behavior profile reconstructed from these solutions.

• nTries : Sets the maximum number of attempts at finding an equilibrium. Default is 10.

• stopAfter : Sets the number of equilibria to find. Default is 1.

• accuracy : Resulting solutions are “epsilon equilibria” to at least this accuracy. I. e., no unilateral deviation byany player will result in an improvement of more than the accuracy. Default is 1.0e-8.

LiapValue

NameLiapValue — Computes the Lyapunov function for a profile

Synopsis

LiapValue[profile->BEHAV] =: NUMBERLiapValue[profile->MIXED] =: NUMBER

114

Chapter 5. Command Language Function Reference

Description

LiapValue returns the Lyapunov function value forprofile . This is a nonnegative value which is zero exactlywhen the profile is a Nash equilibrium.

List

NameList — Creates a list or sequence

Synopsis

List[x->T, {length->INTEGER}] =: LIST(T)List[x->NUMBER, {length->1}, {delta->0}] =: LIST(NUMBER)

Description

The first version ofList creates a new list oflength elements, each equal tox . If length is unspecified, itdefaults to 1.

The second version ofList creates an initialized list oflength elements, with first elementx and subsequentelements incremented bydelta . If length is unspecified, it defaults to 1; ifdelta is unspecified, it defaults to 0.

ListFormat

NameListFormat — Sets the formatting style for output of lists

Synopsis

ListFormat[{braces<->True}, {commas<->True},{lf<->2}, {indent<->2}] =: BOOLEAN

115

Chapter 5. Command Language Function Reference

Description

ListFormat sets the formatting style for output of lists on output streams. The parameters passed are set to the priorstyle settings on return.

• braces : If True , lists are delimited by braces.

• commas: If True , elements are delimited by commas.

• lf : Number of levels of list that are displayed with a line feed.

• indent : Number of spaces to indent each level of a list.

See also

Format, GetListFormat, Write.

LoadEfg

NameLoadEfg — Loads an extensive form game from file

Synopsis

LoadEfg[file->TEXT] =: EFG

Description

LoadEfg loads an extensive form game from the filefile . An error occurs if the file cannot be opened, or if the filedoes not contain a valid extensive form savefile.

See also

SaveEfg.

116

Chapter 5. Command Language Function Reference

LoadNfg

NameLoadNfg — Loads a normal form game from file

Synopsis

LoadNfg[file->TEXT] =: NFG

Description

LoadNfg loads a normal form game from the filefile . An error occurs if the file cannot be opened, or if the filedoes not contain a valid normal form savefile.

See also

SaveNfg.

Log

NameLog — Returns the natural logarithm of a number

Synopsis

Log[x->NUMBER] =: NUMBER

Description

Log computes the natural logarithm ofx . It is an error ifx is nonpositive. The result is always in floating-pointprecision, regardless of the precision ofx .

117

Chapter 5. Command Language Function Reference

See also

Exp, Power.

LpSolve

NameLpSolve — Computes Nash equilibria using linear programming

Synopsis

LpSolve[support->NFSUPPORT, {precision->Float}, {nPivots<->0},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(MIXED)

LpSolve[support->EFSUPPORT, {asNfg->False}, {precision->Float},{nPivots<->0}, {time<->0.000000},{traceFile<->(Output)}, {traceLevel->0}] =: LIST(BEHAV) L

Description

LpSolve solves a two-person, constant-sum game for a Nash equilibrium as a linear program. For extensive formgames, the Koller-Megiddo-Stengel sequence form is used; games not of perfect recall return the empty list ofsolutions.

The behavior of the algorithm may be modified by the following optional parameters:

• asNfg : By default, extensive forms are solved by the sequence form. By setting this parameter toTrue , eachmarked subgame of the extensive form is converted to its corresponding reduced normal form, solved as a linearprogram, and the mixed strategy solutions converted back into behavior profiles.

• precision : Determines the precision of the computation. Default is floating point precision.

See also

LcpSolve.

118

Chapter 5. Command Language Function Reference

Manual

NameManual — Prints the manual entry for a function

Synopsis

Manual[x->TEXT, {y->(Output)}] =: BOOLEAN

Description

Manual prints the manual entry for the functionx . If there is no entry forx , no output is generated. The parametery , which is the null output by default, can be used to print the manual entry to an output stream.

See also

Help, HelpVars.

MarkSubgame

NameMarkSubgame — Marks a subgame root

Synopsis

MarkSubgame[node->NODE] =: BOOLEAN

Description

MarkSubgame marksnode as being the root of a subgame for use in later computation. Only nodes which are rootsof subgames may be marked. ReturnsTrue if node was marked as a subgame (i.e., if it is the root of a subgame).

119

Chapter 5. Command Language Function Reference

See also

MarkedSubgame, Subgames, UnMarkSubgame.

MarkedSubgame

NameMarkedSubgame — Returns whether a subgame root is marked

Synopsis

MarkedSubgame[node->NODE] =: BOOLEAN

Description

MarkedSubgame returnsTrue if node is currently marked as a subgame.

See also

MarkSubgame, Subgames, UnMarkSubgame.

Members

NameMembers — Returns the node which belong to an information set

Synopsis

Members[infoset->INFOSET*] =: LIST(NODE)

120

Chapter 5. Command Language Function Reference

Description

Members returns the list of nodes which are members ofinfoset . If infoset is null, the empty list is returned.

See also

Infoset.

MergeInfosets

NameMergeInfosets — Combines two information sets

Synopsis

MergeInfosets[to->INFOSET, from->INFOSET] =: INFOSET

Description

MergeInfosets moves all the nodes from the information setfrom into to . It is an error if the number of actionsis not the same at the two information sets, or if the information sets are not from the same extensive form game. Theinformation setto is returned.

See also

MoveToInfoset.

Minus

NameMinus — Returns the difference of two numbers or profiles

121

Chapter 5. Command Language Function Reference

Synopsis

Minus[x->NUMBER, y->NUMBER] =: NUMBERMinus[x->MIXED, y->MIXED] =: MIXEDMinus[x->BEHAV, y->BEHAV] =: BEHAV

Description

Minus returns the difference ofx andy .

Short form

x - y

See also

Divide, Plus, Times.

Mixed

NameMixed — Creates a mixed strategy profile on a support

Synopsis

Mixed[support->NFSUPPORT] =: MIXED

Description

Mixed returns a mixed strategy profile oversupport with equal probabilites for each strategy in the support.

122

Chapter 5. Command Language Function Reference

See also

Behav.

Modulus

NameModulus — Computes the remainder from integer division

Synopsis

Modulus[x->INTEGER, y->INTEGER] =: INTEGER

Description

Modulus computes the remainder from dividingy into x . It is an error ify is zero.

Short form

x MOD y

See also

IntegerDivide.

MoveToInfoset

NameMoveToInfoset — Places a node in an information set

123

Chapter 5. Command Language Function Reference

Synopsis

MoveToInfoset[node->NODE, infoset->INFOSET] =: NODE

Description

MoveToInfoset removesnode from its current information set, and makes it a member ofinfoset . It is an errorif the number of actions atnode is not the same as the number of actions ininfoset , or if node andinfosetare from different extensive form games.

See also

MergeInfosets.

MoveTree

NameMoveTree — Moves an entire subtree in an extensive form game

Synopsis

MoveTree[from->NODE, to->NODE] =: NODE

Description

MoveTree moves the subtree rooted atfrom to the terminal nodeto . The nodefrom becomes a terminal node.Returnsto . It is an error ifto is not a terminal node, or iffrom andto are not from the same extensive form game.

See also

CopyTree.

124

Chapter 5. Command Language Function Reference

Name

NameName— Returns the text label of an object

Synopsis

Name[x->ACTION*] =: TEXTName[x->EFG*] =: TEXTName[x->EFOUTCOME*] =: TEXTName[x->EFPLAYER*] =: TEXTName[x->INFOSET*] =: TEXTName[x->NFG*] =: TEXTName[x->NFOUTCOME*] =: TEXTName[x->NFPLAYER*] =: TEXTName[x->NODE*] =: TEXTName[x->STRATEGY*] =: TEXT

Description

Namereturns the name ofx . The name of a null object is defined to be the empty string.

See also

SetName.

Negate

NameNegate — Returns the negation of a number

Synopsis

Negate[x->NUMBER] =: NUMBER

125

Chapter 5. Command Language Function Reference

Description

Negate returns the negation ofx .

Short form

-x

NewEfg

NameNewEfg — Creates a new extensive form game

Synopsis

NewEfg[{players->{}}] =: EFG

Description

NewEfg creates a new extensive form game. The default extensive form game has no players (other than the chanceplayer) defined on it; the optional parameterplayers specifies a list of players to be created and the names to beassigned to them. Returns the newly created game.

NewFunction

NameNewFunction — Creates a user-defined function

Synopsis

NewFunction[name[argument-list], body]

126

Chapter 5. Command Language Function Reference

Description

NewFunction creates a new function. The function may be called exactly as if it were a predefined function of thecommand language. See the section on user-defined functions for more detailed information.

NewInfoset

NameNewInfoset — Creates a new information set in an extensive form game

Synopsis

NewInfoset[player->EFPLAYER, actions->INTEGER] =: INFOSET

Description

NewInfoset creates a new information set belonging toplayer , with actions actions. It is an error ifactions is not positive. The newly created information set is returned.

See also

DeleteEmptyInfoset.

NewNfg

NameNewNfg — Creates a normal form game

Synopsis

NewNfg[dim->LIST(INTEGER)] =: NFG

127

Chapter 5. Command Language Function Reference

Description

NewNfg creates a new normal form game with dimensiondim . No initialization of the payoffs of the game is done.Returns the newly created game.

NewOutcome

NameNewOutcome — Creates a new outcome in a game

Synopsis

NewOutcome[efg->EFG] =: EFOUTCOMENewOutcome[nfg->NFG] =: NFOUTCOME

Description

NewOutcome defines a new outcome in the extensive form gameefg or normal form gamenfg . The new outcomespecifies payoffs of zero for all players. Returns the newly created outcome.

See also

DeleteOutcome, Outcomes, SetOutcome.

NewPlayer

NameNewPlayer — Creates a new player in an extensive form game

128

Chapter 5. Command Language Function Reference

Synopsis

NewPlayer[efg->EFG] =: EFPLAYER

Description

NewPlayer defines a new player in the extensive form game \verb+efg+. Returns the newly created player.

NextSibling

NameNextSibling — Returns the next sibling of a node

Synopsis

NextSibling[node->NODE] =: NODE

Description

NextSibling returns the next sibling ofnode . If node has no next sibling, the null node is returned.

See also

PriorSibling.

Nfg

NameNfg — Creates the reduced normal form corresponding to an extensive form

129

Chapter 5. Command Language Function Reference

Synopsis

Nfg[efg->EFG, {time<->0}] =: NFG

Description

Nfg creates and returns the (structural) reduced normal form game equivalent to the extensive form gameefg . Theoptional parametertime , if specified, contains upon completion the amount of time consumed by thetransformation.

See also

AgentForm.

NodeNumber

NameNodeNumber — Returns the number of a node in a basis

Synopsis

NodeNumber[node->NODE, basis->EFBASIS] =: INTEGER

Description

NodeNumber returns the number assigned tonode in the basisbasis .

See also

Basis.

130

Chapter 5. Command Language Function Reference

NodeValue

NameNodeValue — Returns the expected payoff to a player of being at a node

Synopsis

NodeValue[profile->BEHAV, player->EFPLAYER, node->NODE] =: NUMBER

Description

NodeValue returns the expected payoff toplayer atnode , given that all players are followingprofile .

See also

ActionValue, Belief, InfosetProb, RealizProb.

Nodes

NameNodes — Returns the nodes in a game or basis

Synopsis

Nodes[efg->EFG] =: LIST(NODE)Nodes[infoset->INFOSET*, basis->EFBASIS] =: LIST(NODE)

Description

The first version ofNodes returns a list of nodes of the extensive form gameefg . The list is in prefix traversal order;each node appears in the list prior to any of its descendants.

The second version ofNodes returns a list of nodes of the information setinfoset in thebasis .

131

Chapter 5. Command Language Function Reference

Not

NameNot — Returns the logical negation of a value

Synopsis

Not[x->BOOLEAN] =: BOOLEAN

Description

Not returns the boolean inverse ofx , according to the truth table:

x Not[x]

True False

False True

Unknown Unknown

Short forms

NOT x, !x

See also

And, Or.

132

Chapter 5. Command Language Function Reference

NotEqual

NameNotEqual — Determines if two values are not equal

Synopsis

NotEqual[x->T*, y->T*] =: BOOLEAN

Description

NotEqual returnsTrue when the values ofx andy are not equal.

Short form

x != y

See also

Equal.

NthChar

NameNthChar — Extracts a character from a string

Synopsis

NthChar[text->TEXT, n->INTEGER] =: TEXT

133

Chapter 5. Command Language Function Reference

Description

NthChar returns a text string of length 1 containing thenth character fromtext . By convention, the first characterin a string is indexed by 1. It is an error ifn is nonpositive, or ifn is greater than the length oftext . not equal.

Short forms

text[[n]] , text#n .

See also

NumChars.

NthChild

NameNthChild — Returns a child of a node, by index

Synopsis

NthChild[node->NODE, n->INTEGER] =: NODE

Description

NthChild returns thenth child ofnode . By convention, the first child of a node is indexed by 1. It is an error ifn isnonpositive, or ifn is greater than the number of children ofnode .

Short forms

node#n .

134

Chapter 5. Command Language Function Reference

See also

Children.

NthElement

NameNthElement — Returns an element of a list, by index

Synopsis

NthElement[list<->NLIST(T*), n->INTEGER] =: T

Description

NthElement returns thenth element oflist . By convention, the first element of a list is indexed by 1. It is an errorif n is nonpositive, or ifn is greater than the number of elements inlist .

Short forms

list[[n]] , list_n .

See also

Length.

Null

NameNull — Returns a null object of a specified type

135

Chapter 5. Command Language Function Reference

Synopsis

Null[x->T] =: T*

Description

Null returns a null object of type T.

See also

IsNull.

NumChars

NameNumChars — Returns the length of a text string

Synopsis

NumChars[text->TEXT] =: INTEGER

Description

NumChars returns the number of characters intext .

See also

NthChar.

136

Chapter 5. Command Language Function Reference

NumElements

NameNumElements — Returns the number of elements in a list

Synopsis

NumElements[list->NLIST(T*)] =: INTEGER

Description

NumElements returns the number of elements inlist . The difference between this function andLength is thatthis function is not listable, whileLength is.

See also

Length. NthChar.

Or

NameOr — Returns the logical disjunction of two values

Synopsis

Or[x->BOOLEAN, y->BOOLEAN] =: BOOLEAN

Description

Or returns the disjunction ofx andy , according to the truth table:

True False Unknown

True True True True

137

Chapter 5. Command Language Function Reference

False True False Unknown

Unknown True Unknown Unknown

Short forms

x || y , x OR y

See also

And. Not.

Outcome

NameOutcome — Returns the outcome of a node or contingency

Synopsis

Outcome[node->NODE*] =: EFOUTCOMEOutcome[profile->LIST(STRATEGY)] =: NFOUTCOME

Description

Outcome returns the outcome associated with thenode , or the contingencyprofile . The outcome associatedwith the null node is the null outcome.

See also

SetOutcome.

138

Chapter 5. Command Language Function Reference

Outcomes

NameOutcomes — Returns the outcomes defined on a game

Synopsis

Outcomes[efg->EFG] =: LIST(EFOUTCOME)Outcomes[nfg->NFG] =: LIST(NFOUTCOME)

Description

Outcomes returns the list of outcomes defined on the gameefg or nfg .

See also

DeleteOutcome, NewOutcome, SetOutcome.

Output

NameOutput — Opens a file for output

Synopsis

Output[file->TEXT, {append->False}, {close->True}] =: OUTPUT

Description

Output opens a new output stream for writing tofile . An error occurs iffile is not able to be opened. Bydefault, an existing file is overwritten; specifyingappend to beTrue opens the file in append mode. Also, bydefault, the file is closed after every write operation to the file; specifyingclose to beFalse will leave the file

139

Chapter 5. Command Language Function Reference

open between write operations. This may speed up output to a file, but will mean that the file is not closed until allreferences to the output stream areUnAssign ed.

See also

Format, Input, ListFormat, Write.

Parent

NameParent — Returns the parent of a node

Synopsis

Parent[node->NODE*] =: NODE

Description

Parent returns the parent ofnode . If node is the root node, or ifnode is null, the null node is returned.

See also

Children.

Parentheses

NameParentheses — Returns its parameter

140

Chapter 5. Command Language Function Reference

Synopsis

Parentheses[x->T*] =: T

Description

Parentheses returns the value passed inx . This is used to control the order of evaluation of expressions.

Short form

(x)

Payoff

NamePayoff — Returns the payoff associated with an object

Synopsis

Payoff[outcome->EFOUTCOME*, player->EFPLAYER] =: NUMBERPayoff[outcome->NFOUTCOME*, player->NFPLAYER] =: NUMBERPayoff[profile->BEHAV, player->EFPLAYER] =: NUMBERPayoff[profile->MIXED, player->NFPLAYER] =: NUMBER

Description

The first two versions ofPayoff return the value of the outcomeoutcome to the playerplayer .

The third and fourth versions return the expected payoff to playerplayer , when all players play according toprofile .

In all cases, an error occurs if the parameters are not from the same game.

141

Chapter 5. Command Language Function Reference

See also

SetPayoff.

Platform

NamePlatform — Returns a string identifying the system

Synopsis

Platform[] := TEXT

Description

Platform returns a string identifying the platform that the GCL is currently running on. Can be used in user definedfunctions to define system dependent variables, such as pathnames and command lines for shell commands.

See also

Shell.

Player

NamePlayer — Returns the player corresponding to an object

Synopsis

Player[infoset->INFOSET*] =: EFPLAYERPlayer[strategy->STRATEGY*] =: NFPLAYER

142

Chapter 5. Command Language Function Reference

Description

Player returns the player who chooses at information setinfoset , or who has strategystrategy . If infosetor strategy , as appropriate, is null, the null player is returned.

See also

Infosets, Strategies.

Players

NamePlayers — Returns the list of players in a game

Synopsis

Players[efg->EFG] =: LIST(EFPLAYER)Players[nfg->NFG] =: LIST(NFPLAYER)

Description

Players returns the list of players defined on the gameefg or nfg .

Plus

NamePlus — Returns the sum of two numbers or profiles, or the concatenation of two strings

Synopsis

Plus[x->NUMBER, y->NUMBER] =: NUMBERPlus[x->MIXED, y->MIXED] =: MIXED

143

Chapter 5. Command Language Function Reference

Plus[x->BEHAV, y->BEHAV] =: BEHAVPlus[x->TEXT, y->TEXT] =: TEXT

Description

The first three versions ofPlus return the sum ofx andy . The final version returns the concatentation ofx andy .

Short form

x + y

See also

Divide, Minus, Times.

PolEnumSolve

NamePolEnumSolve — Computes Nash equilibria by enumerating solutions to polynomial equations

Synopsis

PolEnumSolve[support->NFSUPPORT, {stopAfter->0}, {nEvals<->0},{time<->0.000000}, {traceFile<->(Output)}, {traceLevel->0},{singularSupps<->{ }}, {recurse->True}] =: LIST(MIXED)

PolEnumSolve[support->EFSUPPORT, {asNfg->False}, {stopAfter->0},{nEvals<->0}, {time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}, {singularSupps<->{ }},{recurse->True}] =: LIST(BEHAV)

Description

PolEnumSolve solves for all totally mixed Nash equilibrium onsupport . If recurse is True , the algorithmiterates through all sub-supports ofsupport to find the full support equilibria on each sub-support. Supports with

144

Chapter 5. Command Language Function Reference

singular solutions are reported insingularSupps . These supports are skipped by the algorithm when determinedto have singular solutions.

On each sub-support, the algorithm starts with a cube containing the space of possible solutions and proceedsrecursively. The recursion step begins with a subcube. The subcube is discarded if the cube is irrelevant in the senseof lying outside the space of possible solutions. Otherwise a modified Newton’s method is used to search for asolution in the subcube. In the event that such a solution is found, Taylor’s series information at the solution is usedto inquire whether the solution is necessarily the unique solution in the subcube. If Newton’s method leaves thesubcube before finding a solution, Taylor’s series information at the center is used to inquire whether we can be surethat the subcube contains no solutions. If neither of these procedures resolves the issue, the subcube is subdividedand this recursion is performed on each smaller subcube.

The following optional parameters may be used to modify the behavior of the algorithm:

• stopAfter By default, all equilibria are found. This parameter may be used to specify a maximum number ofequilibria to be found.

• asNfg Only applicable to the extensive form version. By default, this isFalse . If it is specified to beTrue , theextensive form game is solved by recursively converting its marked subgames into normal form, solving, andreconstructing the solution as a behavior profile.

• singularSupps : Returns a list of the supports which have singular solutions.

• recurse : Recurses to find totally mixed equilibria on all subsupports ofsupport .

See also

PossibleNashSupports.

PossibleNashSupports

NamePossibleNashSupports — Returns the list of supports that could be supports of Nash equilibria

Synopsis

PossibleNashSupports[efg->EFG] =: LIST(EFSUPPORT)

145

Chapter 5. Command Language Function Reference

Description

PossibleNashSupports returns the list of supports that could be the supports of Nash equilibria. Specifically, thesupports returned are those in which no pure strategy is weakly dominated by another strategy in the support, sincesuch a pure strategy would have a lower expected payoff for any mixed strategy vector that assigned positiveprobability to all elements of the support and no other strategies, and no pure strategy in the support is strictlydominated (relative to the support) by a pure strategy outside the support.

Power

NamePower — Raises a number to a power

Synopsis

Power[x->NUMBER, y->NUMBER] =: NUMBER

Description

Power raisesx to the powery . Power is not implemented for the case wherex is a rational, andy is not an integer.

Short form

x ^ y

See also

Exp, Log.

146

Chapter 5. Command Language Function Reference

Precision

NamePrecision — Returns the precision of a number

Synopsis

Precision[x->NUMBER] =: PRECISION

Description

Precision returns the precision ofx .

Print

NamePrint — Prints a value to the console

Synopsis

Print[x->T*] =: TPrint[x->NLIST(T*)] =: NLIST(T)

Description

Print printsx at the console. When relevant, the output is formatted according to the current settings determined bytheFormat commands. Returnsx .

Short form

<< x

147

Chapter 5. Command Language Function Reference

See also

ListFormat, Write.

PriorAction

NamePriorAction — Returns the action immediately before a node

Synopsis

PriorAction[node->NODE] =: ACTION

Description

PriorAction returns the action corresponding to the branch leading tonode . If node is the root node, its prioraction is the null action.

PriorSibling

NamePriorSibling — Returns the previous sibling of a node

Synopsis

PriorSibling[node->NODE] =: NODE

Description

PriorSibling returns the prior sibling ofnode . If node has no prior sibling, the null node is returned.

148

Chapter 5. Command Language Function Reference

See also

NextSibling.

QreGridSolve

NameQreGridSolve — Computes quantal response equilibria via a grid search

Synopsis

QreGridSolve[support->NFSUPPORT, {pxifile->},{minLam->0.001000}, {maxLam->500.000000},{delLam->0.020000}, {powLam->1}, {fullGraph->False},{delp1->0.100000}, {tol1->0.100000},{delp2->0.010000}, {tol2->0.010000},{nEvals<->0}, {time<->0.000000},{traceFile<->(Output)},{traceLevel->0}] =: LIST(MIXED)

Description

QreGridSolve computes the complete logistic quantal response correspondence for a (small) normal form game onthesupport , for values of lambda betweenminLam andmaxLam. Returns the list of mixed profiles computed.

The operation of the algorithm may be modified by specifying optional parameters. SeeQreSolve for a descriptionof parameters not listed here:

• delp1 : Grid size for course search over probability space. Default is 0.1.

• tol1 : The tolerance on the objective function for course search. Values of p for which the objective function isless this value are searched further on a finer grid. The default is 0.1.

• delp2 : Grid size for fine search over probability space. Default is 0.01.

• tol2 : The tolerance on the objective function for fine search. Values of p for which the objective function is lessthis value are kept. The default is 0.01.

149

Chapter 5. Command Language Function Reference

See also

QreLambda, QreSolve.

QreLambda

NameQreLambda — Returns the value of lambda for which a profile is a QRE

Synopsis

QreLambda[profile->MIXED] =: NUMBERQreLambda[profile->BEHAV] =: NUMBER

Description

QreLambda returns the value of lambda for mixed or behavior profiles computed byQreSolve or QreGridSolve .Profiles not created by one of these algorithms have a null lambda value.

See also

QreGridSolve, QreSolve.

QreSolve

NameQreSolve — Computes quantal response equilibria via homotopy path following

Synopsis

QreSolve[start->MIXED, {pxifile->""}, {minLam->0.001000},{maxLam->500.000000}, {delLam->0.020000}, {powLam->1},

150

Chapter 5. Command Language Function Reference

{fullGraph->False}, {accuracy->0.000000}, {time<->0},{nEvals<->0}, {nIters<->0}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(MIXED),

QreSolve[start->BEHAV, {pxifile->""}, {minLam->0.001000},{maxLam->500.000000}, {delLam->0.020000}, {powLam->1},{fullGraph->False}, {accuracy->0.000000}, {time<->0},{nEvals<->0}, {nIters<->0}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(BEHAV),

Description

QreSolve the principal branch of the logistic quantal response equilibrium correspondence for a game, using thealgorithm described in [Tur02].

The behavior of the algorithm may be modified by specifying some of the following optional parameters:

• minLam: Sets the minimum value of lambda. The default value is 0.001.

• maxLam: Sets the maximum value of lambda. The default value is 500.0.

• fullGraph : If True , the list of behavior strategy profiles returned contains the full sequence of profilescomputed from each successive value of lambda. The default value isFalse , in which case only the profile for thelast value of lambda computed is returned.

Note that the extensive form version disregards any marked subgames.

See also

QreGridSolve, QreLambda.

Quit

NameQuit — Exits the command language

151

Chapter 5. Command Language Function Reference

Synopsis

QuitQuit[{value->INTEGER:=0}] =: BOOLEAN

Description

Quit exits the command language, returningvalue to the operating system.

Randomize

NameRandomize — Returns a random number

Synopsis

Randomize[x->NUMBER, {seed->0}] =: NUMBER

Description

Randomize returns a random number distributed uniformly between zero and one. The result is of rational precision.The denominator is equal to the maximum machine integer, and the numerator is a uniformly distributed integerbetween zero and the maximum integer.

Rational

NameRational — Converts a number to rational precision

152

Chapter 5. Command Language Function Reference

Synopsis

Rational[x->NUMBER] =: NUMBER

Description

Rational convertsx to a number with rational precision.

See also

Float.

Read

NameRead — Reads a value from an input stream

Synopsis

Read[input<->INPUT, x<->BOOLEAN] =: INPUTRead[input<->INPUT, x<->NUMBER] =: INPUTRead[input<->INPUT, x<->TEXT] =: INPUTRead[input<->INPUT, x<->LIST(BOOLEAN)] =: INPUTRead[input<->INPUT, x<->LIST(NUMBER)] =: INPUTRead[input<->INPUT, x<->LIST(TEXT)] =: INPUT

Description

Read reads data from the input stream and assigns it tox . If x is undefined, then its data type is determined from theexposed data in the input stream. Ifx is previously defined, then theRead function will expect to find thecorresponding data type in the input stream, and a file read error will be generated if the exposed data is of the wrongdata type. Ifx is previously defined to be a LIST, thenRead[in,x] will successively read elements into eachelement of the list. If the wrong data type is found for any element of the list, a file read error will be returned.

The "exposed data" in the input stream consists of the following: If first character is a double quote (" ), then theexposed data consists of all characters up until the next double quote. If the first character is a{ , then the exposed

153

Chapter 5. Command Language Function Reference

data consists of all the characters up until the next matching} . Otherwise, the exposed data consists of all charactersuntil the next whitespace.

Short form

input >> x

See also

Input, IsEof, ReadText.

ReadText

NameReadText — Reads data from an input stream as text

Synopsis

ReadText[input<->INPUT, {x<->}, until->TEXT] =: INPUTReadText[input<->INPUT, {x<->}, n->INTEGER] =: INPUT

Description

ReadText reads data of type TEXT from the input stream and assigns it tox . The first signature reads frominputuntil the stringuntil is reached. For example, settinguntil - >"\n" will read a line of text frominput . Thesecond signature readsn characters frominput .

See also

Input, IsEof, Read, Write.

154

Chapter 5. Command Language Function Reference

RealizProb

NameRealizProb — Returns the probability a node is reached

Synopsis

RealizProb[profile->BEHAV, node->NODE] =: NUMBER

Description

RealizProb returns the realization probability fornode given that all players are followingprofile . It is anerror if profile andnode are not from the same extensive form game.

See also

ActionValue, Belief, InfosetProb, NodeValue.

Regret

NameRegret — Returns the gain from deviating to an action or strategy

Synopsis

Regret[profile->BEHAV, action->ACTION] =: NUMBERRegret[profile->MIXED, strategy->STRATEGY] =: NUMBER

Description

Regret returns the gain to a player for deviating toaction or strategy , respectively, assuming all players arefollowing profile . A strategy profile is a Nash equilibrium if and only if the regrets of all actions or strategies arezero.

155

Chapter 5. Command Language Function Reference

Regrets

NameRegrets — Returns the gain from deviating to an action or strategy

Synopsis

Regrets[profile->MIXED] =: LIST(LIST(NUMBER))

Description

Regrets returns a nested list of the regrets generated for each strategy byprofile . The (i,j)th entry is the regretfor player i, strategy j.

Remove

NameRemove— Removes an element from a list

Synopsis

Remove[list->NLIST(T), n->INTEGER] =: LIST(T)

Description

Remove removes thenth element fromlist . A copy of the list with the element removed is returned. It is an errorif n is nonpositive, or ifn is greater than the length oflist .

156

Chapter 5. Command Language Function Reference

RemoveAction

NameRemoveAction — Removes an action from a support

Synopsis

RemoveAction[support->EFSUPPORT, action->ACTION] =: EFSUPPORTRemoveAction[basis->EFBASIS, action->ACTION] =: EFBASIS

Description

RemoveAction removesaction from support (or basis ). If action is not insupport (or basis ). there isno effect. A copy of the modified support is returned. It is an error ifsupport (or basis ) andaction are notfrom the same extensive form game, or if removingaction would result in the support containing no actions at aninformation set.

See also

AddAction, Support.

RemoveNode

NameRemoveNode— Removes a node from a basis

Synopsis

RemoveNode[support->EFBASIS, node->NODE] =: EFBASIS

157

Chapter 5. Command Language Function Reference

Description

RemoveNode removesnode from support . If node is not in the basis, there is no effect. A copy of the modifiedbasis is returned.

See also

AddNode, Basis.

RemoveStrategy

NameRemoveStrategy — Removes a strategy from a support

Synopsis

RemoveStrategy[support->NFSUPPORT, strategy->STRATEGY] =: NFSUPPORT

Description

RemoveStrategy removesstrategy from support . If strategy is not in the support, there is no effect. Acopy of the modified support is returned. It is an error ifsupport andstrategy are not from the same normalform game, or if removingstrategy would result in the support containing no strategies for a player.

See also

AddStrategy, Support.

158

Chapter 5. Command Language Function Reference

Reveal

NameReveal — Reveals the actions at an information set to specified players

Synopsis

Reveal[infoset->INFOSET, who->LIST(EFPLAYER)] =: INFOSET

Description

Reveal reveals the list of actions atinfoset to the players inwho, refining their information partitions at allinformation sets in the extensive form game accordingly.

RootNode

NameRootNode — Returns the root node of an extensive form

Synopsis

RootNode[efg->EFG] =: NODE

Description

RootNode returns the root node ofefg .

159

Chapter 5. Command Language Function Reference

SaveEfg

NameSaveEfg — Writes an extensive form game to a file

Synopsis

SaveEfg[efg->EFG, file->TEXT] =: EFG

Description

SaveEfg writesefg to an external savefilefile . It is an error iffile cannot be opened for writing. Returnsefg .

See also

LoadEfg.

SaveNfg

NameSaveNfg — Writes a normal form game to a file

Synopsis

SaveNfg[efg->NFG, file->TEXT] =: NFG

Description

SaveNfg writesnfg to an external savefilefile . It is an error iffile cannot be opened for writing. Returnsnfg .

160

Chapter 5. Command Language Function Reference

See also

LoadNfg.

SequenceForm

NameSequenceForm — Returns the sequence form of an extensive form game

Synopsis

SequenceForm[efg->EFG] =: NLIST(NUMBER)

Description

SequenceForm returns the sequence form of an extensive form gameefg , where the sequence form is as defined inKoller, Megiddo and von Stengel [KolMegSte94]. The sequence form is returned as a nested list, with the indices inthe reverse order from the numbers of the players. Thus, if there are three players, the (i,j,k)th element is a vector ofpayoffs for player 3’s ith sequence, player 2’s jth sequence, and player 1’s kth sequence. The components of thepayoff vectors are in the same order as the player numbers.

See also

SequenceFormStrats, SequenceFormConstraints, WriteSequenceForm.

SequenceFormConstraints

NameSequenceFormConstraints — Returns the strategy constraints for a player in a sequence form

161

Chapter 5. Command Language Function Reference

Synopsis

SequenceFormConstraints[efg->EFG,player->EFPLAYER] =: LIST(LIST(NUMBER))

Description

SequenceFormConstraints returns the matrix of constraints on the strategies forplayer in the sequence formgame forefg . Each row represents a separate constraint, and each column represents the corresponding sequencefor that player.

See also

SequenceForm, SequenceFormStrats, WriteSequenceForm.

SequenceFormStrats

NameSequenceFormStrats — Returns the sequence form strategies of a player

Synopsis

SequenceFormStrats[efg->EFG,player->EFPLAYER] =: LIST(LIST(ACTION))

Description

SequenceFormStrats returns the sequence form strategies (or sequences) forplayer for the sequence formgame forefg . Each sequence form strategy is represented by a row in the matrix, which is a list of actions for thatplayer corresponding to the sequence.

See also

SequenceForm, SequenceFormConstraints, WriteSequenceForm.

162

Chapter 5. Command Language Function Reference

SetActionProb

NameSetActionProb — Sets the probability an action is played in a profile

Synopsis

SetActionProb[profile<->BEHAV, action->ACTION, value->NUMBER] =: BEHAV

Description

SetActionProb sets the component ofprofile for action to be equal tovalue , and returnsprofile . It isan error ifprofile andaction are not from the same extensive form game.

See also

ActionProb, SetActionProbs.

SetActionProbs

NameSetActionProbs — Sets the probabilities actions are played at an information set

Synopsis

SetActionProbs[profile<->BEHAV, infoset->INFOSET,value->LIST(NUMBER)] =: BEHAV

163

Chapter 5. Command Language Function Reference

Description

SetActionProbs sets the components ofprofile for information setinfoset to be equal tovalues . Returnsprofile . It is an error ifprofile andinfoset are not from the same extensive form game, or if the length ofvalue is not the same as the number of actions inprofile ’s support atinfoset .

See also

ActionProb, SetActionProbs.

SetChanceProbs

NameSetChanceProbs — Sets the probabilities chance actions are played at an information set

Synopsis

SetChanceProbs[infoset->INFOSET, probs->LIST(NUMBER)] =: INFOSET

Description

SetChanceProbs sets the action probabilities forinfoset to the values given inprobs . Returnsinfoset . Anerror occurs ifinfoset does not belong to the chance player.

See also

ChanceProb.

164

Chapter 5. Command Language Function Reference

SetComment

NameSetComment — Sets the comment associated with a game

Synopsis

SetComment[efg->EFG, comment->TEXT] =: EFGSetComment[nfg->NFG, comment->TEXT] =: NFG

Description

SetComment sets the comment associated with the gameefg or nfg .

See also

Comment.

SetEnv

NameSetEnv — Sets an environment variable

Synopsis

SetEnv[name->TEXT, value->TEXT] =: BOOLEAN

Description

SetEnv sets the environment variablename to the valuevalue .

165

Chapter 5. Command Language Function Reference

See also

GetEnv, UnSetEnv.

SetName

NameSetName — Sets the text label of an object

Synopsis

SetName[x->ACTION, name->TEXT] =: ACTIONSetName[x->EFG, name->TEXT] =: EFGSetName[x->EFOUTCOME, name->TEXT] =: EFOUTCOMESetName[x->EFPLAYER, name->TEXT] =: EFPLAYERSetName[x->INFOSET, name->TEXT] =: INFOSETSetName[x->NFG, name->TEXT] =: NFGSetName[x->NFOUTCOME, name->TEXT] =: NFOUTCOMESetName[x->NFPLAYER, name->TEXT] =: NFPLAYERSetName[x->NODE, name->TEXT] =: NODESetName[x->STRATEGY, name->TEXT] =: STRATEGY

Description

SetName sets the text label ofx to name. Returnsx .

See also

Name.

166

Chapter 5. Command Language Function Reference

SetOutcome

NameSetOutcome — Sets the outcome at a node or contingency

Synopsis

SetOutcome[node->NODE, outcome->EFOUTCOME*] =: EFOUTCOMESetOutcome[profile->LIST(STRATEGY), outcome->NFOUTCOME] =: NFOUTCOME

Description

The first version ofSetOutcome attachesoutcome to node . Returns the outcome attached. Note that nonterminalnodes may have outcomes attached; the interpretation is that nonterminal outcomes represent incremental payoffs. Itis an error ifnode andoutcome are not from the same extensive form game.

The second version ofSetOutcome attachesoutcome to the cell in the normal form game determined by the purestrategy profile defined byprofile . Returns the outcome attached. It is an error ifprofile andoutcome arenot from the same normal form game. Also,profile must be a list of strategies consisting of one strategy for eachplayer in the game.

See also

Outcome.

SetPayoff

NameSetPayoff — Sets the payoff to a player of an outcome

Synopsis

SetPayoff[outcome->EFOUTCOME, player->EFPLAYER,payoff->NUMBER] =: EFOUTCOME

SetPayoff[outcome->NFOUTCOME, player->NFPLAYER,

167

Chapter 5. Command Language Function Reference

payoff->NUMBER] =: NFOUTCOME

Description

SetPayoff sets the payoff ofoutcome for player to payoff . It is an error ifoutcome andplayer are notfrom the same game. Returnsoutcome .

See also

Payoff.

SetStrategyProb

NameSetStrategyProb — Sets the probability a strategy is played in a profile

Synopsis

SetStrategyProb[profile<->MIXED, strategy->STRATEGY,value->NUMBER] =: MIXED

Description

SetStrategyProb sets the component ofprofile for strategy to be equal tovalue . It is an error ifprofile andstrategy are not from the same normal form game. Returnsprofile .

See also

SetStrategyProbs, StrategyProb.

168

Chapter 5. Command Language Function Reference

SetStrategyProbs

NameSetStrategyProbs — Sets the probabilities for a player in a profile

Synopsis

SetStrategyProbs[profile<->MIXED, player->NFPLAYER,value->LIST(NUMBER)] =: MIXED

Description

SetStrategyProbs sets the components ofprofile for player to be equal tovalue . It is an error ifprofile andplayer are not from the same normal form game, or if the length ofvalue is not the same as thenumber of strategies forplayer in the support ofprofile . Returnsprofile .

See also

SetStrategyProb, StrategyProb.

Shell

NameShell — Runs a child process

Synopsis

Shell[{command->""}, {spawn->True}] =: INTEGER

Description

Shell runs a child process. The text string to be executed by the shell is given incommand, andspawn specifieswhether to run in the foreground or background.

169

Chapter 5. Command Language Function Reference

See also

Platform.

SimpDivSolve

NameSimpDivSolve — Compute Nash equilibria via simplicial subdivision

Synopsis

SimpDivSolve[support->NFSUPPORT, {stopAfter->1},{nRestarts->1}, {leashLength->0},{precision->Float}, {nEvals<->0},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(MIXED)

SimpDivSolve[support->EFSUPPORT, {asNfg->False},{stopAfter->1}, {nRestarts->1}, {leashLength->0},{precision->Float}, {nEvals<->0},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: LIST(BEHAV)

Description

SimpDivSolve computes a Nash equilibrium for a game using a simplicial subdivision algorithm. The behavior ofthe algorithm may be modified by several optional parameters:

• asNfg : By default, this isFalse . If it is specified to beTrue , the extensive form game is solved by recursivelyconverting its marked subgames into normal form, solving, and reconstructing the solution as a behavior profile.Note that currently simplicial subdivision is only implemented on the normal form, so this parameter must alwaysbe specified andTrue .

• stopAfter : Maximum number of equilibria to find. Default is 1.

• precision : Determines the precision of the computation. Default is floating point precision.

• nRestarts : Number of restarts. At each restart the mesh of the triangulation is halved.

• leashLength : Sets the leash length. Default is 0, which results in no constraint, or no leash. Note that if thisparameter is set to a value different from 0, the algorithm is no longer guaranteed to converge.

170

Chapter 5. Command Language Function Reference

Sort

NameSort — Sorts a list

Synopsis

Sort[x->LIST(NUMBER)] =: LIST(NUMBER)Sort[x->LIST(TEXT)] =: LIST(TEXT)Sort[x->LIST(T), by->LIST(NUMBER)] =: LIST(T)Sort[x->LIST(T), by->LIST(TEXT)] =: LIST(T)

Description

The first two version ofSort Returns a list consisting of the elements ofx sorted in increasing order.

The third and fourth versions ofSort return a list consisting of the elements oflist , sorted according to theordering of the elements ofby . It is an error iflist andby do not have the same dimension.

StartWatch

NameStartWatch — Starts the system stopwatch

Synopsis

StartWatch[] =: NUMBER

171

Chapter 5. Command Language Function Reference

Description

StartWatch starts the system stopwatch. This function has no effect if the stopwatch is already running. Returns theamount of time since the stopwatch was started.

See also

ElapsedTime, IsWatchRunning, StopWatch.

StopWatch

NameStopWatch — Starts the system stopwatch

Synopsis

StopWatch[] =: NUMBER

Description

StopWatch stops the system stopwatch. If the stopwatch was not running, this function has no effect. Returns theamount of time on the stopwatch.

See also

ElapsedTime, IsWatchRunning, StartWatch.

Strategies

NameStrategies — Returns the list of strategies belonging to a player

172

Chapter 5. Command Language Function Reference

Synopsis

Strategies[player->NFPLAYER, support->NFSUPPORT] =: LIST(STRATEGY)

Description

Strategies returns the list of strategies from whichplayer may choose insupport .

See also

Player.

StrategyNumber

NameStrategyNumber — Returns the index of a strategy in a support

Synopsis

StrategyNumber[strategy->STRATEGY, sup->NFSUPPORT] =: INTEGER

Description

StrategyNumber returns the number assigned tostrategy in the supportsup . Strategies for each player arenumbered from 1 to the number of strategies for the player. If a strategy is not in the corresponding support, it isassigned a number of 0.

See also

Strategies.

173

Chapter 5. Command Language Function Reference

StrategyProb

NameStrategyProb — Returns the index of a strategy in a support

Synopsis

StrategyProb[profile->MIXED, strategy->STRATEGY] =: NUMBER

Description

StrategyProb returns the probability thatstrategy is chosen when all players are followingprofile . It is anerror if profile andstrategy are not from the same normal form game.

See also

SetStrategyProb, SetStrategyProbs.

StrategyProbs

NameStrategyProbs — Returns the list of strategy probabilities for a profile

Synopsis

StrategyProbs[profile->MIXED] =: LIST(LIST(NUMBER))

Description

StrategyProbs returns a nested list of the probabilities for each strategy underprofile . The (i,j)th entry is theprobability of player i adopting strategy j.

174

Chapter 5. Command Language Function Reference

See also

SetStrategyProbs, StrategyProb.

StrategyValue

NameStrategyValue — Returns the payoff to playing a strategy against a profile

Synopsis

StrategyValue[profile->MIXED, strategy->STRATEGY] =: NUMBER

Description

StrategyValue returns the expected payoff to a player (who is in control of the strategy set includingstrategy )of choosingstrategy when all players are followingprofile . It is an error ifprofile andstrategy arenot from the same normal form game.

See also

StrategyProb, StrategyValues.

StrategyValues

NameStrategyValues — Returns the payoff to playing a strategy against a profile

Synopsis

StrategyValues[profile->MIXED] =: LIST(LIST(NUMBER))

175

Chapter 5. Command Language Function Reference

Description

StrategyValues returns a list of expected payoffs of each strategy (to the player who chooses that strategy). The(i,j)th entry is the expected payoff to player i of strategy j, where the index numbers correspond to the output ofPlayers andStrategies , respectively.

See also

StrategyProb, StrategyValue.

Subgames

NameSubgames — Returns the list of subgame roots in an extensive form game

Synopsis

Subgames[efg->EFG] =: LIST(NODE)

Description

Subgames returns the list of nodes which are roots of subgames inefg . The ordering of the list is such that allchildren of a node are listed before the node.

See also

MarkSubgame, MarkedSubgame, UnMarkSubgame.

176

Chapter 5. Command Language Function Reference

Support

NameSupport — Returns the support of a game or profile

Synopsis

Support[efg->EFG] =: EFSUPPORTSupport[nfg->NFG] =: NFSUPPORTSupport[profile->BEHAV] =: EFSUPPORTSupport[profile->MIXED] =: NFSUPPORT

Description

The first two versions ofSupport return the support of the gameefg or nfg , containing all actions or strategies,respectively, in the game.

The third and fourth versions ofSupport return the support on whichprofile is defined.

See also

AddAction, AddStrategy, Behav, Mixed, RemoveAction, RemoveStrategy.

Text

NameText — Converts a value to a text string

Synopsis

Text[x->NUMBER] =: TEXTText[x->TEXT] =: TEXT

177

Chapter 5. Command Language Function Reference

Description

Text convertsx into a text string.

Times

NameTimes — Returns the product of two numbers, or a number and a profile

Synopsis

Times[x->NUMBER, y->NUMBER] =: NUMBERTimes[x->NUMBER, y->MIXED] =: MIXEDTimes[x->NUMBER, y->BEHAV] =: BEHAV

Description

Times computes the product ofx andy . For profiles, the product is defined as multiplying elementwise.

Short form

x * y

See also

Minus, Plus.

Transpose

NameTranspose — Returns the transpose of a rectangular matrix

178

Chapter 5. Command Language Function Reference

Synopsis

Transpose[x->LIST(LIST(T))] =: LIST(LIST(T))

Description

Transpose returns the transpose of a rectangular matrix. It is an error iflist is not rectangular.

See also

Inverse.

UnAssign

NameUnAssign — Undefines a variable

Synopsis

UnAssign[name->TEXT] =: BOOLEAN

Description

UnAssign undefines the variable with namename. ReturnsTrue if the variable was defined, andFalse if thevariable was not defined, at the time of the call.

Short form

x :=

See also

Assign, Clear.

179

Chapter 5. Command Language Function Reference

UnDominated

NameUnDominated — Computes the undominated actions or strategies in a support

Synopsis

UnDominated[support->NFSUPPORT, {strong->False},{mixed->False}, {precision->Rational}, {time<->0.000000},{traceFile<->(Output)}, {traceLevel->0}] =: NFSUPPORT

UnDominated[support->EFSUPPORT, {strong->False}, {conditional->False},{time<->0.000000}, {traceFile<->(Output)},{traceLevel->0}] =: EFSUPPORT

Description

UnDominated finds dominated strategies, or actions, as appropriate, in asupport . The returned support containsonly the undominated strategies or actions; if this support is identical to the input support, no strategies or actionswere found to be dominated. The following optional parameters may be specified to modify the behavior of theelimination:

• strong By default, all weakly dominated strategies or actions are eliminated. If this is specifiedTrue ,elimination is based on strict dominance.

• mixed : By default, elimination is done in pure strategies or actions. If this is specifiedTrue , elimination is doneby examining mixtures over other strategies or actions. Note that mixed elimination is only implemented fornormal form games.

• conditional : Dominance computations are conditional on reaching infoset containing the action. For example,a behavior strategy may be strongly dominated conditional on reaching its information set, but only weaklydominated in the entire game. Only relevant for extensive form games.

• precision : Default precision is rational. Note that the precision parameter is only applicable for mixeddomination. Pure strategy domination always uses rational precision.

180

Chapter 5. Command Language Function Reference

UnMarkSubgame

NameUnMarkSubgame — Removes a subgame from the list used by Nash equilibrium algorithms

Synopsis

UnMarkSubgame[node->NODE] =: NODE

Description

UnMarkSubgame unmarksnode as being the root of a subgame for use in later computation. Ifnode is not markedas a subgame root, or ifnode is the root node, this function has no effect. Returns thenode .

See also

MarkSubgame, MarkedSubgame, Subgames.

UnSetEnv

NameUnSetEnv — Unsets an environment variable

Synopsis

UnSetEnv[name->TEXT] =: BOOLEAN

Description

UnSetEnv unsets the environment variablename.

181

Chapter 5. Command Language Function Reference

See also

GetEnv, SetEnv.

Version

NameVersion — Returns the version of Gambit

Synopsis

Version[] =: NUMBER

Description

Version returns the version number of Gambit as a text string.

While

NameWhile — Iterates over expressions while a condition is true

Synopsis

While[boolean-expression, statement-list]

Description

While defines a block of statements to be executed repeatedly. See the section on control structures for completeinformation.

182

Chapter 5. Command Language Function Reference

See also

For.

Write

NameWrite — Writes an object to a text stream

Synopsis

Write[output<->OUTPUT, x->T] =: OUTPUTWrite[output<->OUTPUT, x->LIST(T)] =: OUTPUT

Description

Write does a formatted write ofx to output .

See also

Format, ListFormat, Output, Read.

WriteSequenceForm

NameWriteSequenceForm — Writes the sequence form for an extensive form game to a stream

Synopsis

WriteSequenceForm[output<->OUTPUT, efg->EFG] =: OUTPUT

183

Chapter 5. Command Language Function Reference

Description

WriteSequenceForm writes the sequence form for the gameefg to output.

See also

SequenceForm, SequenceFormConstraints, SequenceFormStrats.

5.2. Categorical listing of functions

This section contains a list of functions organized by category. For a description of each function and its arguments,refer to the following, alphabetically organized, section.

In the GCL, we have tried to minimize the number of built-in functions to include only those that are essential. Theidea is that any other function can be built up as a user defined function from the built-in functions. As part of theGCL distribution, we provide a library of useful user defined functions in the file \verb+stdudfs.gcl+. If the line\verb+Include["stdudfs.gcl"]+ is in the \verb+gclini.gcl+ file, then this file is loaded when the GCL is started. Theuser can also load their own set of user defined functions by adding a line \verb+Include["myudfs.gcl"]+

The reason for minimizing the number of built-in funcitons is that it allows for greater flexibility of use of the GCL,and minimizes clogging up of the space of functions names. It is much easier for users to modify or redefine userdefined functions to suit their particular purpose than to modify built-in functions. Also, this approach makes itpossible to run a “stripped down” version of the GCL if memory is a premium, by just not including unused userdefined functions.

The cost to the above approach is that user defined functions can take longer to execute than a corresponding built-infunction with the same functionality.

Much of the development of the GCL is based on our own computational experience, and tends to be optimized withrespect to the kinds of problems we encounter. However, it may not be optimized for the type of problems you findinteresting. If you find that certain operations in the GCL are unacceptably slow, we would appreciate gettingfeedback on this.

5.2.1. General functionality

184

Chapter 5. Command Language Function Reference

5.2.1.1. Variables and functions

Assign

Clear

Include

NewFunction

Quit

UnAssign

5.2.1.2. Flow control

For

If

While

5.2.1.3. Help

Help

HelpVars

IsDefined

Manual

Version

5.2.1.4. Timing

Date

ElapsedTime

IsWatchRunning

StartWatch

StopWatch

185

Chapter 5. Command Language Function Reference

5.2.1.5. System information and commands

ExePath

GambitExe (user-defined)

GetEnv

Platform

SetEnv

Shell

UnSetEnv

5.2.2. Basic data types

5.2.2.1. Logic

And

Not

Or

5.2.2.2. Relational operators

Equal

Greater

GreaterEqual

Less

LessEqual

NotEqual

186

Chapter 5. Command Language Function Reference

5.2.2.3. Mathematical operations

Divide

Exp

Float

IntegerDivide

Inverse

Log

Max (user-defined)

MaxInt (user-defined)

Min (user-defined)

Minus

Modulus

Negate

Parentheses

Plus

Power

Precision

Randomize

Randomize (user-defined)

Rational

Times

5.2.2.4. Strings

Concat (user-defined)

Greater

GreaterEqual

Less

LessEqual

NthChar

NumChars

Plus

Text

187

Chapter 5. Command Language Function Reference

5.2.2.5. Lists

ArgMax

CartesianProd (user-defined)

Concat

Contains

Dimensions (user-defined)

Dot

Filter

Flatten

Index

IsList

Length

List

Max (user-defined)

Min (user-defined)

NthElement

NumElements

Prepend (user-defined)

Remove

Sort

Sum(user-defined)

Transpose

5.2.2.6. Data conversions

Float

Float (user-defined)

Integer

ListForm (user-defined)

Null

Precision

Rational

Rational (user-defined)

Text

188

Chapter 5. Command Language Function Reference

5.2.3. Input and output

Display (user-defined)

Format

GetFormat

GetListFormat

GetIntegerFormat (user-defined)

GetNumericFormat (user-defined)

GetSolutionFormat (user-defined)

GetTextFormat (user-defined)

Input

IsEof

ListFormat

LoadEfg

LoadNfg

Output

Print

Read

Read (user-defined)

ReadText

SaveEfg

SaveNfg

SetIntegerFormat (user-defined)

SetListFormat (user-defined)

SetNumericFormat (user-defined)

SetSolutionFormat (user-defined)

SetTextFormat (user-defined)

Write

WriteSequenceForm

5.2.4. Building games

5.2.4.1. Extensive form manipulation

189

Chapter 5. Command Language Function Reference

AddAction Adds an action to a support

AddMove Adds a move to a game at a terminal node

AddMove (user-defined)

AddNode Adds a node to a basis

Basis

CompressEfg

CopyTree

DeleteAction

DeleteEmptyInfoset

DeleteEmptyInfosets (user-defined)

DeleteMove

DeleteOutcome

DeleteTree

InsertAction

InsertMove

MergeInfosets

MoveToInfoset

MoveTree

NewEfg

NewInfoset

NewInfoset (user-defined)

NewOutcome

NewOutcome (user-defined)

NewPlayer

NewPlayer (user-defined)

Randomize (user-defined)

RemoveAction

RemoveNode

Reveal

SequenceForm

SequenceFormConstraints

SequenceFormStrats

SetChanceProbs

SetComment

SetName

SetOutcome

SetPayoff

SetPayoffs (user-defined)

Support

190

Chapter 5. Command Language Function Reference

5.2.4.2. Normal form manipulation

AddStrategy Adds a strategy to a support

AgentForm Creates the agent normal form for an extensive form game

CompressNfg

DeleteOutcome

ListForm (user-defined)

NewNfg

NewNfg (user-defined)

NewOutcome

NewOutcome (user-defined)

NewPlayer

NewPlayer (user-defined)

Nfg

Nfg (user-defined)

OutcomeForm (user-defined)

Randomize (user-defined)

RemoveStrategy

SetComment

SetName

SetOutcome

SetPayoff

SetPayoffs (user-defined)

Support

5.2.4.3. Getting information

ActionNumber native Returns the index of an action in asupport or basis

ActionNumber stdudfs.gcl

Actions native Returns the list of actions in a supportat an information set

Actions stdudfs.gcl

AllActions stdudfs.gcl

191

Chapter 5. Command Language Function Reference

AllInfosets stdudfs.gcl

AllMembers stdudfs.gcl

Ancestors stdudfs.gcl

Centroid stdudfs.gcl

Chance native

ChanceProb native

Children native

Comment native

Descendants stdudfs.gcl

Game native

History stdudfs.gcl

Infoset native

Infosets native

Infosets stdudfs.gcl

IsConsistent native

IsConstSum native

IsNull native

IsPerfectRecall native

IsPredecessor native

IsRoot stdudfs.gcl

IsSuccessor native

Members native

Members stdudfs.gcl

Mixed native

Mixed stdudfs.gcl

Name native

NextSibling native

NodeNumber native

Nodes native

NodeTree stdudfs.gcl

NonterminalNodes stdudfs.gcl

NthChild native

NumActions stdudfs.gcl

NumChildren stdudfs.gcl

NumMembers stdudfs.gcl

NumPlayers stdudfs.gcl

NumStrats stdudfs.gcl

Outcome native

Outcomes native

192

Chapter 5. Command Language Function Reference

Parent native

Payoff native

Payoffs stdudfs.gcl

Player native

PlayerNumber stdudfs.gcl

Players native

PriorAction native

PriorSibling native

Profiles stdudfs.gcl

RootNode native

Strategies native

Strategies stdudfs.gcl

StrategyNumber native

TerminalNodes stdudfs.gcl

5.2.5. Solving games

5.2.5.1. Subgames

MarkedSubgame native

MarkedSubgames stdudfs.gcl

MarkSubgames stdudfs.gcl

MarkSubgame native

Subgames native

UnMarkSubgames stdudfs.gcl

UnMarkSubgame native

5.2.5.2. Dominance elimination and supports

Actions native

Actions stdudfs.gcl

193

Chapter 5. Command Language Function Reference

AddAction native

AddStrategy native

Basis native

IsDominated native

IterativeUnDominated stdudfs.gcl

NthElement stdudfs.gcl

PossibleNashSupports native

RemoveAction native

RemoveStrategy native

Strategies native

Strategies stdudfs.gcl

Support native

UnDominated native

UnDominated stdudfs.gcl

5.2.5.3. Solution algorithms

EnumMixedSolve native

EnumMixedSolve stdudfs.gcl

EnumPureSolve native

EnumPureSolve stdudfs.gcl

LcpSolve native

LcpSolve stdudfs.gcl

LiapSolve native

LiapSolve stdudfs.gcl

LpSolve native

LpSolve stdudfs.gcl

PolEnumSolve native

QreGridSolve native

QreSolve native

QreSolve stdudfs.gcl

SimpDivSolve native

SimpDivSolve stdudfs.gcl

194

Chapter 5. Command Language Function Reference

5.2.5.4. Equilibria and refinements

AllNash stdudfs.gcl

AllPerfect stdudfs.gcl

AllSequential stdudfs.gcl

AllSubgamePerfect stdudfs.gcl

ManyNash stdudfs.gcl

OneNash stdudfs.gcl

OnePerfect stdudfs.gcl

OneSequential stdudfs.gcl

OneSubgamePerfect stdudfs.gcl

5.2.5.5. Solution information

Accuracy native

ActionProb native

ActionProbs stdudfs.gcl

ActionValue native

ActionValues stdudfs.gcl

Behav native

Behav stdudfs.gcl

Belief native

Beliefs stdudfs.gcl

Creator native

InfosetProb native

InfosetProbs stdudfs.gcl

InfosetValue native

InfosetValues stdudfs.gcl

IsNash native

IsPerfect native

IsSequential native

IsSubgamePerfect native

LiapValue native

Mixed native

Mixed stdudfs.gcl

NodeValue native

195

Chapter 5. Command Language Function Reference

NodeValues stdudfs.gcl

Payoff native

Payoffs stdudfs.gcl

QreLambda native

QreValue native

RealizProb native

RealizProbs stdudfs.gcl

Regret native

Regrets stdudfs.gcl

SetActionProbs native

SetStrategyProb native

SetStrategyProbs native

SetProbs stdudfs.gcl

StrategyProb native

StrategyProbs native

StrategyValue native

StrategyValues stdudfs.gcl

196

Appendix A. Reference: Algorithms to ComputeNash Equilibria

This appendix is an overview of the literature on computing Nash equilibria in finite games. The focus here is ondetailing the essentials of the theory for the user who wants to compute equilibria, and to document theimplementations of the algorithms provided in Gambit. The interested user should consult McKelvey andMcLennan’s survey article [McKMcL96], plus the references therein and thebibliographyof this manual for moreinformation.

A.1. Tips on getting started

Gambit has a number of algorithms to find Nash equilibria. The appropriate algorithm to use depends on a number offactors, most importantly, the number of players in the game, and the number of equilibria you want to find.

Before computing equilibria, you may wish to eliminate dominated strategies. The smaller the number of strategiesthe algorithm must consider, the faster any algorithm will run. However, dominance elimination can itself becomputationally intensive, especially if domination by mixed strategies (for the normal form) is considered, or ifdominance elimination is done on a large extensive form.

• If you want to find more than one, or all Nash equilibria of a game, then you may first successively eliminatestrongly dominated strategies. Any equilibrium of the original game will also be an equilibrium of the reducedgame.

• If you just want to findoneNash equilibrium, you can first successively eliminateweaklydominated strategies.Elimination of weakly dominated strategies may eliminate some Nash equilibria of the original game, so it shouldnot be used if you want to find multiple Nash equilibria, but any Nash equilibrium to the reduced game will be anequilibrium to the original game, so it can be used if you only want to find one equilibrium.

A.1.1. Common algorithm parameters

There are a few parameters which are common among several algorithms.

A.1.2. Pure strategy equilibria

TheEnumPureSolvealgorithm can be used to enumerate all of the pure strategy equilibria for both extensive andnormal form games.

197

Appendix A. Reference: Algorithms to Compute Nash Equilibria

A.1.3. Two Person Constant Sum Games

For two person constant sum normal form games, the minimax theorem applies. The set of Nash equilibria is aconvex set, and the problem of finding Nash equilibria can be formulated as a linear program. TheLpSolvealgorithmwill solve a constant sum game using this approach.

A.1.4. Two Person Games

For two person nonzero sum games, the problem of finding Nash equilibria can be formulated as a linearcomplementarity problem, and exact solutions can be found as long as computations are done in rationals. TheLcpSolvealgorithm solves a two person game using this approach. Note that this algorithm can also be used directlyon an extensive form game, where it implements the Koller, Megiddo, von Stengel sequence form [KolMegSte94].

For a two person game theEnumMixedSolvealgorithm will enumerate all of the extreme points of the componentsof the set of Nash equilibria, and hence can be used to findall Nash equilibria.

A.1.5. Games With More Than Two Players

For n-person normal form games, with n greater than two, thePolEnumSolvealgorithm will find all Nash equilibria.The PolEnum algorithm may be computationally infeasible on large games. Thus other algorithms are also availablefor finding one or a sample of Nash equilibria. Since Nash equilibria can be irrational, the algorithms to locate oneequilibrium will only find approximations (to machine accuracy) of Nash equilibria.

SimpDivSolveSimpDivSolve is guaranteed to locate one equilibrium for an n-person normal form game. Thisalgorithm can be very slow on some games. Hence two other algorithms are also implemented,QreSolveandLiapSolve. These algorithms can also be used to search for multiple equilibria (with no guarantee that all have beenfound), and to search for equilibria close to a given starting point.

A.1.6. Sequential Equilibria

Sequential equilibria are equilibria that prescribe optimal behavior at any information set of the extensive form, givena consistent assessment of beliefs. See [KreWil82]. QreSolveon extensive form games is guaranteed to converge to asequential equilibrium.

A.2. EnumMixedSolve

EnumMixedSolve finds all Nash equilibria for a two person game. More precisely, it finds the set of extreme pointsof the components of the set of Nash equilibria. The procedure is to enumerate the set of complementary basic

198

Appendix A. Reference: Algorithms to Compute Nash Equilibria

feasible solutions. See Mangasarian [Man64] for details.

Important: EnumMixedSolve only works for two-person normal form games.

A.3. EnumPureSolve

Computation of pure strategy Nash equilibria is done by simple enumeration. All pure strategies are checked to see ifthey are Nash equilibria.

A.4. QreSolve

Computes a branch of the logistic quantal response equilibrium correspondence for n-person normal form games (asdescribed [McKPal95]) and n-person extensive form games (as described in [McKPal98]).

This algorithm returns the last point computed. This algorithm computes the principal branch of the logistic quantalresponse equilibrium correspondence. In this case taking the limit, as lambda goes to infinity, the quantal responseequilibrium defines a unique selection from the set of Nash equilibrium for generic normal form games. Similarly,for extensive form games, it defines a selection from the set of sequential equilibria. Therefore, in extensive formgames, this algorithm can be used to compute approximations to a sequential equilibrium.

A.5. QreGridSolve

Performs a grid search to compute the complete logistic quantal response correspondence, as described in[McKPal95].

Important: This algorithm is very computationally intensive, and should only be attempted on small games.

\item[Grid 1 Del:] Grid size for search over course grid of probability space. \item[Grid 1 Tol:] Maximum value ofobjective function for which to accept solution on course grid. \item[Grid 2 Del:] Grid size for search over fine grid ofprobability space. \item[Grid 2 Tol:] Maximum value of objective function for which to accept solution on fine grid.

199

Appendix A. Reference: Algorithms to Compute Nash Equilibria

A.6. LcpSolve

This algorithm formulates and solves the game as a linear complementarity problem. For a normal form game, thisalgorithm searches for equilibria of the specified normal form game using the Lemke-Howson algorithm, asdescribed in [LemHow64]. Eaves [Eav71] lexicographic rule for linear complementarity problems is used to avoidcycling.

In the Lemke-Howson algorithm equilibria are found by following paths of "almost" equilibria, where one relaxes atmost one constaint. Equilibria are thus inter-connected by networks of paths that result when different of theconstraints are relaxed. One can find the set of "accessible" equilibria in such methods by starting at the extraneoussolution and then tracing out this entire network. See, e. g., Shapley [Sha74]. However, the set of accessibleequilibria does not necessarily include all Nash equilibria.

For extensive form games, this algorithm implements Lemke’s algorithm on the sequence form of the game, asdefined by Koller, Megiddo and von Stengel, in [KolMegSte94].

Important: This algorithm is fast, but only works for two person games. Wilson [Wil71] and Rosenmuller [Ros71]have suggested ways in which the Lemke-Howson Algorithm can be extended to general $n$-player games, butthese extensions require methods of tracing the solution to a set of non linear simultaneous equations, and havenot been implemented in Gambit. Also, on some problems with data type of Double, the current implementationcan exhibit numerical instability which in extreme cases can even lead to incorrect solutions. Solving the sameproblem with Rationals will resolve any such difficulties. However, the algorithm is much slower when operatingon Rationals than on Doubles.

A.7. LiapSolve

Finds Nash equilibria via the Lyapunov function method described in [McK91]. Works on either the extensive ornormal form. This algorithm casts the problem as a function minimization problem by use of a Lyapunov functionfor Nash equilibria. This is a continuously differentiable non negative function whose zeros coincide with the set ofNash equilibria of the game. A standard descent algorithm is used to find a constrained local minimum of thefunction from any given starting location. Since a local minimum need not be a global minimum (with value 0), thealgorithm is not guaranteed to find a Nash equilibrium from any fixed starting point. The algorithm thus incorporatesthe capability of restarting. The algorithm starts from the initial starting point determined by the parameterstart .If a Nash equilibrium is not found, it will keep searching from new randomly chosen starting points until a Nashequilibrium has been found or the maximum number of tries is exceeded, whichever comes first. For an extensiveform game, if the algorithm converges, it converges to a sequential equilibrium1

Important: The disadvantages of this method are that it is generally slower than any of the above methods, andalso, there can be local minima to the Liapunov function which are not zeros of the function. Thus the algorithmcan potentially converge to a non Nash point. However, inspection of the objective function can determine if thisproblem has occurred. If the objective function is zero, a Nash equilibrium has been found. If it is greater thanzero, the point is not Nash. The algorithm will automatically check this. If the objective function is larger than thetolerance, then the point is discarded.

200

Appendix A. Reference: Algorithms to Compute Nash Equilibria

The following parameters can be set; \begin{description} \item[nTries:] Sets the maximum number of attempts atfinding each equilibrium. Note that a value of 0 means the algorithm will continue forever, or until the algorithm isterminated by the user, whichever comes first. \item[start:] Sets the starting profile for the descent algorithm. {\bfDefault} is the centroid. \end{description}

A.8. LpSolve

This algorithm formulates and solves the game as a linear program, and finds the minimax solution of the game. Thisalgorithm only works for two person, zero sum games. This algorithm only finds one Nash equilibrium. However,For a constant sum game, any other equilibria will have the same value. There are no algorithm specific parameters.

A.9. PolEnumSolve

Solves for all totally mixed Nash equilibrium of the game on a given support. The algorithm iterates through allsub-supports of the initial support to find the full support equilibria on each sub-support. Supports with singularsolutions are skipped by the algorithm when determined to have singular solutions.

On each sub-support, the algorithm starts with a cube containing the space of possible solutions and proceedsrecursively. The recursion step begins with a subcube. The subcube is discarded if the cube is irrelevant in the senseof lying outside the space of possible solutions. Otherwise a modified Newton’s method is used to search for asolution in the subcube. In the event that such a solution is found, Taylor’s series information at the solution is usedto inquire whether the solution is necessarily the unique solution in the subcube. If Newton’s method leaves thesubcube before finding a solution, Taylor’s series information at the center is used to inquire whether we can be surethat the subcube contains no solutions. If neither of these procedures resolves the issue, the subcube is subdividedand this recursion is performed on each smaller subcube. Supports with singular solutions

The following optional parameters may be used to modify the behavior of the algorithm: \begin{description}\item[Singular Supps:] Returns a list of the supports which have singular solutions. {\bf Note:} This is currently notimplemented in the GUI, but is available in the GCL. \item[recurse:] Determines whether to recurse to all subsupports. Default is {\bf True}. \end{description}

A.10. SimpDivSolve

Computes a Nash equilibrium to a normal form game based on a simplicial subdivision algorithm. The algorithmimplemented is that of [VTH87]. The algorithm is a simplicial subdivision algorithm which can start at any point inthe simplex. The algorithm starts with a given grid size, follows a path of almost completely labeled subsimplexes,

201

Appendix A. Reference: Algorithms to Compute Nash Equilibria

and converges to a completely labeled sub-simplex that approximates the solution. Additional accuracy is obtainedby refining the grid size and restarting from the previously found point. The idea is that by restarting at a closeapproximation to the solution, each successive increase in accuracy will yield a short path, and hence be quick.

In its pure form, the algorithm is guaranteed to find at least one mixed strategy equilibrium to any n-person game.Experience shows that the algorithm works well, and is acceptably fast for many moderate size problems. But insome examples it can be quite slow. The reason for this is that sometimes after restarting with a refined grid size,even though the starting point is a good approximation to the solution, the algorithm will go to the boundary of thesimplex before converging back to a point that is close to the original starting point. When this occurs, each halvingof the grid size will take twice as long to converge as the previous grid size. If a high degree of accuracy is required,or if the normal form is large, this can result in the algorithm taking a long time to converge.

In order to combat the above difficulty, a parameter ’leash’ has been added to the algorithm which places a limit onthe distance which the algorithm can wander from the restart point. (Setting this parameter to 0 results in no limit,and gives the pure form of the algorithm.) With this parameter set to a non trivial value, the algorithm is no longerguaranteed to converge, and setting small values of the parameter will sometimes yield lack of convergence.However, experience shows that values of the parameter on the order of 10 generally do not destroy convergence, andyield much faster convergence.

Parameters: \begin{description} \item[Stop after:] Maximum number of equilibria to find. Default is 1. \item[nRestarts:] Number of restarts. At each restart the mesh of the triangulation is halved. So this parameter determinesthe final mesh by the formula ${1/2}^{ndivs}$. \item[Leash:] Sets the leashlength. Default is 0, which results in noconstraint, or no leash. \end{description}

Notes1. Andrew Solnick, personal communication to Richard McKelvey

202

Appendix B. A GCL program to build and solve theholdout game

The following GCL program, which is distributed in the fileholdout.gcl in the Gambit distribution, defined a userdefined function

HoldoutGame[stages->INTEGER, prob1->NUMBER, prob2->NUMBER,dist->NUMBER, b->NUMBER] =: EFG

which can be used to create a finite horizon version of the "holdout" game studied in McKelvey and Palfrey,"Endogeneity of alternating offers in a bargaining game," Journal of Economic Theory 73:425-437, 1997. To use thefunction, include the fileholdout.gcl and then type

HoldoutGame[n,r1,r2,d,b]

wheren is the number of stages,r1 andr2 are the prior probabilities that players 1 and 2 are a low benefit type,d isthe common discount factor, andb is the common benefit of giving in to the high type. For example, the followingsequence of commands

Include["holdout.gcl"]e:= HoldoutGame[1, .5, .5, .9, .5]SaveEfg[e,"holdout1.efg"]e:= HoldoutGame[7, .5, .5, .9,. 5]SaveEfg[e,"holdout7.efg"]

create and save a one-stage and seven-stage holdout game, respectively.

The contents of the fileholdout.gcl are reproduced here. This makes use of some of the user-defined functionsavailable instdudfs.gcl .

//// A gcl program to construct a multi stage holdout game//

NewFunction[MultiStageHoldout[ efg<->EFG, node->NODE, isets->LIST(INFOSET), \out->LIST(EFOUTCOME), stages->NUMBER, disc->NUMBER],

// build treei1:=isets_1;i2:=isets_2;AddMove[i1,node];AddMove[i2,node#1];If[NumActions[i1]>1, AddMove[i2, node#2] ];

// attach outcomesSetOutcome [node#1#1, out_1 ];If[NumActions[i2]>1, SetOutcome [node#1#2, out_2 ] ];If[NumActions[i1]>1,

SetOutcome [node#2#1, out_3 ];If[NumActions[i2]>1, SetOutcome [node#2#2, out_4 ] ]];

203

Appendix B. A GCL program to build and solve the holdout game

// recurse to next stageIf[NumActions[i1]>1 || NumActions[i2]>1,

If[stages>1,stages;diset := NewInfoset [Chance[efg], {"",""} , "Discount"];SetChanceProbs [diset,{1.0-disc,disc}];AddMove[diset, node#1#1];MultiStageHoldout[efg,node#1#1#2,isets,out,stages-1,disc]

]]

];

NewFunction[HoldoutGame[ stages->NUMBER,prob1->NUMBER, prob2->NUMBER, disc->NUMBER, b->NUMBER],

e := NewEfg[];n := RootNode[e];

// create chance movesciset1 := NewInfoset [Chance[e], {"High", "Low"} , "Choose 1’s type"];ciset2 := NewInfoset [Chance[e], {"High", "Low"} , "Choose 2’s type"];SetChanceProbs [ciset1,{prob1,1.0-prob1}];SetChanceProbs [ciset2,{prob2,1.0-prob2}];AddMove[ciset1, n];AddMove[ciset2, n#1];AddMove[ciset2, n#2 ];

// Define players, actions, and outcomespl1 := NewPlayer [e,"Player 1"];pl2 := NewPlayer [e,"Player 2"];is1w := NewInfoset [ pl1 , {"H", "G"} ];is1s := NewInfoset [ pl1 , {"H"} ];is2w := NewInfoset [ pl2 , {"H", "G"} ];is2s := NewInfoset [ pl2 , {"H"} ];out1:= SetPayoffs[ NewOutcome[e],{0.0, 0.0}];out2:= SetPayoffs[ NewOutcome[e],{1.0, b}];out3:= SetPayoffs[ NewOutcome[e],{b, 1.0}];out4:= SetPayoffs[ NewOutcome[e],{b,b}];outs:={out1,out2,out3,out4};

// Create multi stage gamesMultiStageHoldout[ e, n#1#1, {is1w,is2w}, outs, stages, disc];MultiStageHoldout[ e, n#1#2, {is1w,is2s}, outs, stages, disc];MultiStageHoldout[ e, n#2#1, {is1s,is2w}, outs, stages, disc];MultiStageHoldout[ e, n#2#2, {is1s,is2s}, outs, stages, disc];nonterm:=NonterminalNodes[e];

// Make perfect recallFor[i:=1,i<= Length [nonterm],i:=i+1,

p:= Player [ Infoset [nonterm_i ] ];If[p!= Chance [e],

Reveal [ Infoset [nonterm_i ],{p}] ]];

e]

204

Appendix B. A GCL program to build and solve the holdout game

205

Bibliography

Articles on computation of Nash equilibria[Eav71] B. C. Eaves, “The linear complementarity problem”, 612-634,Management Science, 17, 1971.

[KolMegSte94] Daphne Koller, Nimrod Megiddo, and Bernhard von Stengel, “Efficient computation of equilibria forextensive two-person games”, 247-259,Games and Economic Behavior, 14, 1996.

[LemHow64] C. E. Lemke and J. T. Howson, “Equilibrium points of bimatrix games”, 413-423,Journal of theSociety of Industrial and Applied Mathematics, 12, 1964.

[Man64] O. Mangasarian, “Equilibrium points in bimatrix games”, 778-780,Journal of the Society for Industrial andApplied Mathematics, 12, 1964.

[McK91] Richard McKelvey,A Liapunov function for Nash equilibria, 1991, California Institute of Technology.

[McKMcL96] Richard McKelvey and Andrew McLennan, “Computation of equilibria in finite games”, 87-142,Handbook of Computational Economics, Edited by H. Amman, Edited by D. Kendrick, Edited by J. Rust,Elsevier, 1996.

[Ros71] J. Rosenmuller, “On a generalization of the Lemke-Howson Algorithm to noncooperative n-person games”,73-79,SIAM Journal of Applied Mathematics, 21, 1971.

[Sha74] Lloyd Shapley, “A note on the Lemke-Houson algorithm”, 175-189,Mathematical Programming Study, 1,1974.

[Tur02] Theodore Turocy, “A computational approach to quantal response equilibrium properties”, 2002.

[VTH87] G. van der Laan, A. J. J. Talman, and L. van Der Heyden, “Simplicial variable dimension algorithms forsolving the nonlinear complementarity problem on a product of unit simplices using a general labelling”,377-397,Mathematics of Operations Research, 1987.

[Wil71] Robert Wilson, “Computing equilibria of n-person games”, 80-87,SIAM Applied Math, 21, 1971.

[Yam93] Y. Yamamoto, 1993, “A Path-Following Procedure to Find a Proper Equilibrium of Finite Games ”,International Journal of Game Theory.

General game theory articles and texts[Harsanyi1967a] John Harsanyi, “Games of Incomplete Information Played By Bayesian Players I”, 159-182,

Management Science, 14, 1967.

[Harsanyi1967b] John Harsanyi, “Games of Incomplete Information Played By Bayesian Players II”, 320-334,Management Science, 14, 1967.

206

Bibliography

[Harsanyi1968] John Harsanyi, “Games of Incomplete Information Played By Bayesian Players III”, 486-502,Management Science, 14, 1968.

[KreWil82] David Kreps and Robert Wilson, “Sequential Equilibria”, 863-894,Econometrica, 50, 1982.

[McKPal95] Richard McKelvey and Tom Palfrey, “Quantal response equilibria for normal form games”, 6-38,Games and Economic Behavior, 10, 1995.

[McKPal98] Richard McKelvey and Tom Palfrey, “Quantal response equilibria for extensive form games”, 9-41,Experimental Economics, 1, 1998.

[Mye78] Roger Myerson, “Refinements of the Nash equilibrium concept”, 73-80,International Journal of GameTheory, 7, 1978.

[Nas50] John Nash, “Equilibrium points in n-person games”, 48-49,Proceedings of the National Academy ofSciences, 36, 1950.

[Sel75] Reinhard Selten,Reexamination of the perfectness concept for equilibrium points in extensive games, 25-55,International Journal of Game Theory, 4, 1975.

[vanD83] Eric van Damme, 1983,Stability and Perfection of Nash Equilibria, Springer-Verlag, Berlin.

Textbooks and general reference[Mye91] Roger Myerson, 1991,Game Theory: Analysis of Conflict, Harvard University Press.

207

Index

208


Recommended