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

""" 

Matching games. 

 

This module implements a class for matching games (stable marriage problems) 

[DI1989]_. At present the extended Gale-Shapley algorithm is implemented 

which can be used to obtain stable matchings. 

 

AUTHORS: 

 

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

""" 

 

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

# 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 sage.structure.sage_object import SageObject 

from sage.rings.all import ZZ 

from copy import deepcopy 

from sage.graphs.bipartite_graph import BipartiteGraph 

 

 

class MatchingGame(SageObject): 

r""" 

A matching game. 

 

A matching game (also called a stable matching problem) models a situation 

in a population of `N` suitors and `N` reviewers. Suitors and reviewers 

rank their preferences and attempt to find a match. 

 

Formally, a matching game of size `N` is defined by two disjoint sets `S` 

and `R` of size `N`. Associated to each element of `S` and `R` is a 

preference list: 

 

.. MATH:: 

 

f : S \to R^N 

\text{ and } 

g : R \to S^N. 

 

Here is an example of matching game on 4 players: 

 

.. MATH:: 

 

S = \{J, K, L, M\}, \\ 

R = \{A, B, C, D\}. 

 

With preference functions: 

 

.. MATH:: 

 

f(s) = \begin{cases} 

(A, D, C, B) & \text{ if } s=J,\\ 

(A, B, C, D) & \text{ if } s=K,\\ 

(B, D, C, A) & \text{ if } s=L,\\ 

(C, A, B, D) & \text{ if } s=M,\\ 

\end{cases} 

 

g(s) = \begin{cases} 

(L, J, K, M) & \text{ if } s=A,\\ 

(J, M, L, K) & \text{ if } s=B,\\ 

(K, M, L, J) & \text{ if } s=C,\\ 

(M, K, J, L) & \text{ if } s=D.\\ 

\end{cases} 

 

INPUT: 

 

Two potential inputs are accepted (see below to see the effect of each): 

 

- ``reviewer/suitors_preferences`` -- a dictionary containing the 

preferences of all players: 

 

* key - each reviewer/suitors 

* value - a tuple of suitors/reviewers 

 

OR: 

 

- ``integer`` -- an integer simply representing the number of reviewers 

and suitors. 

 

To implement the above game in Sage:: 

 

sage: suitr_pref = {'J': ('A', 'D', 'C', 'B'), 

....: 'K': ('A', 'B', 'C', 'D'), 

....: 'L': ('B', 'D', 'C', 'A'), 

....: 'M': ('C', 'A', 'B', 'D')} 

sage: reviewr_pref = {'A': ('L', 'J', 'K', 'M'), 

....: 'B': ('J', 'M', 'L', 'K'), 

....: 'C': ('K', 'M', 'L', 'J'), 

....: 'D': ('M', 'K', 'J', 'L')} 

sage: m = MatchingGame([suitr_pref, reviewr_pref]) 

sage: m 

A matching game with 4 suitors and 4 reviewers 

sage: m.suitors() 

('K', 'J', 'M', 'L') 

sage: m.reviewers() 

('A', 'C', 'B', 'D') 

 

A matching `M` is any bijection between `S` and `R`. If `s \in S` and 

`r \in R` are matched by `M` we denote: 

 

.. MATH:: 

 

M(s) = r. 

 

On any given matching game, one intends to find a matching that is stable. 

In other words, so that no one individual has an incentive to break their 

current match. 

 

Formally, a stable matching is a matching that has no blocking pairs. 

A blocking pair is any pair `(s, r)` such that `M(s) \neq r` but `s` 

prefers `r` to `M(r)` and `r` prefers `s` to `M^{-1}(r)`. 

 

To obtain the stable matching in Sage we use the ``solve`` method which 

uses the extended Gale-Shapley algorithm [DI1989]_:: 

 

sage: m.solve() 

{'J': 'A', 'K': 'C', 'L': 'D', 'M': 'B'} 

 

Matchings have a natural representations as bipartite graphs:: 

 

sage: plot(m) 

Graphics object consisting of 13 graphics primitives 

 

The above plots the bipartite graph associated with the matching. 

This plot can be accessed directly:: 

 

sage: graph = m.bipartite_graph() 

sage: graph 

Bipartite graph on 8 vertices 

 

It is possible to initiate a matching game without having to name each 

suitor and reviewer:: 

 

sage: n = 8 

sage: big_game = MatchingGame(n) 

sage: big_game.suitors() 

(1, 2, 3, 4, 5, 6, 7, 8) 

sage: big_game.reviewers() 

(-1, -2, -3, -4, -5, -6, -7, -8) 

 

If we attempt to obtain the stable matching for the above game, 

without defining the preference function we obtain an error:: 

 

sage: big_game.solve() 

Traceback (most recent call last): 

... 

ValueError: suitor preferences are not complete 

 

To continue we have to populate the preference dictionary. Here 

is one example where the preferences are simply the corresponding 

element of the permutation group:: 

 

sage: from itertools import permutations 

sage: suitr_preferences = list(permutations([-i-1 for i in range(n)])) 

sage: revr_preferences = list(permutations([i+1 for i in range(n)])) 

sage: for player in range(n): 

....: big_game.suitors()[player].pref = suitr_preferences[player] 

....: big_game.reviewers()[player].pref = revr_preferences[-player] 

sage: big_game.solve() 

{1: -1, 2: -8, 3: -6, 4: -7, 5: -5, 6: -4, 7: -3, 8: -2} 

 

Note that we can also combine the two ways of creating a game. For example 

here is an initial matching game:: 

 

sage: suitrs = {'Romeo': ('Juliet', 'Rosaline'), 

....: 'Mercutio': ('Juliet', 'Rosaline')} 

sage: revwrs = {'Juliet': ('Romeo', 'Mercutio'), 

....: 'Rosaline': ('Mercutio', 'Romeo')} 

sage: g = MatchingGame(suitrs, revwrs) 

 

Let us assume that all of a sudden a new pair of suitors and reviewers is 

added but their names are not known:: 

 

sage: g.add_reviewer() 

sage: g.add_suitor() 

sage: g.reviewers() 

('Rosaline', 'Juliet', -3) 

sage: g.suitors() 

('Mercutio', 'Romeo', 3) 

 

Note that when adding a reviewer or a suitor all preferences are wiped:: 

 

sage: [s.pref for s in g.suitors()] 

[[], [], []] 

sage: [r.pref for r in g.reviewers()] 

[[], [], []] 

 

If we now try to solve the game we will get an error as we have not 

specified the preferences which will need to be updated:: 

 

sage: g.solve() 

Traceback (most recent call last): 

... 

ValueError: suitor preferences are not complete 

 

Here we update the preferences so that the new reviewers and suitors 

don't affect things too much (they prefer each other and are the least 

preferred of the others):: 

 

sage: g.suitors()[0].pref = suitrs['Mercutio'] + (-3,) 

sage: g.suitors()[1].pref = suitrs['Romeo'] + (-3,) 

sage: g.suitors()[2].pref = (-3, 'Juliet', 'Rosaline') 

sage: g.reviewers()[0].pref = revwrs['Rosaline'] + (3,) 

sage: g.reviewers()[1].pref = revwrs['Juliet'] + (3,) 

sage: g.reviewers()[2].pref = (3, 'Romeo', 'Mercutio') 

 

Now the game can be solved:: 

 

sage: D = g.solve() 

sage: D['Mercutio'] 

'Rosaline' 

sage: D['Romeo'] 

'Juliet' 

sage: D[3] 

-3 

 

Note that the above could be equivalently (and more simply) carried out 

by simply updated the original preference dictionaries:: 

 

sage: for key in suitrs: 

....: suitrs[key] = suitrs[key] + (-3,) 

sage: for key in revwrs: 

....: revwrs[key] = revwrs[key] + (3,) 

sage: suitrs[3] = (-3, 'Juliet', 'Rosaline') 

sage: revwrs[-3] = (3, 'Romeo', 'Mercutio') 

sage: g = MatchingGame(suitrs, revwrs) 

sage: D = g.solve() 

sage: D['Mercutio'] 

'Rosaline' 

sage: D['Romeo'] 

'Juliet' 

sage: D[3] 

-3 

 

It can be shown that the Gale-Shapley algorithm will return the stable 

matching that is optimal from the point of view of the suitors and is in 

fact the worst possible matching from the point of view of the reviewers. 

To quickly obtain the matching that is optimal for the reviewers we 

use the ``solve`` method with the ``invert=True`` option:: 

 

sage: left_dict = {'a': ('A', 'B', 'C'), 

....: 'b': ('B', 'C', 'A'), 

....: 'c': ('B', 'A', 'C')} 

sage: right_dict = {'A': ('b', 'c', 'a'), 

....: 'B': ('a', 'c', 'b'), 

....: 'C': ('a', 'b', 'c')} 

sage: quick_game = MatchingGame([left_dict, right_dict]) 

sage: quick_game.solve() 

{'a': 'A', 'b': 'C', 'c': 'B'} 

sage: quick_game.solve(invert=True) 

{'A': 'c', 'B': 'a', 'C': 'b'} 

 

EXAMPLES: 

 

8 player letter game:: 

 

sage: suitr_pref = {'J': ('A', 'D', 'C', 'B'), 

....: 'K': ('A', 'B', 'C', 'D'), 

....: 'L': ('B', 'D', 'C', 'A'), 

....: 'M': ('C', 'A', 'B', 'D')} 

sage: reviewr_pref = {'A': ('L', 'J', 'K', 'M'), 

....: 'B': ('J', 'M', 'L', 'K'), 

....: 'C': ('K', 'M', 'L', 'J'), 

....: 'D': ('M', 'K', 'J', 'L')} 

sage: m = MatchingGame([suitr_pref, reviewr_pref]) 

sage: m._suitors 

['K', 'J', 'M', 'L'] 

sage: m._reviewers 

['A', 'C', 'B', 'D'] 

 

Also works for numbers:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

 

Can create a game from an integer. This gives default set of preference 

functions:: 

 

sage: g = MatchingGame(3) 

sage: g 

A matching game with 3 suitors and 3 reviewers 

 

We have an empty set of preferences for a default named set of 

preferences:: 

 

sage: for s in g.suitors(): 

....: s, s.pref 

(1, []) 

(2, []) 

(3, []) 

sage: for r in g.reviewers(): 

....: r, r.pref 

(-1, []) 

(-2, []) 

(-3, []) 

 

Before trying to solve such a game the algorithm will check if it is 

complete or not:: 

 

sage: g.solve() 

Traceback (most recent call last): 

... 

ValueError: suitor preferences are not complete 

 

To be able to obtain the stable matching we must input the preferences:: 

 

sage: for s in g.suitors(): 

....: s.pref = (-1, -2, -3) 

sage: for r in g.reviewers(): 

....: r.pref = (1, 2, 3) 

sage: g.solve() 

{1: -1, 2: -2, 3: -3} 

""" 

