Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

r""" 

Normal form games with N players. 

 

This module implements a class for normal form games (strategic form games) 

[NN2007]_. At present the following algorithms are implemented to 

compute equilibria of these games: 

 

* ``'enumeration'`` - An implementation of the support enumeration 

algorithm built in Sage. 

 

* ``'LCP'`` - An interface with the 'gambit' solver's implementation 

of the Lemke-Howson algorithm. 

 

* ``'lp'`` - A built-in Sage implementation (with a gambit alternative) 

of a zero-sum game solver using linear programming. See 

:class:`MixedIntegerLinearProgram` for more on MILP solvers in Sage. 

 

* ``'lrs'`` - A solver interfacing with the 'lrslib' library. 

 

The architecture for the class is based on the gambit architecture to 

ensure an easy transition between gambit and Sage. At present the 

algorithms for the computation of equilibria only solve 2 player games. 

 

A very simple and well known example of normal form game is referred 

to as the 'Battle of the Sexes' in which two players Amy and Bob 

are modeled. Amy prefers to play video games and Bob prefers to 

watch a movie. They both however want to spend their evening together. 

This can be modeled using the following two matrices: 

 

.. MATH:: 

 

A = \begin{pmatrix} 

3&1\\ 

0&2\\ 

\end{pmatrix} 

 

 

B = \begin{pmatrix} 

2&1\\ 

0&3\\ 

\end{pmatrix} 

 

Matrix `A` represents the utilities of Amy and matrix `B` represents the 

utility of Bob. The choices of Amy correspond to the rows of the matrices: 

 

* The first row corresponds to video games. 

 

* The second row corresponds to movies. 

 

Similarly Bob's choices are represented by the columns: 

 

* The first column corresponds to video games. 

 

* The second column corresponds to movies. 

 

Thus, if both Amy and Bob choose to play video games: Amy receives a 

utility of 3 and Bob a utility of 2. If Amy is indeed going to stick 

with video games Bob has no incentive to deviate (and vice versa). 

 

This situation repeats itself if both Amy and Bob choose to watch a movie: 

neither has an incentive to deviate. 

 

This loosely described situation is referred to as a Nash Equilibrium. 

We can use Sage to find them, and more importantly, see if there is any 

other situation where Amy and Bob have no reason to change their choice 

of action: 

 

Here is how we create the game in Sage:: 

 

sage: A = matrix([[3, 1], [0, 2]]) 

sage: B = matrix([[2, 1], [0, 3]]) 

sage: battle_of_the_sexes = NormalFormGame([A, B]) 

sage: battle_of_the_sexes 

Normal Form Game with the following utilities: {(0, 1): [1, 1], (1, 0): [0, 0], (0, 0): [3, 2], (1, 1): [2, 3]} 

 

To obtain the Nash equilibria we run the ``obtain_nash()`` method. In the 

first few examples, we will use the 'support enumeration' algorithm. 

A discussion about the different algorithms will be given later:: 

 

sage: battle_of_the_sexes.obtain_nash(algorithm='enumeration') 

[[(0, 1), (0, 1)], [(3/4, 1/4), (1/4, 3/4)], [(1, 0), (1, 0)]] 

 

If we look a bit closer at our output we see that a list of three 

pairs of tuples have been returned. Each of these correspond to a 

Nash Equilibrium, represented as a probability distribution over the 

available strategies: 

 

* `[(1, 0), (1, 0)]` corresponds to the first player only 

playing their first strategy and the second player also only playing 

their first strategy. In other words Amy and Bob both play video games. 

 

* `[(0, 1), (0, 1)]` corresponds to the first player only 

playing their second strategy and the second player also only playing 

their second strategy. In other words Amy and Bob both watch movies. 

 

* `[(3/4, 1/4), (1/4, 3/4)]` corresponds to players `mixing` their 

strategies. Amy plays video games 75% of the time and Bob watches 

movies 75% of the time. At this equilibrium point Amy and Bob will 

only ever do the same activity `3/8` of the time. 

 

We can use Sage to compute the expected utility for any mixed strategy 

pair `(\sigma_1, \sigma_2)`. The payoff to player 1 is given by the 

vector/matrix multiplication: 

 

.. MATH:: 

 

\sigma_1 A \sigma_2 

 

The payoff to player 2 is given by: 

 

.. MATH:: 

 

\sigma_1 B \sigma_2 

 

To compute this in Sage we have:: 

 

sage: for ne in battle_of_the_sexes.obtain_nash(algorithm='enumeration'): 

....: print("Utility for {}: ".format(ne)) 

....: print("{} {}".format(vector(ne[0]) * A * vector(ne[1]), vector(ne[0]) * B * vector(ne[1]))) 

Utility for [(0, 1), (0, 1)]: 

2 3 

Utility for [(3/4, 1/4), (1/4, 3/4)]: 

3/2 3/2 

Utility for [(1, 0), (1, 0)]: 

3 2 

 

Allowing players to play mixed strategies ensures that there will always 

be a Nash Equilibrium for a normal form game. This result is called Nash's 

Theorem ([Nas1950]_). 

 

Let us consider the game called 'matching pennies' where two players each 

present a coin with either HEADS or TAILS showing. If the coins show the 

same side then player 1 wins, otherwise player 2 wins: 

 

 

.. MATH:: 

 

A = \begin{pmatrix} 

1&-1\\ 

-1&1\\ 

\end{pmatrix} 

 

 

B = \begin{pmatrix} 

-1&1\\ 

1&-1\\ 

\end{pmatrix} 

 

It should be relatively straightforward to observe, that there is no 

situation, where both players always do the same thing, and have no 

incentive to deviate. 

 

We can plot the utility of player 1 when player 2 is playing a mixed 

strategy `\sigma_2 = (y, 1-y)` (so that the utility to player 1 for 

playing strategy number `i` is given by the matrix/vector multiplication 

`(Ay)_i`, ie element in position `i` of the matrix/vector multiplication 

`Ay`) :: 

 

sage: y = var('y') 

sage: A = matrix([[1, -1], [-1, 1]]) 

sage: p = plot((A * vector([y, 1 - y]))[0], y, 0, 1, color='blue', legend_label='$u_1(r_1, (y, 1-y))$', axes_labels=['$y$', '']) 

sage: p += plot((A * vector([y, 1 - y]))[1], y, 0, 1, color='red', legend_label='$u_1(r_2, (y, 1-y))$'); p 

Graphics object consisting of 2 graphics primitives 

 

We see that the only point at which player 1 is indifferent amongst 

the available strategies is when `y = 1/2`. 

 

If we compute the Nash equilibria we see that this corresponds to a point 

at which both players are indifferent:: 

 

sage: A = matrix([[1, -1], [-1, 1]]) 

sage: B = matrix([[-1, 1], [1, -1]]) 

sage: matching_pennies = NormalFormGame([A, B]) 

sage: matching_pennies.obtain_nash(algorithm='enumeration') 

[[(1/2, 1/2), (1/2, 1/2)]] 

 

The utilities to both players at this Nash equilibrium 

is easily computed:: 

 

sage: [vector([1/2, 1/2]) * M * vector([1/2, 1/2]) 

....: for M in matching_pennies.payoff_matrices()] 

[0, 0] 

 

Note that the above uses the ``payoff_matrices`` method 

which returns the payoff matrices for a 2 player game:: 

 

sage: matching_pennies.payoff_matrices() 

( 

[ 1 -1] [-1 1] 

[-1 1], [ 1 -1] 

) 

 

One can also input a single matrix and then a zero sum game is constructed. 

Here is an instance of `Rock-Paper-Scissors-Lizard-Spock 

<http://www.samkass.com/theories/RPSSL.html>`_:: 

 

sage: A = matrix([[0, -1, 1, 1, -1], 

....: [1, 0, -1, -1, 1], 

....: [-1, 1, 0, 1 , -1], 

....: [-1, 1, -1, 0, 1], 

....: [1, -1, 1, -1, 0]]) 

sage: g = NormalFormGame([A]) 

sage: g.obtain_nash(algorithm='enumeration') 

[[(1/5, 1/5, 1/5, 1/5, 1/5), (1/5, 1/5, 1/5, 1/5, 1/5)]] 

 

We can also study games where players aim to minimize their utility. 

Here is the Prisoner's Dilemma (where players are aiming to reduce 

time spent in prison):: 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: prisoners_dilemma.obtain_nash(algorithm='enumeration', maximization=False) 

[[(0, 1), (0, 1)]] 

 

When obtaining Nash equilibrium the following algorithms are 

currently available: 

 

* ``'lp'``: A solver for constant sum 2 player games using linear 

programming. This constructs a 

:mod:`MixedIntegerLinearProgram <sage.numerical.MILP>` using the 

solver which was passed in with ``solver`` to solve the linear 

programming representation of the game. See 

:class:`MixedIntegerLinearProgram` for more on MILP solvers in Sage. 

 

* ``'lrs'``: Reverse search vertex enumeration for 2 player games. This 

algorithm uses the optional 'lrslib' package. To install it, type 

``sage -i lrslib`` in the shell. For more information, see [Av2000]_. 

 

* ``'LCP'``: Linear complementarity program algorithm for 2 player games. 

This algorithm uses the open source game theory package: 

`Gambit <http://gambit.sourceforge.net/>`_ [Gambit]_. At present this is 

the only gambit algorithm available in sage but further development will 

hope to implement more algorithms 

(in particular for games with more than 2 players). To install it, 

type ``sage -i gambit`` in the shell. 

 

* ``'enumeration'``: Support enumeration for 2 player games. This 

algorithm is hard coded in Sage and checks through all potential 

supports of a strategy. Supports of a given size with a conditionally 

dominated strategy are ignored. Note: this is not the preferred 

algorithm. The algorithm implemented is a combination of a basic 

algorithm described in [NN2007]_ and a pruning component described 

in [SLB2008]_. 

 

Below we show how the these algorithms are called:: 

 

sage: matching_pennies.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(1/2, 1/2), (1/2, 1/2)]] 

sage: matching_pennies.obtain_nash(algorithm='LCP') # optional - gambit 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: matching_pennies.obtain_nash(algorithm='lp', solver='PPL') 

[[(1/2, 1/2), (1/2, 1/2)]] 

sage: matching_pennies.obtain_nash(algorithm='lp', solver='gambit') # optional - gambit 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: matching_pennies.obtain_nash(algorithm='enumeration') 

[[(1/2, 1/2), (1/2, 1/2)]] 

 

Note that if no algorithm argument is passed then the default will be 

selected according to the following order (if the corresponding package is 

installed): 

 

1. ``'lp'`` (if the game is constant-sum; uses the solver chosen by Sage) 

2. ``'lrs'`` (requires 'lrslib') 

3. ``'enumeration'`` 

 

Here is a game being constructed using gambit syntax (note that a 

``NormalFormGame`` object acts like a dictionary with pure strategy tuples as 

keys and payoffs as their values):: 

 

sage: f = NormalFormGame() 

sage: f.add_player(2) # Adding first player with 2 strategies 

sage: f.add_player(2) # Adding second player with 2 strategies 

sage: f[0,0][0] = 1 

sage: f[0,0][1] = 3 

sage: f[0,1][0] = 2 

sage: f[0,1][1] = 3 

sage: f[1,0][0] = 3 

sage: f[1,0][1] = 1 

sage: f[1,1][0] = 4 

sage: f[1,1][1] = 4 

sage: f 

Normal Form Game with the following utilities: {(0, 1): [2, 3], (1, 0): [3, 1], (0, 0): [1, 3], (1, 1): [4, 4]} 

 

Once this game is constructed we can view the payoff matrices and solve the 

game:: 

 

sage: f.payoff_matrices() 

( 

[1 2] [3 3] 

[3 4], [1 4] 

) 

sage: f.obtain_nash(algorithm='enumeration') 

[[(0, 1), (0, 1)]] 

 

We can add an extra strategy to the first player:: 

 

sage: f.add_strategy(0) 

sage: f 

Normal Form Game with the following utilities: {(0, 1): [2, 3], (0, 0): [1, 3], (2, 1): [False, False], (2, 0): [False, False], (1, 0): [3, 1], (1, 1): [4, 4]} 

 

If we do this and try and obtain the Nash equilibrium or view the payoff 

matrices(without specifying the utilities), an error is returned:: 

 

sage: f.obtain_nash() 

Traceback (most recent call last): 

... 

ValueError: utilities have not been populated 

sage: f.payoff_matrices() 

Traceback (most recent call last): 

... 

ValueError: utilities have not been populated 

 

Here we populate the missing utilities:: 

 

sage: f[2, 1] = [5, 3] 

sage: f[2, 0] = [2, 1] 

sage: f.payoff_matrices() 

( 

[1 2] [3 3] 

[3 4] [1 4] 

[2 5], [1 3] 

) 

sage: f.obtain_nash() 

[[(0, 0, 1), (0, 1)]] 

 

We can use the same syntax as above to create games with 

more than 2 players:: 

 

sage: threegame = NormalFormGame() 

sage: threegame.add_player(2) # Adding first player with 2 strategies 

sage: threegame.add_player(2) # Adding second player with 2 strategies 

sage: threegame.add_player(2) # Adding third player with 2 strategies 

sage: threegame[0, 0, 0][0] = 3 

sage: threegame[0, 0, 0][1] = 1 

sage: threegame[0, 0, 0][2] = 4 

sage: threegame[0, 0, 1][0] = 1 

sage: threegame[0, 0, 1][1] = 5 

sage: threegame[0, 0, 1][2] = 9 

sage: threegame[0, 1, 0][0] = 2 

sage: threegame[0, 1, 0][1] = 6 

sage: threegame[0, 1, 0][2] = 5 

sage: threegame[0, 1, 1][0] = 3 

sage: threegame[0, 1, 1][1] = 5 

sage: threegame[0, 1, 1][2] = 8 

sage: threegame[1, 0, 0][0] = 9 

sage: threegame[1, 0, 0][1] = 7 

sage: threegame[1, 0, 0][2] = 9 

sage: threegame[1, 0, 1][0] = 3 

sage: threegame[1, 0, 1][1] = 2 

sage: threegame[1, 0, 1][2] = 3 

sage: threegame[1, 1, 0][0] = 8 

sage: threegame[1, 1, 0][1] = 4 

sage: threegame[1, 1, 0][2] = 6 

sage: threegame[1, 1, 1][0] = 2 

sage: threegame[1, 1, 1][1] = 6 

sage: threegame[1, 1, 1][2] = 4 

sage: threegame 

Normal Form Game with the following utilities: {(0, 1, 1): [3, 5, 8], (1, 1, 0): [8, 4, 6], (1, 0, 0): [9, 7, 9], (0, 0, 1): [1, 5, 9], (1, 0, 1): [3, 2, 3], (0, 0, 0): [3, 1, 4], (0, 1, 0): [2, 6, 5], (1, 1, 1): [2, 6, 4]} 

 

The above requires a lot of input that could be simplified if there is 

another data structure with our utilities and/or a structure to the 

utilities. The following example creates a game with a relatively strange 

utility function:: 

 

sage: def utility(strategy_triplet, player): 

....: return sum(strategy_triplet) * player 

sage: threegame = NormalFormGame() 

sage: threegame.add_player(2) # Adding first player with 2 strategies 

sage: threegame.add_player(2) # Adding second player with 2 strategies 

sage: threegame.add_player(2) # Adding third player with 2 strategies 

sage: for i, j, k in [(i, j, k) for i in [0,1] for j in [0,1] for k in [0,1]]: 

....: for p in range(3): 

....: threegame[i, j, k][p] = utility([i, j, k], p) 

sage: threegame 

Normal Form Game with the following utilities: {(0, 1, 1): [0, 2, 4], (1, 1, 0): [0, 2, 4], (1, 0, 0): [0, 1, 2], (0, 0, 1): [0, 1, 2], (1, 0, 1): [0, 2, 4], (0, 0, 0): [0, 0, 0], (0, 1, 0): [0, 1, 2], (1, 1, 1): [0, 3, 6]} 

 

At present no algorithm has been implemented in Sage for games with 

more than 2 players:: 

 

sage: threegame.obtain_nash() 

Traceback (most recent call last): 

... 

NotImplementedError: Nash equilibrium for games with more than 2 players have not been implemented yet. Please see the gambit website (http://gambit.sourceforge.net/) that has a variety of available algorithms 

 

There are however a variety of such algorithms available in gambit, 

further compatibility between Sage and gambit is actively being developed: 

https://github.com/tturocy/gambit/tree/sage_integration. 

 

It can be shown that linear scaling of the payoff matrices conserves the 

equilibrium values:: 

 

sage: A = matrix([[2, 1], [1, 2.5]]) 

sage: B = matrix([[-1, 3], [2, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='enumeration') 

[[(1/5, 4/5), (3/5, 2/5)]] 

sage: g.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(1/5, 4/5), (3/5, 2/5)]] 

sage: A = 2 * A 

sage: g = NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='LCP') # optional - gambit 

[[(0.2, 0.8), (0.6, 0.4)]] 

 

It is also possible to generate a Normal form game from a gambit Game:: 

 

sage: from gambit import Game # optional - gambit 

sage: gambitgame= Game.new_table([2, 2]) # optional - gambit 

sage: gambitgame[int(0), int(0)][int(0)] = int(8) # optional - gambit 

sage: gambitgame[int(0), int(0)][int(1)] = int(8) # optional - gambit 

sage: gambitgame[int(0), int(1)][int(0)] = int(2) # optional - gambit 

sage: gambitgame[int(0), int(1)][int(1)] = int(10) # optional - gambit 

sage: gambitgame[int(1), int(0)][int(0)] = int(10) # optional - gambit 

sage: gambitgame[int(1), int(0)][int(1)] = int(2) # optional - gambit 

sage: gambitgame[int(1), int(1)][int(0)] = int(5) # optional - gambit 

sage: gambitgame[int(1), int(1)][int(1)] = int(5) # optional - gambit 

sage: g = NormalFormGame(gambitgame) # optional - gambit 

sage: g # optional - gambit 

Normal Form Game with the following utilities: {(0, 1): [2.0, 10.0], (1, 0): [10.0, 2.0], (0, 0): [8.0, 8.0], (1, 1): [5.0, 5.0]} 

 

For more information on using Gambit in Sage see: :mod:`Using Gambit in 

Sage<sage.game_theory.gambit_docs>`. This includes how to access Gambit 

directly using the version of iPython shipped with Sage and an explanation 

as to why the ``int`` calls are needed to handle the Sage preparser. 

 

Here is a slightly longer game that would take too long to solve with 

``'enumeration'``. Consider the following: 

 

An airline loses two suitcases belonging to two different travelers. Both 

suitcases happen to be identical and contain identical antiques. An 

airline manager tasked to settle the claims of both travelers explains 

that the airline is liable for a maximum of 10 per suitcase, and in order 

to determine an honest appraised value of the antiques the manager 

separates both travelers so they can't confer, and asks them to write down 

the amount of their value at no less than 2 and no larger than 10. He 

also tells them that if both write down the same number, he will treat 

that number as the true dollar value of both suitcases and reimburse both 

travelers that amount. 

 

However, if one writes down a smaller number than the other, this smaller 

number will be taken as the true dollar value, and both travelers will 

receive that amount along with a bonus/malus: 2 extra will be paid to the 

traveler who wrote down the lower value and a 2 deduction will be taken 

from the person who wrote down the higher amount. The challenge is: what 

strategy should both travelers follow to decide the value they should 

write down? 

 

In the following we create the game (with a max value of 10) and solve it:: 

 

sage: K = 10 # Modifying this value lets us play with games of any size 

sage: A = matrix([[min(i,j) + 2 * sign(j-i) for j in range(K, 1, -1)] 

....: for i in range(K, 1, -1)]) 

sage: B = matrix([[min(i,j) + 2 * sign(i-j) for j in range(K, 1, -1)] 

....: for i in range(K, 1, -1)]) 

sage: g = NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(0, 0, 0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 0, 0, 0, 1)]] 

sage: g.obtain_nash(algorithm='LCP') # optional - gambit 

[[(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0), 

(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)]] 

 

The output is a pair of vectors (as before) showing the Nash equilibrium. 

In particular it here shows that out of the 10 possible strategies both 

players should choose the last. Recall that the above considers a reduced 

version of the game where individuals can claim integer values from 10 

to 2. The equilibrium strategy is thus for both players to state that 

the value of their suitcase is 2. 

 

Several standard Normal Form Games have also been implemented. 

For more information on how to access these, see: 

:mod:`Game Theory Catalog<sage.game_theory.catalog>`. 

Included is information on the situation each Game models. 

For example:: 

 

sage: g = game_theory.normal_form_games.PrisonersDilemma() 

sage: g 

Prisoners dilemma - Normal Form Game with the following utilities: ... 

sage: d = {(0, 1): [-5, 0], (1, 0): [0, -5], 

....: (0, 0): [-2, -2], (1, 1): [-4, -4]} 

sage: g == d 

True 

sage: g.obtain_nash() 

[[(0, 1), (0, 1)]] 

 

We can easily obtain the best response for a player to a given strategy. In 

this example we obtain the best responses for Player 1, when Player 2 uses two 

different strategies:: 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((1/2, 1/2), player=0) 

[0, 1, 2] 

sage: g.best_responses((3/4, 1/4), player=0) 

[0] 

 

Here we do the same for player 2:: 

 

sage: g.best_responses((4/5, 1/5, 0), player=1) 

[0, 1] 

 

We see that for the game `Rock-Paper-Scissors-Lizard-Spock 

<http://www.samkass.com/theories/RPSSL.html>`_ any pure strategy has two best 

responses:: 

 

sage: g = game_theory.normal_form_games.RPSLS() 

sage: A, B = g.payoff_matrices() 

sage: A, B 

( 

[ 0 -1 1 1 -1] [ 0 1 -1 -1 1] 

[ 1 0 -1 -1 1] [-1 0 1 1 -1] 

[-1 1 0 1 -1] [ 1 -1 0 -1 1] 

[-1 1 -1 0 1] [ 1 -1 1 0 -1] 

[ 1 -1 1 -1 0], [-1 1 -1 1 0] 

) 

sage: g.best_responses((1, 0, 0, 0, 0), player=0) 

[1, 4] 

sage: g.best_responses((0, 1, 0, 0, 0), player=0) 

[2, 3] 

sage: g.best_responses((0, 0, 1, 0, 0), player=0) 

[0, 4] 

sage: g.best_responses((0, 0, 0, 1, 0), player=0) 

[0, 2] 

sage: g.best_responses((0, 0, 0, 0, 1), player=0) 

[1, 3] 

sage: g.best_responses((1, 0, 0, 0, 0), player=1) 

[1, 4] 

sage: g.best_responses((0, 1, 0, 0, 0), player=1) 

[2, 3] 

sage: g.best_responses((0, 0, 1, 0, 0), player=1) 

[0, 4] 

sage: g.best_responses((0, 0, 0, 1, 0), player=1) 

[0, 2] 

sage: g.best_responses((0, 0, 0, 0, 1), player=1) 

[1, 3] 

 

Note that degenerate games can cause problems for most algorithms. 

The following example in fact has an infinite quantity of equilibria which 

is evidenced by the various algorithms returning different solutions:: 

 

sage: A = matrix([[3,3],[2,5],[0,6]]) 

sage: B = matrix([[3,3],[2,6],[3,1]]) 

sage: degenerate_game = NormalFormGame([A,B]) 

sage: degenerate_game.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(0, 1/3, 2/3), (1/3, 2/3)], [(1, 0, 0), (1/2, 3)], [(1, 0, 0), (1, 3)]] 

sage: degenerate_game.obtain_nash(algorithm='LCP') # optional - gambit 

[[(0.0, 0.3333333333, 0.6666666667), (0.3333333333, 0.6666666667)], 

[(1.0, -0.0, 0.0), (0.6666666667, 0.3333333333)], 

[(1.0, 0.0, 0.0), (1.0, 0.0)]] 

sage: degenerate_game.obtain_nash(algorithm='enumeration') 

[[(0, 1/3, 2/3), (1/3, 2/3)], [(1, 0, 0), (1, 0)]] 

 

We can check the cause of this by using ``is_degenerate()``:: 

 

sage: degenerate_game.is_degenerate() 

True 

 

Note the 'negative' `-0.0` output by gambit. This is due to the numerical 

nature of the algorithm used. 

 

Here is an example with the trivial game where all payoffs are 0:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(3) # Adding first player with 3 strategies 

sage: g.add_player(3) # Adding second player with 3 strategies 

sage: for key in g: 

....: g[key] = [0, 0] 

sage: g.payoff_matrices() 

( 

[0 0 0] [0 0 0] 

[0 0 0] [0 0 0] 

[0 0 0], [0 0 0] 

) 

sage: g.obtain_nash(algorithm='enumeration') 

[[(0, 0, 1), (0, 0, 1)], [(0, 0, 1), (0, 1, 0)], [(0, 0, 1), (1, 0, 0)], 

[(0, 1, 0), (0, 0, 1)], [(0, 1, 0), (0, 1, 0)], [(0, 1, 0), (1, 0, 0)], 

[(1, 0, 0), (0, 0, 1)], [(1, 0, 0), (0, 1, 0)], [(1, 0, 0), (1, 0, 0)]] 

 

A good description of degenerate games can be found in [NN2007]_. 

 

REFERENCES: 

 

- [Nas1950]_ 

 

- [NN2007]_ 

 

- [Av2000]_ 

 

- [Gambit]_ 

 

- [SLB2008]_ 

 

AUTHOR: 

 

- James Campbell and Vince Knight (06-2014): Original version 

- Tobenna P. Igwe: Constant-sum game solvers 

 

""" 

 

#***************************************************************************** 

# Copyright (C) 2014 James Campbell james.campbell@tanti.org.uk 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import print_function 

from __future__ import absolute_import 

 

from collections import MutableMapping 

from itertools import product 

from .parser import Parser 

from sage.misc.latex import latex 

from sage.misc.misc import powerset 

from sage.rings.all import QQ 

from sage.structure.sage_object import SageObject 

from sage.matrix.constructor import matrix 

from sage.matrix.constructor import vector 

from sage.misc.package import is_package_installed, PackageNotFoundError 

from sage.misc.temporary_file import tmp_filename 

from sage.numerical.mip import MixedIntegerLinearProgram 

 

try: 

from gambit import Game 

from gambit.nash import ExternalLPSolver, ExternalLCPSolver 

except ImportError: 

Game = None 

ExternalLPSolver = None 

ExternalLCPSolver = None 

 

 

class NormalFormGame(SageObject, MutableMapping): 

r""" 

An object representing a Normal Form Game. Primarily used to compute the 

Nash Equilibria. 

 

INPUT: 

 

- ``generator`` -- can be a list of 2 matrices, a single matrix or left 

blank 

 

""" 

 

def __init__(self, generator=None): 

r""" 

Initializes a Normal Form game and checks the inputs. 

 

EXAMPLES: 

 

Can have games with more than 2 players:: 

 

sage: threegame = NormalFormGame() 

sage: threegame.add_player(2) # Adding first player with 2 strategies 

sage: threegame.add_player(2) # Adding second player with 2 strategies 

sage: threegame.add_player(2) # Adding third player with 2 strategies 

sage: threegame[0, 0, 0][0] = 3 

sage: threegame[0, 0, 0][1] = 1 

sage: threegame[0, 0, 0][2] = 4 

sage: threegame[0, 0, 1][0] = 1 

sage: threegame[0, 0, 1][1] = 5 

sage: threegame[0, 0, 1][2] = 9 

sage: threegame[0, 1, 0][0] = 2 

sage: threegame[0, 1, 0][1] = 6 

sage: threegame[0, 1, 0][2] = 5 

sage: threegame[0, 1, 1][0] = 3 

sage: threegame[0, 1, 1][1] = 5 

sage: threegame[0, 1, 1][2] = 8 

sage: threegame[1, 0, 0][0] = 9 

sage: threegame[1, 0, 0][1] = 7 

sage: threegame[1, 0, 0][2] = 9 

sage: threegame[1, 0, 1][0] = 3 

sage: threegame[1, 0, 1][1] = 2 

sage: threegame[1, 0, 1][2] = 3 

sage: threegame[1, 1, 0][0] = 8 

sage: threegame[1, 1, 0][1] = 4 

sage: threegame[1, 1, 0][2] = 6 

sage: threegame[1, 1, 1][0] = 2 

sage: threegame[1, 1, 1][1] = 6 

sage: threegame[1, 1, 1][2] = 4 

sage: threegame.obtain_nash() 

Traceback (most recent call last): 

... 

NotImplementedError: Nash equilibrium for games with more than 2 players have not been implemented yet. Please see the gambit website (http://gambit.sourceforge.net/) that has a variety of available algorithms 

 

Can initialise a game from a gambit game object:: 

 

sage: from gambit import Game # optional - gambit 

sage: gambitgame= Game.new_table([2, 2]) # optional - gambit 

sage: gambitgame[int(0), int(0)][int(0)] = int(5) # optional - gambit 

sage: gambitgame[int(0), int(0)][int(1)] = int(8) # optional - gambit 

sage: gambitgame[int(0), int(1)][int(0)] = int(2) # optional - gambit 

sage: gambitgame[int(0), int(1)][int(1)] = int(11) # optional - gambit 

sage: gambitgame[int(1), int(0)][int(0)] = int(10) # optional - gambit 

sage: gambitgame[int(1), int(0)][int(1)] = int(7) # optional - gambit 

sage: gambitgame[int(1), int(1)][int(0)] = int(5) # optional - gambit 

sage: gambitgame[int(1), int(1)][int(1)] = int(5) # optional - gambit 

sage: g = NormalFormGame(gambitgame) # optional - gambit 

sage: g # optional - gambit 

Normal Form Game with the following utilities: {(0, 1): [2.0, 11.0], (1, 0): [10.0, 7.0], (0, 0): [5.0, 8.0], (1, 1): [5.0, 5.0]} 

 

TESTS: 

 

Raise error if matrices aren't the same size:: 

 

sage: p1 = matrix([[1, 2], [3, 4]]) 

sage: p2 = matrix([[3, 3], [1, 4], [6, 6]]) 

sage: error = NormalFormGame([p1, p2]) 

Traceback (most recent call last): 

... 

ValueError: matrices must be the same size 

 

Note that when initializing, a single argument must be passed:: 

 

sage: p1 = matrix([[1, 2], [3, 4]]) 

sage: p2 = matrix([[3, 3], [1, 4], [6, 6]]) 

sage: error = NormalFormGame(p1, p2) 

Traceback (most recent call last): 

... 

TypeError: __init__() takes at most 2 arguments (3 given) 

 

When initiating, argument passed must be a list or nothing:: 

 

sage: error = NormalFormGame({4:6, 6:9}) 

Traceback (most recent call last): 

... 

TypeError: Generator function must be a list, gambit game or nothing 

 

When passing nothing, the utilities then need to be entered manually:: 

 

sage: game = NormalFormGame() 

sage: game 

Normal Form Game with the following utilities: {} 

 

""" 