def __init__(self, generator, revr=None): 

r""" 

Initialize a matching game and check the inputs. 

 

TESTS:: 

 

sage: suit = {0: (3, 4), 1: (3, 4)} 

sage: revr = {3: (0, 1), 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: TestSuite(g).run() 

 

sage: g = MatchingGame(3) 

sage: TestSuite(g).run() 

 

sage: g2 = MatchingGame(QQ(3)) 

sage: g == g2 

True 

 

The above shows that the input can be either two dictionaries 

or an integer:: 

 

sage: g = MatchingGame(suit, 3) 

Traceback (most recent call last): 

... 

TypeError: generator must be an integer or a pair of 2 dictionaries 

 

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

Traceback (most recent call last): 

... 

TypeError: generator must be an integer or a pair of 2 dictionaries 

 

sage: g = MatchingGame('1,2,3', 'A,B,C') 

Traceback (most recent call last): 

... 

TypeError: generator must be an integer or a pair of 2 dictionaries 

""" 

self._suitors = [] 

self._reviewers = [] 

if revr is not None: 

generator = [generator, revr] 

 

if generator in ZZ: 

for i in range(generator): 

self.add_suitor() 

self.add_reviewer() 

elif isinstance(generator[0], dict) and isinstance(generator[1], dict): 