self.players = [] 

self.utilities = {} 

matrices = [] 

if generator is not None: 

if type(generator) is not list and type(generator) is not Game: 

raise TypeError("Generator function must be a list, gambit game or nothing") 

 

if type(generator) is list: 

if len(generator) == 1: 

generator.append(-generator[-1]) 

matrices = generator 

if matrices[0].dimensions() != matrices[1].dimensions(): 

raise ValueError("matrices must be the same size") 

self._two_matrix_game(matrices) 

elif type(generator) is Game: 

game = generator 

self._gambit_game(game) 

 

def __delitem__(self, key): 

r""" 

This method is one of a collection that aims to make a game 

instance behave like a dictionary which can be used if a game 

is to be generated without using a matrix. 

 

Here we set up deleting an element of the utilities dictionary:: 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: prisoners_dilemma 

Normal Form Game with the following utilities: {(0, 1): [5, 0], (1, 0): [0, 5], (0, 0): [2, 2], (1, 1): [4, 4]} 

sage: del(prisoners_dilemma[(0,1)]) 

sage: prisoners_dilemma 

Normal Form Game with the following utilities: {(1, 0): [0, 5], (0, 0): [2, 2], (1, 1): [4, 4]} 

""" 

self.utilities.pop(key, None) 

 

def __getitem__(self, key): 

r""" 

This method is one of a collection that aims to make a game 

instance behave like a dictionary which can be used if a game 

is to be generated without using a matrix. 

 

Here we allow for querying a key:: 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: prisoners_dilemma[(0, 1)] 

[5, 0] 

sage: del(prisoners_dilemma[(0,1)]) 

sage: prisoners_dilemma[(0, 1)] 

Traceback (most recent call last): 

... 

KeyError: (0, 1) 

""" 

 

return self.utilities[key] 

 

def __iter__(self): 

r""" 

This method is one of a collection that aims to make a game 

instance behave like a dictionary which can be used if a game 

is to be generated without using a matrix. 

 

Here we allow for iteration over the game to correspond to 

iteration over keys of the utility dictionary:: 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: for key in prisoners_dilemma: 

....: print("The strategy pair {} gives utilities {}".format(key, prisoners_dilemma[key])) 

The strategy pair (0, 1) gives utilities [5, 0] 

The strategy pair (1, 0) gives utilities [0, 5] 

The strategy pair (0, 0) gives utilities [2, 2] 

The strategy pair (1, 1) gives utilities [4, 4] 

""" 

return iter(self.utilities) 

 

def __setitem__(self, key, value): 

r""" 

This method is one of a collection that aims to make a game 

instance behave like a dictionary which can be used if a game 

is to be generated without using a matrix. 

 

Here we set up setting the value of a key:: 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: del(prisoners_dilemma[(0,1)]) 

sage: prisoners_dilemma[(0,1)] = [5,6] 

sage: prisoners_dilemma.payoff_matrices() 

( 

[2 5] [2 6] 

[0 4], [5 4] 

) 

 

We can use the dictionary-like interface to overwrite a strategy 

profile:: 

 

sage: prisoners_dilemma[(0,1)] = [-3,-30] 

sage: prisoners_dilemma.payoff_matrices() 

( 

[ 2 -3] [ 2 -30] 

[ 0 4], [ 5 4] 

) 

""" 

self.utilities[key] = value 

 

def __len__(self): 

r""" 

Return the length of the game to be the length of the utilities. 

 

EXAMPLES:: 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: len(prisoners_dilemma) 

4 

""" 

return len(self.utilities) 

 

def _repr_(self): 

r""" 

Return the strategy_profiles of the game. 

 

EXAMPLES: 

 

Basic description of the game shown when calling the game instance:: 

 

sage: p1 = matrix([[1, 2], [3, 4]]) 

sage: p2 = matrix([[3, 3], [1, 4]]) 

sage: g = NormalFormGame([p1, p2]) 

sage: g 

Normal Form Game with the following utilities: {(0, 1): [2, 3], (1, 0): [3, 1], (0, 0): [1, 3], (1, 1): [4, 4]} 

""" 

base_str = "Normal Form Game with the following utilities: {}" 

return base_str.format(self.utilities) 

 

def _latex_(self): 

r""" 

Return the LaTeX code representing the ``NormalFormGame``. 

 

EXAMPLES: 

 

LaTeX method shows the two payoff matrices for a two player game:: 

 

sage: A = matrix([[-1, -2], [-12, 2]]) 

sage: B = matrix([[1, 0], [1, -1]]) 

sage: g = NormalFormGame([A, B]) 

sage: latex(g) 

\left(\left(\begin{array}{rr} 

-1 & -2 \\ 

-12 & 2 

\end{array}\right), \left(\begin{array}{rr} 

1 & 0 \\ 

1 & -1 

\end{array}\right)\right) 

 

LaTeX method shows nothing interesting for games with more players:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(2) # Adding first player with 2 strategies 

sage: g.add_player(2) # Adding second player with 2 strategies 

sage: g.add_player(2) # Creating a game with three players 

sage: latex(g) 

\text{\texttt{Normal{ }Form{ }Game{ }...[False,{ }False,{ }False]{\char`\}}}} 

""" 

if len(self.players) == 2: 

M1, M2 = self.payoff_matrices() 

return "\left(%s, %s\\right)" % (M1._latex_(), M2._latex_()) 

return latex(str(self)) 

 

def _two_matrix_game(self, matrices): 

r""" 

Populate ``self.utilities`` with the values from 2 matrices. 

 

EXAMPLES: 

 

A small example game:: 

 

sage: A = matrix([[1, 0], [-2, 3]]) 

sage: B = matrix([[3, 2], [-1, 0]]) 

sage: two_game = NormalFormGame() 

sage: two_game._two_matrix_game([A, B]) 

""" 

self.players = [] 

self.utilities = {} 

self.add_player(matrices[0].dimensions()[0]) 

self.add_player(matrices[1].dimensions()[1]) 

for strategy_profile in self.utilities: 

self.utilities[strategy_profile] = [matrices[0][strategy_profile], 

matrices[1][strategy_profile]] 

 

def _gambit_game(self, game): 

r""" 

Creates a ``NormalFormGame`` object from a Gambit game. 

 

TESTS:: 

 

sage: from gambit import Game # optional - gambit 

sage: testgame = Game.new_table([2, 2]) # optional - gambit 

sage: testgame[int(0), int(0)][int(0)] = int(8) # optional - gambit 

sage: testgame[int(0), int(0)][int(1)] = int(8) # optional - gambit 

sage: testgame[int(0), int(1)][int(0)] = int(2) # optional - gambit 

sage: testgame[int(0), int(1)][int(1)] = int(10) # optional - gambit 

sage: testgame[int(1), int(0)][int(0)] = int(10) # optional - gambit 

sage: testgame[int(1), int(0)][int(1)] = int(2) # optional - gambit 

sage: testgame[int(1), int(1)][int(0)] = int(5) # optional - gambit 

sage: testgame[int(1), int(1)][int(1)] = int(5) # optional - gambit 

sage: g = NormalFormGame() # optional - gambit 

sage: g._gambit_game(testgame) # optional - gambit 

sage: g # optional - gambit 

Normal Form Game with the following utilities: 

{(0, 1): [2.0, 10.0], (1, 0): [10.0, 2.0], 

(0, 0): [8.0, 8.0], (1, 1): [5.0, 5.0]} 

""" 

self.players = [] 

self.utilities = {} 