for i in generator[0]: 

self.add_suitor(i) 

for k in generator[1]: 

self.add_reviewer(k) 

 

for i in self._suitors: 

i.pref = generator[0][i._name] 

for k in self._reviewers: 

k.pref = generator[1][k._name] 

else: 

raise TypeError("generator must be an integer or a pair of 2 dictionaries") 

 

def _repr_(self): 

r""" 

Return a basic representation of the game stating how many 

players are in the game. 

 

EXAMPLES: 

 

Matching game with 2 reviewers and 2 suitors:: 

 

sage: M = MatchingGame(2) 

sage: M 

A matching game with 2 suitors and 2 reviewers 

""" 

txt = 'A matching game with {} suitors and {} reviewers' 

return txt.format(len(self._suitors), len(self._reviewers)) 

 

def _latex_(self): 

r""" 

Create the LaTeX representation of the dictionaries for suitors 

and reviewers. 

 

EXAMPLES:: 

 

sage: suit = {0: (3, 4), 1: (3, 4)} 

sage: revr = {3: (0, 1), 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: latex(g) 

\text{Suitors:} 

\begin{aligned} 

\\ 0 & \to (3, 4) 

\\ 1 & \to (3, 4) 

\end{aligned} 

\text{Reviewers:} 

\begin{aligned} 

\\ 3 & \to (0, 1) 

\\ 4 & \to (1, 0) 

\end{aligned} 

""" 

output = "\\text{Suitors:}\n\\begin{aligned}" 

for suitor in self._suitors: 

output += "\n\\\\ %s & \\to %s" % (suitor, suitor.pref) 

output += "\n\\end{aligned}\n\\text{Reviewers:}\n\\begin{aligned}" 

for reviewer in self._reviewers: 

output += "\n\\\\ %s & \\to %s" % (reviewer, reviewer.pref) 

return output + "\n\\end{aligned}" 

 

def __eq__(self, other): 

""" 

Check equality. 

 

sage: suit = {0: (3, 4), 1: (3, 4)} 

sage: revr = {3: (0, 1), 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g2 = MatchingGame([suit, revr]) 

sage: g == g2 

True 

 

Here the two sets of suitors have different preferences:: 

 

sage: suit1 = {0: (3, 4), 1: (3, 4)} 

sage: revr1 = {3: (1, 0), 4: (1, 0)} 

sage: g1 = MatchingGame([suit1, revr1]) 

sage: suit2 = {0: (4, 3), 1: (3, 4)} 

sage: revr2 = {3: (1, 0), 4: (1, 0)} 

sage: g2 = MatchingGame([suit2, revr2]) 

sage: g == g2 

False 

 

Here the two sets of reviewers have different preferences:: 

 

sage: suit1 = {0: (3, 4), 1: (3, 4)} 

sage: revr1 = {3: (0, 1), 4: (1, 0)} 

sage: g1 = MatchingGame([suit1, revr1]) 

sage: suit2 = {0: (3, 4), 1: (3, 4)} 

sage: revr2 = {3: (1, 0), 4: (0, 1)} 

sage: g2 = MatchingGame([suit2, revr2]) 

sage: g == g2 

False 

 

Note that if two games are created with players ordered differently 

they can still be equal:: 

 

sage: g1 = MatchingGame(1) 

sage: g1.add_reviewer(-2) 

sage: g1.add_reviewer(-3) 

sage: g1.add_suitor(3) 

sage: g1.add_suitor(2) 

sage: g1.reviewers() 

(-1, -2, -3) 

sage: g1.suitors() 

(1, 3, 2) 

 

sage: g2 = MatchingGame(1) 

sage: g2.add_reviewer(-2) 

sage: g2.add_reviewer(-3) 

sage: g2.add_suitor(2) 

sage: g2.add_suitor(3) 

sage: g2.reviewers() 

(-1, -2, -3) 

sage: g2.suitors() 

(1, 2, 3) 

 

sage: g1 == g2 

True 

""" 