for player in game.players: 

num_strategies = len(player.strategies) 

self.add_player(num_strategies) 

for strategy_profile in self.utilities: 

utility_vector = [float(game[strategy_profile][i]) for i in range(len(self.players))] 

self.utilities[strategy_profile] = utility_vector 

 

def _gambit_(self, as_integer=False, maximization=True): 

r""" 

Creates a Gambit game from a ``NormalFormGame`` object 

 

INPUT: 

 

- ``as_integer`` -- boolean; whether the gambit representation 

should have the payoffs represented as integers or decimals 

 

- ``maximization`` -- boolean; whether a player is trying to 

maximize their utility or minimize it 

 

TESTS:: 

 

sage: from gambit import Game # optional - gambit 

sage: A = matrix([[2, 1], [1, 2.5]]) 

sage: g = NormalFormGame([A]) 

sage: gg = g._gambit_() # optional - gambit 

sage: gg # optional - gambit 

NFG 1 R "" { "1" "2" } 

<BLANKLINE> 

{ { "1" "2" } 

{ "1" "2" } 

} 

"" 

<BLANKLINE> 

{ 

{ "" 2, -2 } 

{ "" 1, -1 } 

{ "" 1, -1 } 

{ "" 2.5, -2.5 } 

} 

1 2 3 4 

<BLANKLINE> 

 

sage: gg = g._gambit_(as_integer=True) # optional - gambit 

sage: gg # optional - gambit 

NFG 1 R "" { "1" "2" } 

<BLANKLINE> 

{ { "1" "2" } 

{ "1" "2" } 

} 

"" 

<BLANKLINE> 

{ 

{ "" 2, -2 } 

{ "" 1, -1 } 

{ "" 1, -1 } 

{ "" 2, -2 } 

} 

1 2 3 4 

<BLANKLINE> 

 

:: 

 

sage: A = matrix([[2, 1], [1, 2.5]]) 

sage: B = matrix([[3, 2], [5.5, 4]]) 

sage: g = NormalFormGame([A, B]) 

sage: gg = g._gambit_() # optional - gambit 

sage: gg # optional - gambit 

NFG 1 R "" { "1" "2" } 

<BLANKLINE> 

{ { "1" "2" } 

{ "1" "2" } 

} 

"" 

<BLANKLINE> 

{ 

{ "" 2, 3 } 

{ "" 1, 5.5 } 

{ "" 1, 2 } 

{ "" 2.5, 4 } 

} 

1 2 3 4 

<BLANKLINE> 

 

sage: gg = g._gambit_(as_integer = True) # optional - gambit 

sage: gg # optional - gambit 

NFG 1 R "" { "1" "2" } 

<BLANKLINE> 

{ { "1" "2" } 

{ "1" "2" } 

} 

"" 

<BLANKLINE> 

{ 

{ "" 2, 3 } 

{ "" 1, 5 } 

{ "" 1, 2 } 

{ "" 2, 4 } 

} 

1 2 3 4 

<BLANKLINE> 

 

:: 

 

sage: threegame = NormalFormGame() # optional - gambit 

sage: threegame.add_player(2) # optional - gambit 

sage: threegame.add_player(2) # optional - gambit 

sage: threegame.add_player(2) # optional - gambit 

sage: threegame[0, 0, 0][0] = 3 # optional - gambit 

sage: threegame[0, 0, 0][1] = 1 # optional - gambit 

sage: threegame[0, 0, 0][2] = 4 # optional - gambit 

sage: threegame[0, 0, 1][0] = 1 # optional - gambit 

sage: threegame[0, 0, 1][1] = 5 # optional - gambit 

sage: threegame[0, 0, 1][2] = 9 # optional - gambit 

sage: threegame[0, 1, 0][0] = 2 # optional - gambit 

sage: threegame[0, 1, 0][1] = 6 # optional - gambit 

sage: threegame[0, 1, 0][2] = 5 # optional - gambit 

sage: threegame[0, 1, 1][0] = 3 # optional - gambit 

sage: threegame[0, 1, 1][1] = 5 # optional - gambit 

sage: threegame[0, 1, 1][2] = 8 # optional - gambit 

sage: threegame[1, 0, 0][0] = 9 # optional - gambit 

sage: threegame[1, 0, 0][1] = 7 # optional - gambit 

sage: threegame[1, 0, 0][2] = 9 # optional - gambit 

sage: threegame[1, 0, 1][0] = 3 # optional - gambit 

sage: threegame[1, 0, 1][1] = 2 # optional - gambit 

sage: threegame[1, 0, 1][2] = 3 # optional - gambit 

sage: threegame[1, 1, 0][0] = 8 # optional - gambit 

sage: threegame[1, 1, 0][1] = 4 # optional - gambit 

sage: threegame[1, 1, 0][2] = 6 # optional - gambit 

sage: threegame[1, 1, 1][0] = 2 # optional - gambit 

sage: threegame[1, 1, 1][1] = 6 # optional - gambit 

sage: threegame[1, 1, 1][2] = 4 # optional - gambit 

sage: threegame._gambit_(as_integer = True) # optional - gambit 

NFG 1 R "" { "1" "2" "3" } 

<BLANKLINE> 

{ { "1" "2" } 

{ "1" "2" } 

{ "1" "2" } 

} 

"" 

<BLANKLINE> 

{ 

{ "" 3, 1, 4 } 

{ "" 9, 7, 9 } 

{ "" 2, 6, 5 } 

{ "" 8, 4, 6 } 

{ "" 1, 5, 9 } 

{ "" 3, 2, 3 } 

{ "" 3, 5, 8 } 

{ "" 2, 6, 4 } 

} 

1 2 3 4 5 6 7 8  

<BLANKLINE> 

""" 

from decimal import Decimal 

strategy_sizes = [p.num_strategies for p in self.players] 

g = Game.new_table(strategy_sizes) 

 

sgn = 1 

if not maximization: 

sgn = -1 

 

players = len(strategy_sizes) 

 

for strategy_profile in self.utilities: 

for i in range(players): 

if as_integer: 

g[strategy_profile][i] = sgn * int(self.utilities[strategy_profile][i]) 

else: 

g[strategy_profile][i] = sgn * Decimal(float(self.utilities[strategy_profile][i])) 

return g 

 

def is_constant_sum(self): 

r""" 

Checks if the game is constant sum. 

 

EXAMPLES:: 

 

sage: A = matrix([[2, 1], [1, 2.5]]) 

sage: g = NormalFormGame([A]) 

sage: g.is_constant_sum() 

True 

sage: g = NormalFormGame([A, A]) 

sage: g.is_constant_sum() 

False 

sage: A = matrix([[1, 1], [1, 1]]) 

sage: g = NormalFormGame([A, A]) 

sage: g.is_constant_sum() 

True 

sage: A = matrix([[1, 1, 2], [1, 1, -1], [1, -1, 1]]) 

sage: B = matrix([[2, 2, 1], [2, 2, 4], [2, 4, 2]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.is_constant_sum() 

True 

sage: A = matrix([[1, 1, 2], [1, 1, -1], [1, -1, 1]]) 

sage: B = matrix([[2, 2, 1], [2, 2.1, 4], [2, 4, 2]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.is_constant_sum() 

False 

""" 

import sys 

if len(self.players) > 2: 

return False 

m1, m2 = self.payoff_matrices() 

c = m1 + m2 

t = c[0,0] 

 

for row in c: 

for i in row: 

if abs(t - i) > sys.float_info.epsilon: 

return False 

 

return True 

 

def payoff_matrices(self): 

r""" 

Return 2 matrices representing the payoffs for each player. 

 

EXAMPLES:: 

 

sage: p1 = matrix([[1, 2], [3, 4]]) 

sage: p2 = matrix([[3, 3], [1, 4]]) 

sage: g = NormalFormGame([p1, p2]) 

sage: g.payoff_matrices() 

( 

[1 2] [3 3] 

[3 4], [1 4] 

) 

 

If we create a game with 3 players we will not be able to 

obtain payoff matrices:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(2) # adding first player with 2 strategies 

sage: g.add_player(2) # adding second player with 2 strategies 

sage: g.add_player(2) # adding third player with 2 strategies 

sage: g.payoff_matrices() 

Traceback (most recent call last): 

... 

ValueError: Only available for 2 player games 

 

If we do create a two player game but it is not complete 

then an error is also raised:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(1) # Adding first player with 1 strategy 

sage: g.add_player(1) # Adding second player with 1 strategy 

sage: g.payoff_matrices() 

Traceback (most recent call last): 

... 

ValueError: utilities have not been populated 

 

The above creates a 2 player game where each player has 

a single strategy. Here we populate the strategies and 

can then view the payoff matrices:: 

 

sage: g[0, 0] = [1,2] 

sage: g.payoff_matrices() 

([1], [2]) 

""" 

if len(self.players) != 2: 

raise ValueError("Only available for 2 player games") 

 

if not self._is_complete(): 

raise ValueError("utilities have not been populated") 

 

m1 = matrix(QQ, self.players[0].num_strategies, self.players[1].num_strategies) 

m2 = matrix(QQ, self.players[0].num_strategies, self.players[1].num_strategies) 

for strategy_profile in self.utilities: 

m1[strategy_profile] = self[strategy_profile][0] 

m2[strategy_profile] = self[strategy_profile][1] 

return m1, m2 

 

def add_player(self, num_strategies): 

r""" 

Add a player to a NormalFormGame. 

 

INPUT: 

 

- ``num_strategies`` -- the number of strategies the player should have 

 

EXAMPLES:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(2) # Adding first player with 2 strategies 

sage: g.add_player(1) # Adding second player with 1 strategy 

sage: g.add_player(1) # Adding third player with 1 strategy 

sage: g 

Normal Form Game with the following utilities: {(1, 0, 0): [False, False, False], (0, 0, 0): [False, False, False]} 

""" 

self.players.append(_Player(num_strategies)) 

self._generate_utilities(True) 

 

def _generate_utilities(self, replacement): 

r""" 

Create all the required keys for ``self.utilities``. 

 

This is used when generating players and/or adding strategies. 

 

INPUT: 

 

- ``replacement`` -- Boolean value of whether previously created 

profiles should be replaced or not 

 

TESTS:: 

 

sage: from sage.game_theory.normal_form_game import _Player 

sage: g = NormalFormGame() 

sage: g.players.append(_Player(2)) 

sage: g.players.append(_Player(2)) 

sage: g 

Normal Form Game with the following utilities: {} 

 

sage: g._generate_utilities(True) 

sage: g 

Normal Form Game with the following utilities: 

{(0, 1): [False, False], (1, 0): [False, False], 

(0, 0): [False, False], (1, 1): [False, False]} 

 

sage: g[(0,1)] = [2, 3] 

sage: g.add_strategy(1) 

sage: g._generate_utilities(False) 

sage: g 

Normal Form Game with the following utilities: 

{(0, 1): [2, 3], (1, 2): [False, False], 

(0, 0): [False, False], (0, 2): [False, False], 

(1, 0): [False, False], (1, 1): [False, False]} 

 

sage: g._generate_utilities(True) 

sage: g 

Normal Form Game with the following utilities: 

{(0, 1): [False, False], (1, 2): [False, False], 

(0, 0): [False, False], (1, 1): [False, False], 

(1, 0): [False, False], (0, 2): [False, False]} 

""" 

strategy_sizes = [range(p.num_strategies) for p in self.players] 

if replacement is True: 

self.utilities = {} 

for profile in product(*strategy_sizes): 

if profile not in self.utilities.keys(): 

self.utilities[profile] = [False] * len(self.players) 

 

def add_strategy(self, player): 

r""" 

Add a strategy to a player, will not affect already completed 

strategy profiles. 

 

INPUT: 

 

- ``player`` -- the index of the player 

 

EXAMPLES: 

 

A simple example:: 

 

sage: s = matrix([[1, 0], [-2, 3]]) 

sage: t = matrix([[3, 2], [-1, 0]]) 

sage: example = NormalFormGame([s, t]) 

sage: example 

Normal Form Game with the following utilities: {(0, 1): [0, 2], (1, 0): [-2, -1], (0, 0): [1, 3], (1, 1): [3, 0]} 

sage: example.add_strategy(0) 

sage: example 

Normal Form Game with the following utilities: {(0, 1): [0, 2], (0, 0): [1, 3], (2, 1): [False, False], (2, 0): [False, False], (1, 0): [-2, -1], (1, 1): [3, 0]} 

 

""" 

self.players[player].add_strategy() 

self._generate_utilities(False) 

 

def _is_complete(self): 

r""" 

Check if ``utilities`` has been completed and return a 

boolean. 

 

EXAMPLES: 

 

A simple example:: 

 

sage: s = matrix([[1, 0], [-2, 3]]) 

sage: t = matrix([[3, 2], [-1, 0]]) 

sage: example = NormalFormGame([s, t]) 

sage: example.add_strategy(0) 

sage: example._is_complete() 

False 

""" 