return (isinstance(other, MatchingGame) 

and set(self._suitors) == set(other._suitors) 

and set(self._reviewers) == set(other._reviewers) 

and all(r1.pref == r2.pref for r1, r2 in 

zip(set(self._reviewers), set(other._reviewers))) 

and all(s1.pref == s2.pref for s1, s2 in 

zip(set(self._suitors), set(other._suitors)))) 

 

def __hash__(self): 

""" 

Raise an error because this is mutable. 

 

EXAMPLES:: 

 

sage: hash(MatchingGame(3)) 

Traceback (most recent call last): 

... 

TypeError: unhashable because matching games are mutable 

""" 

raise TypeError("unhashable because matching games are mutable") 

 

def plot(self): 

r""" 

Create the plot representing the stable matching for the game. 

Note that the game must be solved for this to work. 

 

EXAMPLES: 

 

An error is returned if the game is not solved:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: plot(g) 

Traceback (most recent call last): 

... 

ValueError: game has not been solved yet 

 

sage: g.solve() 

{0: 3, 1: 4} 

sage: plot(g) 

Graphics object consisting of 7 graphics primitives 

""" 

pl = self.bipartite_graph() 

return pl.plot() 

 

def bipartite_graph(self): 

r""" 

Construct a ``BipartiteGraph`` Object of the game. 

This method is similar to the plot method. 

Note that the game must be solved for this to work. 

 

EXAMPLES: 

 

An error is returned if the game is not solved:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g.bipartite_graph() 

Traceback (most recent call last): 

... 

ValueError: game has not been solved yet 

 

sage: g.solve() 

{0: 3, 1: 4} 

sage: g.bipartite_graph() 

Bipartite graph on 4 vertices 

""" 

self._is_solved() 

graph = BipartiteGraph(self._sol_dict) 

return graph 

 

def _is_solved(self): 

r""" 

Raise an error if the game has not been solved yet. 

 

EXAMPLES:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_solved() 

Traceback (most recent call last): 

... 

ValueError: game has not been solved yet 

sage: g.solve() 

{0: 3, 1: 4} 

sage: g._is_solved() 

""" 

suitor_check = all(s.partner for s in self._suitors) 

reviewer_check = all(r.partner for r in self._reviewers) 

if not suitor_check or not reviewer_check: 

raise ValueError("game has not been solved yet") 

 

def _is_complete(self): 

r""" 

Raise an error if all players do not have acceptable preferences. 

 

EXAMPLES: 

 

Not enough reviewers:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 1)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: must have the same number of reviewers as suitors 

 

Not enough suitors:: 

 

sage: suit = {0: (3, 4)} 

sage: revr = {1: (0, 2), 

....: 3: (0, 1)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: must have the same number of reviewers as suitors 

 

Suitors preferences are incomplete:: 

 

sage: suit = {0: (3, 8), 

....: 1: (0, 0)} 

sage: revr = {3: (0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: suitor preferences are not complete 

 

Reviewer preferences are incomplete:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 2, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: reviewer preferences are not complete 

 

Suitor preferences have repetitions:: 

 

sage: suit = {0: (3, 4), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: reviewer preferences contain repetitions 

 

Reviewer preferences have repetitions:: 

 

sage: suit = {0: (3, 4, 3), 

....: 1: (3, 4)} 

sage: revr = {3: (0, 1), 

....: 4: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: suitor preferences contain repetitions 

""" 

if len(self._suitors) != len(self._reviewers): 

raise ValueError("must have the same number of reviewers as suitors") 

 

for suitor in self._suitors: 

if set(suitor.pref) != set(self._reviewers): 

raise ValueError("suitor preferences are not complete") 

 

for reviewer in self._reviewers: 

if set(reviewer.pref) != set(self._suitors): 

raise ValueError("reviewer preferences are not complete") 

 

for reviewer in self._reviewers: 

if len(set(reviewer.pref)) < len(reviewer.pref): 

raise ValueError("reviewer preferences contain repetitions") 

 

for suitor in self._suitors: 