results = [] 

for profile in self.utilities.values(): 

results.append(all(type(i) is not bool for i in profile)) 

return all(results) 

 

def obtain_nash(self, algorithm=False, maximization=True, solver=None): 

r""" 

A function to return the Nash equilibrium for the game. 

Optional arguments can be used to specify the algorithm used. 

If no algorithm is passed then an attempt is made to use the most 

appropriate algorithm. 

 

INPUT: 

 

- ``algorithm`` - the following algorithms should be available through 

this function: 

 

* ``'lrs'`` - This algorithm is only suited for 2 player games. 

See the lrs web site (http://cgm.cs.mcgill.ca/~avis/C/lrs.html). 

 

* ``'LCP'`` - This algorithm is only suited for 2 player games. 

See the gambit web site (http://gambit.sourceforge.net/). 

 

* ``'lp'`` - This algorithm is only suited for 2 player 

constant sum games. Uses MILP solver determined by the 

``solver`` argument. 

 

* ``'enumeration'`` - This is a very inefficient 

algorithm (in essence a brute force approach). 

 

1. For each k in 1...min(size of strategy sets) 

2. For each I,J supports of size k 

3. Prune: check if supports are dominated 

4. Solve indifference conditions and check that have Nash Equilibrium. 

 

Solving the indifference conditions is done by building the 

corresponding linear system. If `\rho_1, \rho_2` are the 

supports player 1 and 2 respectively. Then, indifference implies: 

 

.. MATH:: 

 

u_1(s_1,\rho_2) = u_1(s_2, \rho_2) 

 

for all `s_1, s_2` in the support of `\rho_1`. This corresponds to: 

 

.. MATH:: 

 

\sum_{j\in S(\rho_2)}A_{s_1,j}{\rho_2}_j = \sum_{j\in S(\rho_2)}A_{s_2,j}{\rho_2}_j 

 

for all `s_1, s_2` in the support of `\rho_1` where `A` is the payoff 

matrix of player 1. Equivalently we can consider consecutive rows of 

`A` (instead of all pairs of strategies). Thus the corresponding 

linear system can be written as: 

 

.. MATH:: 

 

\left(\sum_{j \in S(\rho_2)}A_{i,j} - A_{i+1,j}\right){\rho_2}_j 

 

for all `1\leq i \leq |S(\rho_1)|` (where `A` has been modified to only 

contain the rows corresponding to `S(\rho_1)`). We also require all 

elements of `\rho_2` to sum to 1: 

 

.. MATH:: 

 

\sum_{j\in S(\rho_1)}{\rho_2}_j = 1 

 

- ``maximization`` -- (default: ``True``) whether a player is 

trying to maximize their utility or minimize it: 

 

* When set to ``True`` it is assumed that players aim to 

maximise their utility. 

 

* When set to ``False`` it is assumed that players aim to 

minimise their utility. 

 

- ``solver`` -- (optional) see :class:`MixedIntegerLinearProgram` 

for more information on the MILP solvers in Sage, may also 

be ``'gambit'`` to use the MILP solver included with the gambit 

library. Note that ``None`` means to use the default Sage LP solver, 

normally GLPK. 

 

EXAMPLES: 

 

A game with 1 equilibrium when ``maximization`` is ``True`` and 3 when 

``maximization`` is ``False``:: 

 

sage: A = matrix([[10, 500, 44], 

....: [15, 10, 105], 

....: [19, 204, 55], 

....: [20, 200, 590]]) 

sage: B = matrix([[2, 1, 2], 

....: [0, 5, 6], 

....: [3, 4, 1], 

....: [4, 1, 20]]) 

sage: g=NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(0, 0, 0, 1), (0, 0, 1)]] 

sage: g.obtain_nash(algorithm='lrs', maximization=False) # optional - lrslib 

[[(2/3, 1/12, 1/4, 0), (6333/8045, 247/8045, 293/1609)], [(3/4, 0, 1/4, 0), (0, 11/307, 296/307)], [(5/6, 1/6, 0, 0), (98/99, 1/99, 0)]] 

 

This particular game has 3 Nash equilibria:: 

 

sage: A = matrix([[3,3], 

....: [2,5], 

....: [0,6]]) 

sage: B = matrix([[3,2], 

....: [2,6], 

....: [3,1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='enumeration') 

[[(0, 1/3, 2/3), (1/3, 2/3)], [(4/5, 1/5, 0), (2/3, 1/3)], [(1, 0, 0), (1, 0)]] 

 

Here is a slightly larger game:: 

 

sage: A = matrix([[160, 205, 44], 

....: [175, 180, 45], 

....: [201, 204, 50], 

....: [120, 207, 49]]) 

sage: B = matrix([[2, 2, 2], 

....: [1, 0, 0], 

....: [3, 4, 1], 

....: [4, 1, 2]]) 

sage: g=NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='enumeration') 

[[(0, 0, 3/4, 1/4), (1/28, 27/28, 0)]] 

sage: g.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(0, 0, 3/4, 1/4), (1/28, 27/28, 0)]] 

sage: g.obtain_nash(algorithm='LCP') # optional - gambit 

[[(0.0, 0.0, 0.75, 0.25), (0.0357142857, 0.9642857143, 0.0)]] 

 

2 random matrices:: 

 

sage: player1 = matrix([[2, 8, -1, 1, 0], 

....: [1, 1, 2, 1, 80], 

....: [0, 2, 15, 0, -12], 

....: [-2, -2, 1, -20, -1], 

....: [1, -2, -1, -2, 1]]) 

sage: player2 = matrix([[0, 8, 4, 2, -1], 

....: [6, 14, -5, 1, 0], 

....: [0, -2, -1, 8, -1], 

....: [1, -1, 3, -3, 2], 

....: [8, -4, 1, 1, -17]]) 

sage: fivegame = NormalFormGame([player1, player2]) 

sage: fivegame.obtain_nash(algorithm='enumeration') 

[[(1, 0, 0, 0, 0), (0, 1, 0, 0, 0)]] 

sage: fivegame.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(1, 0, 0, 0, 0), (0, 1, 0, 0, 0)]] 

sage: fivegame.obtain_nash(algorithm='LCP') # optional - gambit 

[[(1.0, 0.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0, 0.0)]] 

 

Here are some examples of finding Nash equilibria for constant-sum games:: 

 

sage: A = matrix.identity(2) 

sage: cg = NormalFormGame([A]) 

sage: cg.obtain_nash(algorithm='lp') 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: cg.obtain_nash(algorithm='lp', solver='Coin') # optional - cbc 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: cg.obtain_nash(algorithm='lp', solver='PPL') 

[[(1/2, 1/2), (1/2, 1/2)]] 

sage: cg.obtain_nash(algorithm='lp', solver='gambit') # optional - gambit 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: A = matrix([[2, 1], [1, 3]]) 

sage: cg = NormalFormGame([A]) 

sage: ne = cg.obtain_nash(algorithm='lp', solver='glpk') 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] 

[[[0.666667, 0.333333], [0.666667, 0.333333]]] 

sage: ne = cg.obtain_nash(algorithm='lp', solver='Coin') # optional - cbc 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] # optional - cbc 

[[[0.666667, 0.333333], [0.666667, 0.333333]]] 

sage: cg.obtain_nash(algorithm='lp', solver='PPL') 

[[(2/3, 1/3), (2/3, 1/3)]] 

sage: ne = cg.obtain_nash(algorithm='lp', solver='gambit') # optional - gambit 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] # optional - gambit 

[[[0.666667, 0.333333], [0.666667, 0.333333]]] 

sage: A = matrix([[1, 2, 1], [1, 1, 2], [2, 1, 1]]) 

sage: B = matrix([[2, 1, 2], [2, 2, 1], [1, 2, 2]]) 

sage: cg = NormalFormGame([A, B]) 

sage: ne = cg.obtain_nash(algorithm='lp', solver='glpk') 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] 

[[[0.333333, 0.333333, 0.333333], [0.333333, 0.333333, 0.333333]]] 

sage: ne = cg.obtain_nash(algorithm='lp', solver='Coin') # optional - cbc 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] # optional - cbc 

[[[0.333333, 0.333333, 0.333333], [0.333333, 0.333333, 0.333333]]] 

sage: cg.obtain_nash(algorithm='lp', solver='PPL') 

[[(1/3, 1/3, 1/3), (1/3, 1/3, 1/3)]] 

sage: ne = cg.obtain_nash(algorithm='lp', solver='gambit') # optional - gambit 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] # optional - gambit 

[[[0.333333, 0.333333, 0.333333], [0.333333, 0.333333, 0.333333]]] 

sage: A = matrix([[160, 205, 44], 

....: [175, 180, 45], 

....: [201, 204, 50], 

....: [120, 207, 49]]) 

sage: cg = NormalFormGame([A]) 

sage: cg.obtain_nash(algorithm='lp', solver='PPL') 

[[(0, 0, 1, 0), (0, 0, 1)]] 

 

Running the constant-sum solver on a game which isn't a constant sum game 

generates a ``ValueError``:: 

 

sage: cg = NormalFormGame([A, A]) 

sage: cg.obtain_nash(algorithm='lp', solver='glpk') 

Traceback (most recent call last): 

... 

ValueError: Input game needs to be a two player constant sum game 

 

Here is an example of a 3 by 2 game with 3 Nash equilibrium:: 

 

sage: A = matrix([[3,3], 

....: [2,5], 

....: [0,6]]) 

sage: B = matrix([[3,2], 

....: [2,6], 

....: [3,1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.obtain_nash(algorithm='enumeration') 

[[(0, 1/3, 2/3), (1/3, 2/3)], [(4/5, 1/5, 0), (2/3, 1/3)], [(1, 0, 0), (1, 0)]] 

 

Of the algorithms implemented, only ``'lrs'`` and ``'enumeration'`` 

are guaranteed to find all Nash equilibria in a game. The solver for 

constant sum games only ever finds one Nash equilibrium. Although it 

is possible for the ``'LCP'`` solver to find all Nash equilibria 

in some instances, there are instances where it will not be able to 

find all Nash equilibria.:: 

 

sage: A = matrix(2, 2) 

sage: gg = NormalFormGame([A]) 

sage: gg.obtain_nash(algorithm='enumeration') 

[[(0, 1), (0, 1)], [(0, 1), (1, 0)], [(1, 0), (0, 1)], [(1, 0), (1, 0)]] 

sage: gg.obtain_nash(algorithm='lrs') # optional - lrs 

[[(0, 1), (0, 1)], [(0, 1), (1, 0)], [(1, 0), (0, 1)], [(1, 0), (1, 0)]] 

sage: gg.obtain_nash(algorithm='lp', solver='glpk') 

[[(1.0, 0.0), (1.0, 0.0)]] 

sage: gg.obtain_nash(algorithm='LCP') # optional - gambit 

[[(1.0, 0.0), (1.0, 0.0)]] 

sage: gg.obtain_nash(algorithm='enumeration', maximization=False) 

[[(0, 1), (0, 1)], [(0, 1), (1, 0)], [(1, 0), (0, 1)], [(1, 0), (1, 0)]] 

sage: gg.obtain_nash(algorithm='lrs', maximization=False) # optional - lrs 

[[(0, 1), (0, 1)], [(0, 1), (1, 0)], [(1, 0), (0, 1)], [(1, 0), (1, 0)]] 

sage: gg.obtain_nash(algorithm='lp', solver='glpk', maximization=False) 

[[(1.0, 0.0), (1.0, 0.0)]] 

sage: gg.obtain_nash(algorithm='LCP', maximization=False) # optional - gambit 

[[(1.0, 0.0), (1.0, 0.0)]] 

 

Note that outputs for all algorithms are as lists of lists of 

tuples and the equilibria have been sorted so that all algorithms give 

a comparable output (although ``'LCP'`` returns floats):: 

 

sage: enumeration_eqs = g.obtain_nash(algorithm='enumeration') 

sage: [[type(s) for s in eq] for eq in enumeration_eqs] 

[[<... 'tuple'>, <... 'tuple'>], [<... 'tuple'>, <... 'tuple'>], [<... 'tuple'>, <... 'tuple'>]] 

sage: lrs_eqs = g.obtain_nash(algorithm='lrs') # optional - lrslib 

sage: [[type(s) for s in eq] for eq in lrs_eqs] # optional - lrslib 

[[<... 'tuple'>, <... 'tuple'>], [<... 'tuple'>, <... 'tuple'>], [<... 'tuple'>, <... 'tuple'>]] 

sage: LCP_eqs = g.obtain_nash(algorithm='LCP') # optional - gambit 

sage: [[type(s) for s in eq] for eq in LCP_eqs] # optional - gambit 

[[<... 'tuple'>, <... 'tuple'>], [<... 'tuple'>, <... 'tuple'>], [<... 'tuple'>, <... 'tuple'>]] 

sage: enumeration_eqs == sorted(enumeration_eqs) 

True 

sage: lrs_eqs == sorted(lrs_eqs) # optional - lrslib 

True 

sage: LCP_eqs == sorted(LCP_eqs) # optional - gambit 

True 

sage: lrs_eqs == enumeration_eqs # optional - lrslib 

True 

sage: enumeration_eqs == LCP_eqs # optional - gambit 

False 

sage: [[[round(float(p), 6) for p in str] for str in eq] for eq in enumeration_eqs] == [[[round(float(p), 6) for p in str] for str in eq] for eq in LCP_eqs] # optional - gambit 

True 

 

Also, not specifying a valid solver would lead to an error:: 

 

sage: A = matrix.identity(2) 

sage: g = NormalFormGame([A]) 

sage: g.obtain_nash(algorithm="invalid") 

Traceback (most recent call last): 

... 

ValueError: 'algorithm' should be set to 'enumeration', 'LCP', 'lp' or 'lrs' 

sage: g.obtain_nash(algorithm="lp", solver="invalid") 

Traceback (most recent call last): 

... 

ValueError: 'solver' should be set to 'GLPK', ..., None 

(in which case the default one is used), or a callable. 

""" 