if len(set(suitor.pref)) < len(suitor.pref): 

raise ValueError("suitor preferences contain repetitions") 

 

def add_suitor(self, name=None): 

r""" 

Add a suitor to the game. 

 

INPUT: 

 

- ``name`` -- can be a string or a number; if left blank will 

automatically generate an integer 

 

EXAMPLES: 

 

Creating a two player game:: 

 

sage: g = MatchingGame(2) 

sage: g.suitors() 

(1, 2) 

 

Adding a suitor without specifying a name:: 

 

sage: g.add_suitor() 

sage: g.suitors() 

(1, 2, 3) 

 

Adding a suitor while specifying a name:: 

 

sage: g.add_suitor('D') 

sage: g.suitors() 

(1, 2, 3, 'D') 

 

Note that now our game is no longer complete:: 

 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: must have the same number of reviewers as suitors 

 

Note that an error is raised if one tries to add a suitor 

with a name that already exists:: 

 

sage: g.add_suitor('D') 

Traceback (most recent call last): 

... 

ValueError: a suitor with name "D" already exists 

 

If we add a suitor without passing a name then the name 

of the suitor will not use one that is already chosen:: 

 

sage: suit = {0: (-1, -2), 

....: 2: (-2, -1)} 

sage: revr = {-1: (0, 1), 

....: -2: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g.suitors() 

(0, 2) 

 

sage: g.add_suitor() 

sage: g.suitors() 

(0, 2, 3) 

""" 

if name is None: 

name = len(self._suitors) + 1 

while name in self._suitors: 

name += 1 

if any(s._name == name for s in self._suitors): 

raise ValueError('a suitor with name "{}" already exists'.format(name)) 

 

new_suitor = Player(name) 

self._suitors.append(new_suitor) 

for r in self._reviewers: 

r.pref = [] 

 

def add_reviewer(self, name=None): 

r""" 

Add a reviewer to the game. 

 

INPUT: 

 

- ``name`` -- can be a string or number; if left blank will 

automatically generate an integer 

 

EXAMPLES: 

 

Creating a two player game:: 

 

sage: g = MatchingGame(2) 

sage: g.reviewers() 

(-1, -2) 

 

Adding a suitor without specifying a name:: 

 

sage: g.add_reviewer() 

sage: g.reviewers() 

(-1, -2, -3) 

 

Adding a suitor while specifying a name:: 

 

sage: g.add_reviewer(10) 

sage: g.reviewers() 

(-1, -2, -3, 10) 

 

Note that now our game is no longer complete:: 

 

sage: g._is_complete() 

Traceback (most recent call last): 

... 

ValueError: must have the same number of reviewers as suitors 

 

Note that an error is raised if one tries to add a reviewer 

with a name that already exists:: 

 

sage: g.add_reviewer(10) 

Traceback (most recent call last): 

... 

ValueError: a reviewer with name "10" already exists 

 

If we add a reviewer without passing a name then the name 

of the reviewer will not use one that is already chosen:: 

 

sage: suit = {0: (-1, -3), 

....: 1: (-3, -1)} 

sage: revr = {-1: (0, 1), 

....: -3: (1, 0)} 

sage: g = MatchingGame([suit, revr]) 

sage: g.reviewers() 

(-3, -1) 

 

sage: g.add_reviewer() 

sage: g.reviewers() 

(-3, -1, -4) 

""" 

if name is None: 

name = -len(self._reviewers) - 1 

while name in self._reviewers: 

name -= 1 

if any(r._name == name for r in self._reviewers): 

raise ValueError('a reviewer with name "{}" already exists'.format(name)) 

 

new_reviewer = Player(name) 

self._reviewers.append(new_reviewer) 

for s in self._suitors: 

s.pref = [] 

 

def suitors(self): 

""" 

Return the suitors of ``self``. 

 

EXAMPLES:: 

 

sage: g = MatchingGame(2) 

sage: g.suitors() 

(1, 2) 

""" 

return tuple(self._suitors) 

 

def reviewers(self): 