if len(self.players) > 2: 

raise NotImplementedError("Nash equilibrium for games with more " 

"than 2 players have not been " 

"implemented yet. Please see the gambit " 

"website (http://gambit.sourceforge.net/) that has a variety of " 

"available algorithms") 

 

if not self._is_complete(): 

raise ValueError("utilities have not been populated") 

 

if not algorithm: 

if self.is_constant_sum(): 

algorithm = "lp" 

elif is_package_installed('lrslib'): 

algorithm = "lrs" 

else: 

algorithm = "enumeration" 

 

if algorithm == "lrs": 

if not is_package_installed('lrslib'): 

raise PackageNotFoundError("lrslib") 

 

return self._solve_lrs(maximization) 

 

if algorithm == "LCP": 

if Game is None: 

raise PackageNotFoundError("gambit") 

return self._solve_LCP(maximization) 

 

if algorithm.startswith('lp'): 

return self._solve_LP(solver=solver, maximization=maximization) 

 

if algorithm == "enumeration": 

return self._solve_enumeration(maximization) 

 

raise ValueError("'algorithm' should be set to 'enumeration', 'LCP', 'lp' or 'lrs'") 

 

def _solve_lrs(self, maximization=True): 

r""" 

EXAMPLES: 

 

A simple game:: 

 

sage: A = matrix([[1, 2], [3, 4]]) 

sage: B = matrix([[3, 3], [1, 4]]) 

sage: C = NormalFormGame([A, B]) 

sage: C._solve_lrs() # optional - lrslib 

[[(0, 1), (0, 1)]] 

 

2 random matrices:: 

 

sage: p1 = matrix([[-1, 4, 0, 2, 0], 

....: [-17, 246, -5, 1, -2], 

....: [0, 1, 1, -4, -4], 

....: [1, -3, 9, 6, -1], 

....: [2, 53, 0, -5, 0]]) 

sage: p2 = matrix([[0, 1, 1, 3, 1], 

....: [3, 9, 44, -1, -1], 

....: [1, -4, -1, -3, 1], 

....: [1, 0, 0, 0, 0,], 

....: [1, -3, 1, 21, -2]]) 

sage: biggame = NormalFormGame([p1, p2]) 

sage: biggame._solve_lrs() # optional - lrslib 

[[(0, 0, 0, 20/21, 1/21), (11/12, 0, 0, 1/12, 0)]] 

 

Another test:: 

 

sage: p1 = matrix([[-7, -5, 5], 

....: [5, 5, 3], 

....: [1, -6, 1]]) 

sage: p2 = matrix([[-9, 7, 9], 

....: [6, -2, -3], 

....: [-4, 6, -10]]) 

sage: biggame = NormalFormGame([p1, p2]) 

sage: biggame._solve_lrs() # optional - lrslib 

[[(0, 1, 0), (1, 0, 0)], 

[(1/3, 2/3, 0), (0, 1/6, 5/6)], 

[(1/3, 2/3, 0), (1/7, 0, 6/7)], 

[(1, 0, 0), (0, 0, 1)]] 

""" 

from subprocess import PIPE, Popen 

m1, m2 = self.payoff_matrices() 

if maximization is False: 

m1 = - m1 

m2 = - m2 

game1_str, game2_str = self._Hrepresentation(m1, m2) 

 

g1_name = tmp_filename() 

with open(g1_name, 'w') as g1_file: 

g1_file.write(game1_str) 

g2_name = tmp_filename() 

with open(g2_name, 'w') as g2_file: 

g2_file.write(game2_str) 

 

try: 

process = Popen(['lrsnash', g1_name, g2_name], 

stdout=PIPE, 

stderr=PIPE) 

except OSError: 

from sage.misc.package import PackageNotFoundError 

raise PackageNotFoundError("lrslib") 

 

lrs_output = [row for row in process.stdout] 

process.terminate() 

 

nasheq = Parser(lrs_output).format_lrs() 

return sorted(nasheq) 

 

def _solve_LCP(self, maximization): 

r""" 

Solve a :class:`NormalFormGame` using Gambit's LCP algorithm. 

 

EXAMPLES:: 

 

sage: a = matrix([[1, 0], [1, 4]]) 

sage: b = matrix([[2, 3], [2, 4]]) 

sage: c = NormalFormGame([a, b]) 

sage: c._solve_LCP(maximization=True) # optional - gambit 

[[(0.0, 1.0), (0.0, 1.0)]] 

""" 

g = self._gambit_(maximization) 

output = ExternalLCPSolver().solve(g) 

nasheq = Parser(output).format_gambit(g) 

return sorted(nasheq) 

 

def _solve_gambit_LP(self, maximization=True): 

r""" 

Solve a constant sum :class:`NormalFormGame` using Gambit's 

LP implementation. 

 

EXAMPLES:: 

 

sage: A = matrix([[2, 1], [1, 2.5]]) 

sage: g = NormalFormGame([A]) 

sage: g._solve_gambit_LP() # optional - gambit 

[[(0.6, 0.4), (0.6, 0.4)]] 

sage: A = matrix.identity(2) 

sage: g = NormalFormGame([A]) 

sage: g._solve_gambit_LP() # optional - gambit 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: g = NormalFormGame([A,A]) 

sage: g._solve_gambit_LP() # optional - gambit 

Traceback (most recent call last): 

... 

RuntimeError: Method only valid for constant-sum games. 

""" 

if Game is None: 

raise NotImplementedError("gambit is not installed") 

g = self._gambit_(maximization = maximization) 

output = ExternalLPSolver().solve(g) 

nasheq = Parser(output).format_gambit(g) 

return sorted(nasheq) 

 

def _solve_LP(self, solver='glpk', maximization=True): 

r""" 

Solves a constant sum :class:`NormalFormGame` using 

the specified LP solver. 

 

INPUT: 

 

- ``solver`` -- the solver to be used to solve the LP: 

 

* ``'gambit'`` - his uses the solver included within the gambit 

library to create and solve the LP 

 

* for further possible values, see :class:`MixedIntegerLinearProgram` 

 

EXAMPLES:: 

 

sage: A = matrix.identity(2) 

sage: g = NormalFormGame([A]) 

sage: g._solve_LP() 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: g._solve_LP('gambit') # optional - gambit 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: g._solve_LP('Coin') # optional - cbc 

[[(0.5, 0.5), (0.5, 0.5)]] 

sage: g._solve_LP('PPL') 

[[(1/2, 1/2), (1/2, 1/2)]] 

sage: A = matrix([[2, 1], [1, 3]]) 

sage: g = NormalFormGame([A]) 

sage: ne = g._solve_LP() 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] 

[[[0.666667, 0.333333], [0.666667, 0.333333]]] 

sage: ne = g._solve_LP('gambit') # optional - gambit 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] # optional - gambit 

[[[0.666667, 0.333333], [0.666667, 0.333333]]] 

sage: ne = g._solve_LP('Coin') # optional - cbc 

sage: [[[round(el, 6) for el in v] for v in eq] for eq in ne] # optional - cbc 

[[[0.666667, 0.333333], [0.666667, 0.333333]]] 

sage: g._solve_LP('PPL') 

[[(2/3, 1/3), (2/3, 1/3)]] 

 

An exception is raised if the input game is not constant sum:: 

 

sage: A = matrix.identity(2) 

sage: B = A.transpose() 

sage: g = NormalFormGame([A, B]) 

sage: g._solve_LP() 

Traceback (most recent call last): 

... 

ValueError: Input game needs to be a two player constant sum game 

""" 

if not self.is_constant_sum(): 

raise ValueError("Input game needs to be a two player constant sum game") 

if solver == 'gambit': 

return self._solve_gambit_LP(maximization) 

 

sgn = 1 

if not maximization: 

sgn = -1 

 

strategy_sizes = [p.num_strategies for p in self.players] 

 

p = MixedIntegerLinearProgram(maximization=False, solver=solver) 

y = p.new_variable(nonnegative=True) 

v = p.new_variable(nonnegative=False) 

p.add_constraint(sgn * self.payoff_matrices()[0] * y - v[0] <= 0) 

p.add_constraint(matrix([[1] * strategy_sizes[1]]) * y == 1) 

p.set_objective(v[0]) 

p.solve() 

y = tuple(p.get_values(y).values()) 

 

p = MixedIntegerLinearProgram(maximization=False, solver=solver) 

x = p.new_variable(nonnegative=True) 

u = p.new_variable(nonnegative=False) 

p.add_constraint(sgn * -self.payoff_matrices()[0].T * x - u[0] <= 0) 

p.add_constraint(matrix([[1] * strategy_sizes[0]]) * x == 1) 

p.set_objective(u[0]) 

p.solve() 

x = tuple(p.get_values(x).values()) 

return [[x, y]] 

 

def _solve_enumeration(self, maximization=True): 

r""" 

Obtain the Nash equilibria using support enumeration. 

 

Algorithm implemented here is Algorithm 3.4 of [NN2007]_ 

with an aspect of pruning from [SLB2008]_. 

 

1. For each k in 1...min(size of strategy sets) 

2. For each I,J supports of size k 

3. Prune: check if supports are dominated 

4. Solve indifference conditions and check that have Nash Equilibrium. 

 

EXAMPLES: 

 

A Game:: 

 

sage: A = matrix([[160, 205, 44], 

....: [175, 180, 45], 

....: [201, 204, 50], 

....: [120, 207, 49]]) 

sage: B = matrix([[2, 2, 2], 

....: [1, 0, 0], 

....: [3, 4, 1], 

....: [4, 1, 2]]) 

sage: g=NormalFormGame([A, B]) 

sage: g._solve_enumeration() 

[[(0, 0, 3/4, 1/4), (1/28, 27/28, 0)]] 

 

A game with 3 equilibria:: 

 

sage: A = matrix([[3,3], 

....: [2,5], 

....: [0,6]]) 

sage: B = matrix([[3,2], 

....: [2,6], 

....: [3,1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g._solve_enumeration(maximization=False) 

[[(1, 0, 0), (0, 1)]] 

 

A simple example:: 

 

sage: s = matrix([[1, 0], [-2, 3]]) 

sage: t = matrix([[3, 2], [-1, 0]]) 

sage: example = NormalFormGame([s, t]) 

sage: example._solve_enumeration() 

[[(0, 1), (0, 1)], [(1/2, 1/2), (1/2, 1/2)], [(1, 0), (1, 0)]] 

 

Another:: 

 

sage: A = matrix([[0, 1, 7, 1], 

....: [2, 1, 3, 1], 

....: [3, 1, 3, 5], 

....: [6, 4, 2, 7]]) 

sage: B = matrix([[3, 2, 8, 4], 

....: [6, 2, 0, 3], 

....: [1, 3, -1, 1], 

....: [3, 2, 1, 1]]) 

sage: C = NormalFormGame([A, B]) 

sage: C._solve_enumeration() 

[[(0, 0, 0, 1), (1, 0, 0, 0)], [(2/7, 0, 0, 5/7), (5/11, 0, 6/11, 0)], [(1, 0, 0, 0), (0, 0, 1, 0)]] 

 

Again:: 

 

sage: X = matrix([[1, 4, 2], 

....: [4, 0, 3], 

....: [2, 3, 5]]) 

sage: Y = matrix([[3, 9, 2], 

....: [0, 3, 1], 

....: [5, 4, 6]]) 

sage: Z = NormalFormGame([X, Y]) 

sage: Z._solve_enumeration() 

[[(0, 0, 1), (0, 0, 1)], [(2/9, 0, 7/9), (0, 3/4, 1/4)], [(1, 0, 0), (0, 1, 0)]] 

 

TESTS: 

 

Due to the nature of the linear equations solved in this algorithm 

some negative vectors can be returned. Here is a test that ensures 

this doesn't happen (the particular payoff matrices chosen give a 

linear system that would have negative valued vectors as solution):: 

 

sage: a = matrix([[-13, 59], 

....: [27, 86]]) 

sage: b = matrix([[14, 6], 

....: [58, -14]]) 

sage: c = NormalFormGame([a, b]) 

sage: c._solve_enumeration() 

[[(0, 1), (1, 0)]] 

 

Testing against an error in `_is_NE`. Note that 1 equilibrium is 

missing: ``[(2/3, 1/3), (0, 1)]``, however this equilibrium has 

supports of different sizes. This only occurs in degenerate games 

and is not supported in the `enumeration` algorithm:: 

 

sage: N = NormalFormGame([matrix(2,[0,-1,-2,-1]),matrix(2,[1,0,0,2])]) 

sage: N._solve_enumeration() 

[[(0, 1), (0, 1)], [(1, 0), (1, 0)]] 

 

In this instance the `lrs` algorithm is able to find all 

three equilibria:: 

 

sage: N = NormalFormGame([matrix(2,[0,-1,-2,-1]),matrix(2,[1,0,0,2])]) 

sage: N.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(0, 1), (0, 1)], [(2/3, 1/3), (0, 1)], [(1, 0), (1, 0)]] 

 

Here is another:: 

 

sage: N = NormalFormGame([matrix(2,[7,-8,-4,-8,7,0]),matrix(2,[-9,-1,-8,3,2,3])]) 

sage: N._solve_enumeration() 

[[(0, 1), (0, 0, 1)]] 

""" 

 

M1, M2 = self.payoff_matrices() 

if maximization is False: 

M1 = -M1 

M2 = -M2 

 

potential_supports = [[tuple(support) for support in 

powerset(range(player.num_strategies))] 

for player in self.players] 

 

potential_support_pairs = [pair for pair in product(*potential_supports) if len(pair[0]) == len(pair[1])] 

 

equilibria = [] 

for pair in potential_support_pairs: 

# Check if any supports are dominated for row player 

if (self._row_cond_dominance(pair[0], pair[1], M1) 

# Check if any supports are dominated for col player 

and self._row_cond_dominance(pair[1], pair[0], M2.transpose())): 

a = self._solve_indifference(pair[0], pair[1], M2) 

b = self._solve_indifference(pair[1], pair[0], M1.transpose()) 

if a and b and self._is_NE(a, b, pair[0], pair[1], M1, M2): 

equilibria.append([tuple(a), tuple(b)]) 

 

return sorted(equilibria) 

 

def _row_cond_dominance(self, p1_sup, p2_sup, matrix): 

r""" 

Check if any row strategies of a sub matrix defined 

by a given pair of supports are conditionally dominated. 

Return ``False`` if a row is conditionally dominated. 

 

TESTS: 

 

A matrix that depending on the support for the column player 

has a dominated row:: 

 

sage: g = NormalFormGame() 

sage: A = matrix([[1, 1, 5], [2, 2, 0]]) 

sage: g._row_cond_dominance((0, 1), (0, 1), A) 

False 

 

or does not have a dominated row:: 

 

sage: g._row_cond_dominance((0, 1), (0, 2), A) 

True 

""" 

subm = matrix.matrix_from_rows_and_columns(list(p1_sup), list(p2_sup)) 

nbr_rows = subm.nrows() 

nbr_cols = subm.ncols() 

for s in range(nbr_rows): 

strategy = subm.rows()[s] 

for r in range(s, nbr_rows): 

row = subm.rows()[r] 

if strategy != row: 

if all(strategy[i] < row[i] for i in range(nbr_cols)): 

return False 

if all(row[i] < strategy[i] for i in range(nbr_cols)): 

return False 

return True 

 

def _solve_indifference(self, support1, support2, M): 

r""" 

For support1, retrns the strategy with support: support2 that makes the 

column player indifferent for the utilities given by M. 

 

This is done by building the corresponding linear system. 

If `\rho_1, \rho_2` are the supports of player 1 and 2 respectively. 

Then, indifference for player 1 implies: 

 

.. MATH:: 

 

u_1(s_1,\rho_2) = u_1(s_2, \rho_2) 

 

for all `s_1, s_2` in the support of `\rho_1`. This corresponds to: 

 

.. MATH:: 

 

\sum_{j\in S(\rho_2)}A_{s_1,j}{\rho_2}_j = 

\sum_{j\in S(\rho_2)}A_{s_2,j}{\rho_2}_j 

 

for all `s_1, s_2` in the support of `\rho_1` where `A` is the payoff 

matrix of player 1. Equivalently we can consider consecutive rows of 

`A` (instead of all pairs of strategies). Thus the corresponding 

linear system can be written as: 

 

.. MATH:: 

 

\left(\sum_{j \in S(\rho_2)}^{A_{i,j} - A_{i+1,j}\right){\rho_2}_j 

 

for all `1\leq i \leq |S(\rho_1)|` (where `A` has been modified to only 

contain the row corresponding to `S(\rho_1)`). We also require all 

elements of `\rho_2` to sum to 1: 

 

.. MATH:: 

 

\sum_{j\in S(\rho_1)}{\rho_2}_j = 1. 

 

TESTS: 

 

Find the indifference vector for a support pair that has 

no dominated strategies:: 

 

sage: A = matrix([[1, 1, 5], [2, 2, 0]]) 

sage: g = NormalFormGame([A]) 

sage: g._solve_indifference((0, 1), (0, 2), A) 

(1/3, 2/3) 

sage: g._solve_indifference((0, 2), (0, 1), -A.transpose()) 

(5/6, 0, 1/6) 

 

When a support pair has a dominated strategy there is no 

solution to the indifference equation:: 

 

sage: g._solve_indifference((0, 1), (0, 1), -A.transpose()) 

<BLANKLINE> 

 

Particular case of a game with 1 strategy for each for each player:: 

 

sage: A = matrix([[10]]) 

sage: g = NormalFormGame([A]) 

sage: g._solve_indifference((0,), (0,), -A.transpose()) 

(1) 

""" 

linearsystem = matrix(QQ, len(support2) + 1, M.nrows()) 

 

# Build linear system for player 1 

for strategy1 in support1: 

# Checking particular case of supports of pure strategies 

if len(support2) == 1: 

for strategy2 in range(M.ncols()): 

if M[strategy1][support2[0]] < \ 

M[strategy1][strategy2]: 

return False 

else: 

for strategy_pair2 in range(len(support2)): 

# Coefficients of linear system that ensure indifference 

# between two consecutive strategies of the support 

linearsystem[strategy_pair2, strategy1] = \ 

M[strategy1][support2[strategy_pair2]] -\ 

M[strategy1][support2[strategy_pair2 - 1]] 

# Coefficients of linear system that ensure the vector is 

# a probability vector. ie. sum to 1 

linearsystem[-1, strategy1] = 1 

# Create rhs of linear systems 

linearsystem_rhs = vector([0 for i in range(len(support2))] + [1]) 

 

# Solve both linear systems 

try: 

result = linearsystem.solve_right(linearsystem_rhs) 

except ValueError: 

return None 

 

return result 

 

def _is_NE(self, a, b, p1_support, p2_support, M1, M2): 

r""" 

For vectors that obey indifference for a given support pair, 

checks if it corresponds to a Nash equilibria (support is obeyed and 

no negative values, also that no player has incentive to deviate 

out of supports). 

 

TESTS:: 

 

sage: X = matrix([[1, 4, 2], 

....: [4, 0, 3], 

....: [2, 3, 5]]) 

sage: Y = matrix([[3, 9, 2], 

....: [0, 3, 1], 

....: [5, 4, 6]]) 

sage: Z = NormalFormGame([X, Y]) 

sage: Z._is_NE([0, 1/4, 3/4], [3/5, 2/5, 0], (1, 2,), (0, 1,), X, Y) 

False 

 

sage: Z._is_NE([2/9, 0, 7/9], [0, 3/4, 1/4], (0, 2), (1, 2), X, Y) 

True 

 

Checking pure strategies are not forgotten:: 

 

sage: A = matrix(2, [0, -1, -2, -1]) 

sage: B = matrix(2, [1, 0, 0, 2]) 

sage: N = NormalFormGame([A, B]) 

sage: N._is_NE([1, 0], [1, 0], (0,), (0,), A, B) 

True 

sage: N._is_NE([0, 1], [0, 1], (1,), (1,), A, B) 

True 

sage: N._is_NE([1, 0], [0, 1], (0,), (1,), A, B) 

False 

sage: N._is_NE([0, 1], [1, 0], (1,), (0,), A, B) 

False 

 

sage: A = matrix(3, [-7, -5, 5, 5, 5, 3, 1, -6, 1]) 

sage: B = matrix(3, [-9, 7, 9, 6, -2, -3, -4, 6, -10]) 

sage: N = NormalFormGame([A, B]) 

sage: N._is_NE([1, 0, 0], [0, 0, 1], (0,), (2,), A, B) 

True 

sage: N._is_NE([0, 1, 0], [1, 0, 0], (1,), (0,), A, B) 

True 

sage: N._is_NE([0, 1, 0], [0, 1, 0], (1,), (1,), A, B) 

False 

sage: N._is_NE([0, 0, 1], [0, 1, 0], (2,), (1,), A, B) 

False 

sage: N._is_NE([0, 0, 1], [0, 0, 1], (2,), (2,), A, B) 

False 

""" 

# Check that supports are obeyed 

if not(all([a[i] > 0 for i in p1_support]) and 

all([b[j] > 0 for j in p2_support]) and 

all([a[i] == 0 for i in range(len(a)) 

if i not in p1_support]) and 

all([b[j] == 0 for j in range(len(b)) 

if j not in p2_support])): 

return False 

 

# Check that have pair of best responses 

 

p1_payoffs = [sum(v * row[i] for i, v in enumerate(b)) 

for row in M1.rows()] 

p2_payoffs = [sum(v * col[j] for j, v in enumerate(a)) 

for col in M2.columns()] 

 

#if p1_payoffs.index(max(p1_payoffs)) not in p1_support: 

if not any(i in p1_support for i, x in enumerate(p1_payoffs) 

if x == max(p1_payoffs)): 

return False 

if not any(i in p2_support for i, x in enumerate(p2_payoffs) 

if x == max(p2_payoffs)): 

return False 

 

return True 

 

def _Hrepresentation(self, m1, m2): 

r""" 

Create the H-representation strings required to use lrs nash. 

 

EXAMPLES:: 

 

sage: A = matrix([[1, 2], [3, 4]]) 

sage: B = matrix([[3, 3], [1, 4]]) 

sage: C = NormalFormGame([A, B]) 

sage: print(C._Hrepresentation(A, B)[0]) 

H-representation 

linearity 1 5 

begin 

5 4 rational 

0 1 0 0 

0 0 1 0 

0 -3 -1 1 

0 -3 -4 1 

-1 1 1 0 

end 

<BLANKLINE> 

sage: print(C._Hrepresentation(A, B)[1]) 

H-representation 

linearity 1 5 

begin 

5 4 rational 

0 -1 -2 1 

0 -3 -4 1 

0 1 0 0 

0 0 1 0 

-1 1 1 0 

end 

<BLANKLINE> 

 

""" 

from sage.geometry.polyhedron.misc import _to_space_separated_string 

m = self.players[0].num_strategies 

n = self.players[1].num_strategies 

midentity = list(matrix.identity(m)) 

nidentity = list(matrix.identity(n)) 

 

s = 'H-representation\n' 

s += 'linearity 1 ' + str(m + n + 1) + '\n' 

s += 'begin\n' 

s += str(m + n + 1) + ' ' + str(m + 2) + ' rational\n' 

for f in list(midentity): 

s += '0 ' + _to_space_separated_string(f) + ' 0 \n' 

for e in list(m2.transpose()): 

s += '0 ' + _to_space_separated_string(-e) + ' 1 \n' 

s += '-1 ' 

for g in range(m): 

s += '1 ' 

s += '0 \n' 

s += 'end\n' 

 

t = 'H-representation\n' 

t += 'linearity 1 ' + str(m + n + 1) + '\n' 

t += 'begin\n' 

t += str(m + n + 1) + ' ' + str(n + 2) + ' rational\n' 

for e in list(m1): 

t += '0 ' + _to_space_separated_string(-e) + ' 1 \n' 

for f in list(nidentity): 

t += '0 ' + _to_space_separated_string(f) + ' 0 \n' 

t += '-1 ' 

for g in range(n): 

t += '1 ' 

t += '0 \n' 

t += 'end\n' 

return s, t 

 

def is_degenerate(self, certificate=False): 