""" 

Return the reviewers of ``self``. 

 

EXAMPLES:: 

 

sage: g = MatchingGame(2) 

sage: g.reviewers() 

(-1, -2) 

""" 

return tuple(self._reviewers) 

 

def solve(self, invert=False): 

r""" 

Compute a stable matching for the game using the Gale-Shapley 

algorithm. 

 

EXAMPLES:: 

 

sage: suitr_pref = {'J': ('A', 'D', 'C', 'B'), 

....: 'K': ('A', 'B', 'C', 'D'), 

....: 'L': ('B', 'C', 'D', 'A'), 

....: 'M': ('C', 'A', 'B', 'D')} 

sage: reviewr_pref = {'A': ('L', 'J', 'K', 'M'), 

....: 'B': ('J', 'M', 'L', 'K'), 

....: 'C': ('M', 'K', 'L', 'J'), 

....: 'D': ('M', 'K', 'J', 'L')} 

sage: m = MatchingGame([suitr_pref, reviewr_pref]) 

sage: m.solve() 

{'J': 'A', 'K': 'D', 'L': 'B', 'M': 'C'} 

 

sage: suitr_pref = {'J': ('A', 'D', 'C', 'B'), 

....: 'K': ('A', 'B', 'C', 'D'), 

....: 'L': ('B', 'C', 'D', 'A'), 

....: 'M': ('C', 'A', 'B', 'D')} 

sage: reviewr_pref = {'A': ('L', 'J', 'K', 'M'), 

....: 'B': ('J', 'M', 'L', 'K'), 

....: 'C': ('M', 'K', 'L', 'J'), 

....: 'D': ('M', 'K', 'J', 'L')} 

sage: m = MatchingGame([suitr_pref, reviewr_pref]) 

sage: m.solve(invert=True) 

{'A': 'L', 'B': 'J', 'C': 'M', 'D': 'K'} 

 

sage: suitr_pref = {1: (-1,)} 

sage: reviewr_pref = {-1: (1,)} 

sage: m = MatchingGame([suitr_pref, reviewr_pref]) 

sage: m.solve() 

{1: -1} 

 

sage: suitr_pref = {} 

sage: reviewr_pref = {} 

sage: m = MatchingGame([suitr_pref, reviewr_pref]) 

sage: m.solve() 

{} 

 

TESTS: 

 

This also works for players who are both a suitor and reviewer:: 

 

sage: suit = {0: (3,4,2), 1: (3,4,2), 2: (2,3,4)} 

sage: revr = {2: (2,0,1), 3: (0,1,2), 4: (1,0,2)} 

sage: g = MatchingGame(suit, revr) 

sage: g.solve() 

{0: 3, 1: 4, 2: 2} 

""" 

self._is_complete() 

 

for s in self._suitors: 

s.partner = None 

for r in self._reviewers: 

r.partner = None 

 

if invert: 

reviewers = deepcopy(self._suitors) 

suitors = deepcopy(self._reviewers) 

else: 

suitors = deepcopy(self._suitors) 

reviewers = deepcopy(self._reviewers) 

 

while any(s.partner is None for s in suitors): 

s = None 

for x in suitors: 

if x.partner is None: 

s = x 

break 

r = next((x for x in reviewers if x == s.pref[0]), None) 

if r.partner is None: 

r.partner = s 

s.partner = r 

elif r.pref.index(s._name) < r.pref.index(r.partner._name): 

r.partner.partner = None 

r.partner = s 

s.partner = r 

else: 

s.pref = s.pref[1:] 

 

if invert: 

suitors, reviewers = reviewers, suitors 

 

for i, j in zip(self._suitors, suitors): 

i.partner = j.partner 

for i, j in zip(self._reviewers, reviewers): 

i.partner = j.partner 

 

self._sol_dict = {} 

for s in self._suitors: 

self._sol_dict[s] = [s.partner] 

for r in self._reviewers: 

self._sol_dict[r] = [r.partner] 

 

if invert: 

return {key: self._sol_dict[key][0] for key in self._reviewers} 

return {key: self._sol_dict[key][0] for key in self._suitors} 

 

 

class Player(object): 