""" 

A function to check whether the game is degenerate or not. 

Will return a boolean. 

 

A two-player game is called nondegenerate if no mixed strategy of 

support size `k` has more than `k` pure best responses [NN2007]_. In a 

degenerate game, this definition is violated, for example if there 

is a pure strategy that has two pure best responses. 

 

The implementation here transforms the search over mixed strategies to a 

search over supports which is a discrete search. A full explanation of 

this is given in [CK2015]_. This problem is known to be NP-Hard 

[Du2009]_. Another possible implementation is via best response 

polytopes, see :trac:`18958`. 

 

The game Rock-Paper-Scissors is an example of a non-degenerate game,:: 

 

sage: g = game_theory.normal_form_games.RPS() 

sage: g.is_degenerate() 

False 

 

whereas `Rock-Paper-Scissors-Lizard-Spock 

<http://www.samkass.com/theories/RPSSL.html>`_ is degenerate because 

for every pure strategy there are two best responses.:: 

 

sage: g = game_theory.normal_form_games.RPSLS() 

sage: g.is_degenerate() 

True 

 

EXAMPLES: 

 

Here is an example of a degenerate game given in [DGRB2010]_:: 

 

sage: A = matrix([[3, 3], [2, 5], [0, 6]]) 

sage: B = matrix([[3, 3], [2, 6], [3, 1]]) 

sage: degenerate_game = NormalFormGame([A,B]) 

sage: degenerate_game.is_degenerate() 

True 

 

Here is an example of a degenerate game given in [NN2007]_:: 

 

sage: A = matrix([[0, 6], [2, 5], [3, 3]]) 

sage: B = matrix([[1, 0], [0, 2], [4, 4]]) 

sage: d_game = NormalFormGame([A, B]) 

sage: d_game.is_degenerate() 

True 

 

Here are some other examples of degenerate games:: 

 

sage: M = matrix([[2, 1], [1, 1]]) 

sage: N = matrix([[1, 1], [1, 2]]) 

sage: game = NormalFormGame([M, N]) 

sage: game.is_degenerate() 

True 

 

If more information is required, it may be useful to use 

``certificate=True``. This will return a boolean of whether the game is 

degenerate or not, and if True; a tuple containing the strategy where 

degeneracy was found and the player it belongs to. ``0`` is the row 

player and ``1`` is the column player.:: 

 

sage: M = matrix([[2, 1], [1, 1]]) 

sage: N = matrix([[1, 1], [1, 2]]) 

sage: g = NormalFormGame([M, N]) 

sage: test, certificate = g.is_degenerate(certificate=True) 

sage: test, certificate 

(True, ((1, 0), 0)) 

 

Using the output, we see that the opponent has more best responses than 

the size of the support of the strategy in question ``(1, 0)``. (We 

specify the player as ``(player + 1) % 2`` to ensure that we have the 

opponent's index.):: 

 

sage: g.best_responses(certificate[0], (certificate[1] + 1) % 2) 

[0, 1] 

 

Another example with a mixed strategy causing degeneracy.:: 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: test, certificate = g.is_degenerate(certificate=True) 

sage: test, certificate 

(True, ((1/2, 1/2), 1)) 

 

Again, we see that the opponent has more best responses than the size of 

the support of the strategy in question ``(1/2, 1/2)``.:: 

 

sage: g.best_responses(certificate[0], (certificate[1] + 1) % 2) 

[0, 1, 2] 

 

Sometimes, the different algorithms for obtaining nash_equilibria don't 

agree with each other. This can happen when games are degenerate:: 

 

sage: a = matrix([[-75, 18, 45, 33], 

....: [42, -8, -77, -18], 

....: [83, 18, 11, 40], 

....: [-10, -38, 76, -9]]) 

sage: b = matrix([[62, 64, 87, 51], 

....: [-41, -27, -69, 52], 

....: [-17, 25, -97, -82], 

....: [30, 31, -1, 50]]) 

sage: d_game = NormalFormGame([a, b]) 

sage: d_game.obtain_nash(algorithm='lrs') # optional - lrslib 

[[(0, 0, 1, 0), (0, 1, 0, 0)], 

[(17/29, 0, 0, 12/29), (0, 0, 42/73, 31/73)], 

[(122/145, 0, 23/145, 0), (0, 1, 0, 0)]] 

sage: d_game.obtain_nash(algorithm='LCP') # optional - gambit 

[[(0.5862068966, 0.0, 0.0, 0.4137931034), 

(0.0, 0.0, 0.5753424658, 0.4246575342)]] 

sage: d_game.obtain_nash(algorithm='enumeration') 

[[(0, 0, 1, 0), (0, 1, 0, 0)], [(17/29, 0, 0, 12/29), (0, 0, 42/73, 31/73)]] 

sage: d_game.is_degenerate() 

True 

 

TESTS:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(3) # Adding first player with 3 strategies 

sage: g.add_player(3) # Adding second player with 3 strategies 

sage: for key in g: 

....: g[key] = [0, 0] 

sage: g.is_degenerate() 

True 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.is_degenerate() 

True 

 

sage: A = matrix([[1, -1], [-1, 1]]) 

sage: B = matrix([[-1, 1], [1, -1]]) 

sage: matching_pennies = NormalFormGame([A, B]) 

sage: matching_pennies.is_degenerate() 

False 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: prisoners_dilemma.is_degenerate() 

False 

 

sage: g = NormalFormGame() 

sage: g.add_player(2) 

sage: g.add_player(2) 

sage: g.add_player(2) 

sage: g.is_degenerate() 

Traceback (most recent call last): 

... 

NotImplementedError: Tests for Degeneracy is not yet implemented for games with more than two players. 

""" 

if len(self.players) > 2: 

raise NotImplementedError("Tests for Degeneracy is not yet " 

"implemented for games with more than " 

"two players.") 

 

d = self._is_degenerate_pure(certificate) 

if d: 

return d 

 

M1, M2 = self.payoff_matrices() 

potential_supports = [[tuple(support) for support in 

powerset(range(player.num_strategies))] 

for player in self.players] 

 

# filter out all supports that are pure or empty 

potential_supports = [[i for i in k if len(i) > 1] 

for k in potential_supports] 

 

potential_support_pairs = [pair for pair in 

product(*potential_supports) if 

len(pair[0]) != len(pair[1])] 

 

# Sort so that solve small linear systems first 

potential_support_pairs.sort(key=lambda x: sum([len(k) for k in x])) 

 

for pair in potential_support_pairs: 

if len(pair[0]) < len(pair[1]): 

strat = self._solve_indifference(pair[0], pair[1], M2) 

if strat and len(self.best_responses(strat, player=0)) > len(pair[0]): 

if certificate: 

return True, (strat, 0) 

else: 

return True 

elif len(pair[1]) < len(pair[0]): 

strat = self._solve_indifference(pair[1], pair[0], M1.transpose()) 

if strat and len(self.best_responses(strat, player=0)) > len(pair[1]): 

if certificate: 

return True, (strat, 1) 

else: 

return True 

 

if certificate: 

return False, () 

else: 

return False 

 

def best_responses(self, strategy, player): 

""" 

For a given strategy for a player and the index of the opponent, 

computes the payoff for the opponent and returns a list of the indices 

of the best responses. Only implemented for two player games 

 

INPUT: 

 

- ``strategy`` -- a probability distribution vector 

 

- ``player`` -- the index of the opponent, ``0`` for the row player, 

``1`` for the column player. 

 

EXAMPLES:: 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

 

Now we can obtain the best responses for Player 1, when Player 2 uses 

different strategies:: 

 

sage: g.best_responses((1/2, 1/2), player=0) 

[0, 1, 2] 

sage: g.best_responses((3/4, 1/4), player=0) 

[0] 

 

To get the best responses for Player 2 we pass the argument :code:`player=1` 

 

sage: g.best_responses((4/5, 1/5, 0), player=1) 

[0, 1] 

 

sage: A = matrix([[1, 0], [0, 1], [0, 0]]) 

sage: B = matrix([[1, 0], [0, 1], [0.7, 0.8]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((0, 1, 0), player=1) 

[1] 

 

sage: A = matrix([[3,3],[2,5],[0,6]]) 

sage: B = matrix([[3,3],[2,6],[3,1]]) 

sage: degenerate_game = NormalFormGame([A,B]) 

sage: degenerate_game.best_responses((1, 0, 0), player=1) 

[0, 1] 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((1/3, 1/3, 1/3), player=1) 

[1] 

 

Note that this has only been implemented for 2 player games:: 

 

sage: g = NormalFormGame() 

sage: g.add_player(2) # adding first player with 2 strategies 

sage: g.add_player(2) # adding second player with 2 strategies 

sage: g.add_player(2) # adding third player with 2 strategies 

sage: g.best_responses((1/2, 1/2), player=2) 

Traceback (most recent call last): 

... 

ValueError: Only available for 2 player games 

 

If the strategy is not of the correct dimension for the given player 

then an error is returned:: 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((1/2, 1/2), player=1) 

Traceback (most recent call last): 

... 

ValueError: Strategy is not of correct dimension 

 

sage: g.best_responses((1/3, 1/3, 1/3), player=0) 

Traceback (most recent call last): 

... 

ValueError: Strategy is not of correct dimension 

 

If the strategy is not a true probability vector then an error is 

passed: 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((1/3, 1/2, 0), player=1) 

Traceback (most recent call last): 

... 

ValueError: Strategy is not a probability distribution vector 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((3/2, -1/2), player=0) 

Traceback (most recent call last): 

... 

ValueError: Strategy is not a probability distribution vector 

 

If the player specified is not `0` or `1`, an error is raised:: 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g.best_responses((1/2, 1/2), player='Player1') 

Traceback (most recent call last): 

... 

ValueError: Player1 is not an index of the oponent, must be 0 or 1 

""" 

if len(self.players) != 2: 

raise ValueError('Only available for 2 player games') 

 

if player != 0 and player != 1: 

raise ValueError('%s is not an index of the oponent, must be 0 or 1' % player) 

 

strategy = vector(strategy) 

 

if sum(strategy) != 1 or min(strategy) < 0: 

raise ValueError('Strategy is not a probability distribution vector') 

 

if player == 0: 

payoff_matrix = self.payoff_matrices()[0] 

elif player == 1: 

payoff_matrix = self.payoff_matrices()[1].transpose() 

 

if len(strategy) != payoff_matrix.dimensions()[1]: 

raise ValueError('Strategy is not of correct dimension') 

 

payoffs = list(payoff_matrix * strategy) 

indices = [i for i, j in enumerate(payoffs) if j == max(payoffs)] 

 

return indices 

 

def _is_degenerate_pure(self, certificate=False): 

""" 

Checks whether a game is degenerate in pure strategies. 

 

TESTS:: 

 

sage: A = matrix([[3,3],[2,5],[0,6]]) 

sage: B = matrix([[3,3],[2,6],[3,1]]) 

sage: degenerate_game = NormalFormGame([A,B]) 

sage: degenerate_game._is_degenerate_pure() 

True 

 

sage: A = matrix([[1, 0], [0, 1], [0, 0]]) 

sage: B = matrix([[1, 0], [0, 1], [0.7, 0.8]]) 

sage: g = NormalFormGame([A, B]) 

sage: g._is_degenerate_pure() 

False 

 

sage: A = matrix([[2, 5], [0, 4]]) 

sage: B = matrix([[2, 0], [5, 4]]) 

sage: prisoners_dilemma = NormalFormGame([A, B]) 

sage: prisoners_dilemma._is_degenerate_pure() 

False 

 

sage: A = matrix([[0, -1, 1, 1, -1], 

....: [1, 0, -1, -1, 1], 

....: [-1, 1, 0, 1 , -1], 

....: [-1, 1, -1, 0, 1], 

....: [1, -1, 1, -1, 0]]) 

sage: g = NormalFormGame([A]) 

sage: g._is_degenerate_pure() 

True 

 

Whilst this game is not degenerate in pure strategies, it is 

actually degenerate, but only in mixed strategies. 

 

sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]]) 

sage: B = matrix([[4, 3], [2, 6], [3, 1]]) 

sage: g = NormalFormGame([A, B]) 

sage: g._is_degenerate_pure() 

False 

""" 

M1, M2 = self.payoff_matrices() 

for i, row in enumerate(M2.rows()): 

if list(row).count(max(row)) > 1: 

if certificate: 

strat = [0 for k in range(M1.nrows())] 

strat[i] = 1 

return True, (tuple(strat), 0) 

else: 

return True 

 

for j, col in enumerate(M1.columns()): 

if list(col).count(max(col)) > 1: 

if certificate: 

strat = [0 for k in range(M1.ncols())] 

strat[j] = 1 

return True, (tuple(strat), 1) 

else: 

return True 

return False 

 

 

class _Player(): 

def __init__(self, num_strategies): 

r""" 

TESTS:: 

 

sage: from sage.game_theory.normal_form_game import _Player 

sage: p = _Player(5) 

sage: p.num_strategies 

5 

""" 

self.num_strategies = num_strategies 

 

def add_strategy(self): 

r""" 

TESTS:: 

 

sage: from sage.game_theory.normal_form_game import _Player 

sage: p = _Player(5) 

sage: p.add_strategy() 

sage: p.num_strategies 

6 

""" 

self.num_strategies += 1