r""" 

A class to act as a data holder for the players used of the 

matching games. 

 

These instances are used when initiating players and to keep track of 

whether or not partners have a preference. 

""" 

def __init__(self, name): 

r""" 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player(10) 

sage: p 

10 

sage: p.pref 

[] 

sage: p.partner is None 

True 

""" 

self._name = name 

self.pref = [] 

self.partner = None 

 

def __hash__(self): 

r""" 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player(10) 

sage: d = {p : (1, 2, 3)} 

sage: d 

{10: (1, 2, 3)} 

""" 

return hash(self._name) 

 

def __repr__(self): 

r""" 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player(10) 

sage: p 

10 

 

sage: p = Player('Karl') 

sage: p 

'Karl' 

""" 

return repr(self._name) 

 

def __eq__(self, other): 

r""" 

 

Tests equality of two players. This only checks the name of the player 

and not their preferences. 

 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player(10) 

sage: q = Player('Karl') 

sage: p == q 

False 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player(10) 

sage: q = Player(10) 

sage: p == q 

True 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player(10) 

sage: q = Player(10) 

sage: p.pref = (1, 2) 

sage: p.pref = (2, 1) 

sage: p == q 

True 

""" 

if isinstance(other, Player): 

return self._name == other._name 

return self._name == other 

 

def __lt__(self, other): 

""" 

Tests less than inequality of two players. Allows for players to be 

sorted on their names. 

 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player('A') 

sage: q = Player('B') 

sage: p < q 

True 

sage: q < p 

False 

 

sage: p = Player(0) 

sage: q = Player(1) 

sage: p < q 

True 

sage: q < p 

False 

""" 

if isinstance(other, Player): 

return self._name < other._name 

return self._name < other 

 

def __gt__(self, other): 

""" 

Tests greater than inequality of two players. Allows for players to be 

sorted on their names. 

 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player('A') 

sage: q = Player('B') 

sage: p > q 

False 

sage: q > p 

True 

 

sage: p = Player(0) 

sage: q = Player(1) 

sage: p > q 

False 

sage: q > p 

True 

""" 

if isinstance(other, Player): 

return self._name > other._name 

return self._name > other 

 

def __ge__(self, other): 

""" 

Tests greater than or equal inequality of two players. Allows for 

players to be sorted on their names. 

 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player('A') 

sage: q = Player('B') 

sage: p >= q 

False 

sage: q >= p 

True 

 

sage: p = Player(0) 

sage: q = Player(1) 

sage: p >= q 

False 

sage: q >= p 

True 

 

sage: p = Player(0) 

sage: q = Player(0) 

sage: p >= q 

True 

 

sage: p = Player('C') 

sage: q = Player('C') 

sage: p >= q 

True 

""" 

if isinstance(other, Player): 

return self._name >= other._name 

return self._name >= other 

 

def __le__(self, other): 

""" 

Tests less than or equal inequality of two players. Allows for 

players to be sorted on their names. 

 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player('A') 

sage: q = Player('B') 

sage: p <= q 

True 

sage: q <= p 

False 

 

sage: p = Player(0) 

sage: q = Player(1) 

sage: p <= q 

True 

sage: q <= p 

False 

 

sage: p = Player(0) 

sage: q = Player(0) 

sage: p <= q 

True 

 

sage: p = Player('C') 

sage: q = Player('C') 

sage: p <= q 

True 

""" 

if isinstance(other, Player): 

return self._name <= other._name 

return self._name <= other 

 

def __ne__(self, other): 

""" 

Tests inequality of two players. Allows for 

players to be sorted on their names. 

 

TESTS:: 

 

sage: from sage.game_theory.matching_game import Player 

sage: p = Player('A') 

sage: q = Player('B') 

sage: p != q 

True 

 

sage: p = Player(0) 

sage: q = Player(1) 

sage: p != q 

True 

 

sage: p = Player(0) 

sage: q = Player(0) 

sage: p != q 

False 

 

sage: p = Player('C') 

sage: q = Player('C') 

sage: p != q 

False 

""" 

if isinstance(other, Player): 

return self._name != other._name 

return self._name != other