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

r""" 

Bipartite graphs 

 

This module implements bipartite graphs. 

 

AUTHORS: 

 

- Robert L. Miller (2008-01-20): initial version 

 

- Ryan W. Hinton (2010-03-04): overrides for adding and deleting vertices 

and edges 

 

TESTS:: 

 

sage: B = graphs.CompleteBipartiteGraph(7, 9) 

sage: loads(dumps(B)) == B 

True 

 

:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(4)) 

sage: B == B.copy() 

True 

sage: type(B.copy()) 

<class 'sage.graphs.bipartite_graph.BipartiteGraph'> 

""" 

 

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

# Copyright (C) 2008 Robert L. Miller <rlmillster@gmail.com> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

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

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

from __future__ import print_function 

from __future__ import absolute_import 

from six import iteritems 

from six.moves import range 

 

from .graph import Graph 

from sage.rings.integer import Integer 

 

class BipartiteGraph(Graph): 

r""" 

Bipartite graph. 

 

INPUT: 

 

- ``data`` -- can be any of the following: 

 

#. Empty or ``None`` (creates an empty graph). 

#. An arbitrary graph. 

#. A reduced adjacency matrix. 

#. A file in alist format. 

#. From a NetworkX bipartite graph. 

 

A reduced adjacency matrix contains only the non-redundant portion of the 

full adjacency matrix for the bipartite graph. Specifically, for zero 

matrices of the appropriate size, for the reduced adjacency matrix ``H``, 

the full adjacency matrix is ``[[0, H'], [H, 0]]``. 

 

The alist file format is described at 

http://www.inference.phy.cam.ac.uk/mackay/codes/alist.html 

 

- ``partition`` -- (default: ``None``) a tuple defining vertices of the left and right 

partition of the graph. Partitions will be determined automatically 

if ``partition``=``None``. 

 

- ``check`` -- (default: ``True``) if ``True``, an invalid input partition 

raises an exception. In the other case offending edges simply won't 

be included. 

 

.. NOTE:: 

 

All remaining arguments are passed to the ``Graph`` constructor 

 

EXAMPLES: 

 

1. No inputs or ``None`` for the input creates an empty graph:: 

 

sage: B = BipartiteGraph() 

sage: type(B) 

<class 'sage.graphs.bipartite_graph.BipartiteGraph'> 

sage: B.order() 

0 

sage: B == BipartiteGraph(None) 

True 

 

2. From a graph: without any more information, finds a bipartition:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(4)) 

sage: B = BipartiteGraph(graphs.CycleGraph(5)) 

Traceback (most recent call last): 

... 

TypeError: Input graph is not bipartite! 

sage: G = Graph({0:[5,6], 1:[4,5], 2:[4,6], 3:[4,5,6]}) 

sage: B = BipartiteGraph(G) 

sage: B == G 

True 

sage: B.left 

{0, 1, 2, 3} 

sage: B.right 

{4, 5, 6} 

sage: B = BipartiteGraph({0:[5,6], 1:[4,5], 2:[4,6], 3:[4,5,6]}) 

sage: B == G 

True 

sage: B.left 

{0, 1, 2, 3} 

sage: B.right 

{4, 5, 6} 

 

You can specify a partition using ``partition`` argument. Note that if such graph 

is not bipartite, then Sage will raise an error. However, if one specifies 

``check=False``, the offending edges are simply deleted (along with 

those vertices not appearing in either list). We also lump creating 

one bipartite graph from another into this category:: 

 

sage: P = graphs.PetersenGraph() 

sage: partition = [list(range(5)), list(range(5,10))] 

sage: B = BipartiteGraph(P, partition) 

Traceback (most recent call last): 

... 

TypeError: Input graph is not bipartite with respect to the given partition! 

 

sage: B = BipartiteGraph(P, partition, check=False) 

sage: B.left 

{0, 1, 2, 3, 4} 

sage: B.show() 

 

:: 

 

sage: G = Graph({0:[5,6], 1:[4,5], 2:[4,6], 3:[4,5,6]}) 

sage: B = BipartiteGraph(G) 

sage: B2 = BipartiteGraph(B) 

sage: B == B2 

True 

sage: B3 = BipartiteGraph(G, [list(range(4)), list(range(4,7))]) 

sage: B3 

Bipartite graph on 7 vertices 

sage: B3 == B2 

True 

 

:: 

 

sage: G = Graph({0:[], 1:[], 2:[]}) 

sage: part = (list(range(2)), [2]) 

sage: B = BipartiteGraph(G, part) 

sage: B2 = BipartiteGraph(B) 

sage: B == B2 

True 

 

4. From a reduced adjacency matrix:: 

 

sage: M = Matrix([(1,1,1,0,0,0,0), (1,0,0,1,1,0,0), 

....: (0,1,0,1,0,1,0), (1,1,0,1,0,0,1)]) 

sage: M 

[1 1 1 0 0 0 0] 

[1 0 0 1 1 0 0] 

[0 1 0 1 0 1 0] 

[1 1 0 1 0 0 1] 

sage: H = BipartiteGraph(M); H 

Bipartite graph on 11 vertices 

sage: H.edges() 

[(0, 7, None), 

(0, 8, None), 

(0, 10, None), 

(1, 7, None), 

(1, 9, None), 

(1, 10, None), 

(2, 7, None), 

(3, 8, None), 

(3, 9, None), 

(3, 10, None), 

(4, 8, None), 

(5, 9, None), 

(6, 10, None)] 

 

:: 

 

sage: M = Matrix([(1, 1, 2, 0, 0), (0, 2, 1, 1, 1), (0, 1, 2, 1, 1)]) 

sage: B = BipartiteGraph(M, multiedges=True, sparse=True) 

sage: B.edges() 

[(0, 5, None), 

(1, 5, None), 

(1, 6, None), 

(1, 6, None), 

(1, 7, None), 

(2, 5, None), 

(2, 5, None), 

(2, 6, None), 

(2, 7, None), 

(2, 7, None), 

(3, 6, None), 

(3, 7, None), 

(4, 6, None), 

(4, 7, None)] 

 

:: 

 

sage: F.<a> = GF(4) 

sage: MS = MatrixSpace(F, 2, 3) 

sage: M = MS.matrix([[0, 1, a+1], [a, 1, 1]]) 

sage: B = BipartiteGraph(M, weighted=True, sparse=True) 

sage: B.edges() 

[(0, 4, a), (1, 3, 1), (1, 4, 1), (2, 3, a + 1), (2, 4, 1)] 

sage: B.weighted() 

True 

 

5. From an alist file:: 

 

sage: file_name = os.path.join(SAGE_TMP, 'deleteme.alist.txt') 

sage: fi = open(file_name, 'w') 

sage: _ = fi.write("7 4 \n 3 4 \n 3 3 1 3 1 1 1 \n 3 3 3 4 \n\ 

1 2 4 \n 1 3 4 \n 1 0 0 \n 2 3 4 \n\ 

2 0 0 \n 3 0 0 \n 4 0 0 \n\ 

1 2 3 0 \n 1 4 5 0 \n 2 4 6 0 \n 1 2 4 7 \n") 

sage: fi.close(); 

sage: B = BipartiteGraph(file_name) 

sage: B == H 

True 

 

6. From a NetworkX bipartite graph:: 

 

sage: import networkx 

sage: G = graphs.OctahedralGraph() 

sage: N = networkx.make_clique_bipartite(G.networkx_graph()) 

sage: B = BipartiteGraph(N) 

 

TESTS: 

 

Make sure we can create a ``BipartiteGraph`` with keywords but no 

positional arguments (:trac:`10958`). 

 

:: 

 

sage: B = BipartiteGraph(multiedges=True) 

sage: B.allows_multiple_edges() 

True 

 

Ensure that we can construct a ``BipartiteGraph`` with isolated vertices 

via the reduced adjacency matrix (:trac:`10356`):: 

 

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

sage: a 

Bipartite graph on 4 vertices 

sage: a.vertices() 

[0, 1, 2, 3] 

sage: g = BipartiteGraph(matrix(4,4,[1]*4+[0]*12)) 

sage: g.vertices() 

[0, 1, 2, 3, 4, 5, 6, 7] 

sage: sorted(g.left.union(g.right)) 

[0, 1, 2, 3, 4, 5, 6, 7] 

 

Make sure that loops are not allowed (:trac:`23275`):: 

 

sage: B = BipartiteGraph(loops=True) 

Traceback (most recent call last): 

... 

ValueError: loops are not allowed in bipartite graphs 

sage: B = BipartiteGraph(loops=None) 

sage: B.allows_loops() 

False 

sage: B.add_edge(0,0) 

Traceback (most recent call last): 

... 

ValueError: cannot add edge from 0 to 0 in graph without loops 

 

""" 

 

def __init__(self, data=None, partition=None, check=True, *args, **kwds): 

""" 

Create a bipartite graph. See documentation ``BipartiteGraph?`` for 

detailed information. 

 

EXAMPLES:: 

 

sage: P = graphs.PetersenGraph() 

sage: partition = [list(range(5)), list(range(5,10))] 

sage: B = BipartiteGraph(P, partition, check=False) 

""" 

if kwds is None: 

kwds = {'loops': False} 

else: 

if 'loops' in kwds and kwds['loops']: 

raise ValueError('loops are not allowed in bipartite graphs') 

kwds['loops'] = False 

 

if data is None: 

if partition is not None and check: 

if partition[0] or partition[1]: 

raise ValueError("Invalid partition.") 

Graph.__init__(self, **kwds) 

self.left = set() 

self.right = set() 

return 

 

# need to turn off partition checking for Graph.__init__() adding 

# vertices and edges; methods are restored ad the end of big "if" 

# statement below 

import types 

self.add_vertex = types.MethodType(Graph.add_vertex, 

self, 

BipartiteGraph) 

self.add_vertices = types.MethodType(Graph.add_vertices, 

self, 

BipartiteGraph) 

self.add_edge = types.MethodType(Graph.add_edge, self, BipartiteGraph) 

 

from sage.structure.element import is_Matrix 

if isinstance(data, BipartiteGraph): 

Graph.__init__(self, data, *args, **kwds) 

self.left = set(data.left) 

self.right = set(data.right) 

elif isinstance(data, str): 

Graph.__init__(self, *args, **kwds) 

# will call self.load_afile after restoring add_vertex() instance 

# methods; initialize left and right attributes 

self.left = set() 

self.right = set() 

elif is_Matrix(data): 

# sanity check for mutually exclusive keywords 

if kwds.get("multiedges", False) and kwds.get("weighted", False): 

raise TypeError( 

"Weighted multi-edge bipartite graphs from reduced " + 

"adjacency matrix not supported.") 

Graph.__init__(self, *args, **kwds) 

ncols = data.ncols() 

nrows = data.nrows() 

self.left = set(range(ncols)) 

self.right = set(range(ncols, nrows + ncols)) 

 

# ensure that the vertices exist even if there 

# are no associated edges (trac #10356) 

self.add_vertices(self.left) 

self.add_vertices(self.right) 

 

if kwds.get("multiedges", False): 

for ii in range(ncols): 

for jj in range(nrows): 

if data[jj][ii] != 0: 

self.add_edges([(ii, jj + ncols)] * data[jj][ii]) 

elif kwds.get("weighted", False): 

for ii in range(ncols): 

for jj in range(nrows): 

if data[jj][ii] != 0: 

self.add_edge((ii, jj + ncols, data[jj][ii])) 

else: 

for ii in range(ncols): 

for jj in range(nrows): 

if data[jj][ii] != 0: 

self.add_edge((ii, jj + ncols)) 

elif (isinstance(data, Graph) and partition is not None): 

from copy import copy 

left, right = partition 

left = copy(left) 

right = copy(right) 

verts = set(left) | set(right) 

if set(data.vertices()) != verts: 

data = data.subgraph(list(verts)) 

Graph.__init__(self, data, *args, **kwds) 

if check: 

while len(left) > 0: 

a = left.pop(0) 

if len(set(data.neighbors(a)) & set(left)) != 0: 

raise TypeError( 

"Input graph is not bipartite with " + 

"respect to the given partition!") 

while len(right) > 0: 

a = right.pop(0) 

if len(set(data.neighbors(a)) & set(right)) != 0: 

raise TypeError( 

"Input graph is not bipartite with " + 

"respect to the given partition!") 

else: 

while len(left) > 0: 

a = left.pop(0) 

a_nbrs = set(data.neighbors(a)) & set(left) 

if len(a_nbrs) != 0: 

self.delete_edges([(a, b) for b in a_nbrs]) 

while len(right) > 0: 

a = right.pop(0) 

a_nbrs = set(data.neighbors(a)) & set(right) 

if len(a_nbrs) != 0: 

self.delete_edges([(a, b) for b in a_nbrs]) 

self.left, self.right = set(partition[0]), set(partition[1]) 

elif isinstance(data, Graph): 

Graph.__init__(self, data, *args, **kwds) 

try: 

self.left, self.right = self.bipartite_sets() 

except Exception: 

raise TypeError("Input graph is not bipartite!") 

else: 

import networkx 

Graph.__init__(self, data, *args, **kwds) 

if isinstance(data, (networkx.MultiGraph, networkx.Graph)): 

if hasattr(data, "node_type"): 

# Assume the graph is bipartite 

self.left = set() 

self.right = set() 

for v in data.nodes_iter(): 

if data.node_type[v] == "Bottom": 

self.left.add(v) 

elif data.node_type[v] == "Top": 

self.right.add(v) 

else: 

raise TypeError( 

"NetworkX node_type defies bipartite " + 

"assumption (is not 'Top' or 'Bottom')") 

# make sure we found a bipartition 

if not (hasattr(self, "left") and hasattr(self, "right")): 

try: 

self.left, self.right = self.bipartite_sets() 

except Exception: 

raise TypeError("Input graph is not bipartite!") 

 

# restore vertex partition checking 

self.add_vertex = types.MethodType(BipartiteGraph.add_vertex, 

self, 

BipartiteGraph) 

self.add_vertices = types.MethodType(BipartiteGraph.add_vertices, 

self, 

BipartiteGraph) 

self.add_edge = types.MethodType(BipartiteGraph.add_edge, 

self, 

BipartiteGraph) 

 

# post-processing 

if isinstance(data, str): 

self.load_afile(data) 

 

return 

 

def __repr__(self): 

r""" 

Returns a short string representation of self. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(16)) 

sage: B 

Bipartite cycle graph: graph on 16 vertices 

""" 

s = Graph._repr_(self).lower() 

if "bipartite" in s: 

return s.capitalize() 

else: 

return "".join(["Bipartite ", s]) 

 

def add_vertex(self, name=None, left=False, right=False): 

""" 

Creates an isolated vertex. If the vertex already exists, then 

nothing is done. 

 

INPUT: 

 

- ``name`` -- (default: ``None``) name of the new vertex. If no name 

is specified, then the vertex will be represented by the least 

non-negative integer not already representing a vertex. Name must 

be an immutable object and cannot be ``None``. 

 

- ``left`` -- (default: ``False``) if ``True``, puts the new vertex 

in the left partition. 

 

- ``right`` -- (default: ``False``) if ``True``, puts the new vertex 

in the right partition. 

 

Obviously, ``left`` and ``right`` are mutually exclusive. 

 

As it is implemented now, if a graph `G` has a large number 

of vertices with numeric labels, then ``G.add_vertex()`` could 

potentially be slow, if name is ``None``. 

 

OUTPUT: 

 

- If ``name``=``None``, the new vertex name is returned. ``None`` otherwise. 

 

EXAMPLES:: 

 

sage: G = BipartiteGraph() 

sage: G.add_vertex(left=True) 

0 

sage: G.add_vertex(right=True) 

1 

sage: G.vertices() 

[0, 1] 

sage: G.left 

{0} 

sage: G.right 

{1} 

 

TESTS: 

 

Exactly one of ``left`` and ``right`` must be true:: 

 

sage: G = BipartiteGraph() 

sage: G.add_vertex() 

Traceback (most recent call last): 

... 

RuntimeError: Partition must be specified (e.g. left=True). 

sage: G.add_vertex(left=True, right=True) 

Traceback (most recent call last): 

... 

RuntimeError: Only one partition may be specified. 

 

Adding the same vertex must specify the same partition:: 

 

sage: bg = BipartiteGraph() 

sage: bg.add_vertex(0, right=True) 

sage: bg.add_vertex(0, right=True) 

sage: bg.vertices() 

[0] 

sage: bg.add_vertex(0, left=True) 

Traceback (most recent call last): 

... 

RuntimeError: Cannot add duplicate vertex to other partition. 

""" 

# sanity check on partition specifiers 

if left and right: 

raise RuntimeError("Only one partition may be specified.") 

if not (left or right): 

raise RuntimeError("Partition must be specified (e.g. left=True).") 

 

# do nothing if we already have this vertex (idempotent) 

if (name is not None) and (name in self): 

if (((name in self.left) and left) or 

((name in self.right) and right)): 

return 

else: 

raise RuntimeError( 

"Cannot add duplicate vertex to other partition.") 

 

# add the vertex 

retval = Graph.add_vertex(self, name) 

if retval is not None: name = retval 

 

# add to proper partition 

if left: 

self.left.add(name) 

else: 

self.right.add(name) 

 

return retval 

 

def add_vertices(self, vertices, left=False, right=False): 

""" 

Add vertices to the bipartite graph from an iterable container of 

vertices. Vertices that already exist in the graph will not be added 

again. 

 

INPUT: 

 

- ``vertices`` -- sequence of vertices to add. 

 

- ``left`` -- (default: ``False``) either ``True`` or sequence of 

same length as ``vertices`` with ``True``/``False`` elements. 

 

- ``right`` -- (default: ``False``) either ``True`` or sequence of 

the same length as ``vertices`` with ``True``/``False`` elements. 

 

Only one of ``left`` and ``right`` keywords should be provided. See 

the examples below. 

 

EXAMPLES:: 

 

sage: bg = BipartiteGraph() 

sage: bg.add_vertices([0,1,2], left=True) 

sage: bg.add_vertices([3,4,5], left=[True, False, True]) 

sage: bg.add_vertices([6,7,8], right=[True, False, True]) 

sage: bg.add_vertices([9,10,11], right=True) 

sage: bg.left 

{0, 1, 2, 3, 5, 7} 

sage: bg.right 

{4, 6, 8, 9, 10, 11} 

 

TESTS:: 

 

sage: bg = BipartiteGraph() 

sage: bg.add_vertices([0,1,2], left=True) 

sage: bg.add_vertices([0,1,2], left=[True,True,True]) 

sage: bg.add_vertices([0,1,2], right=[False,False,False]) 

sage: bg.add_vertices([0,1,2], right=[False,False,False]) 

sage: bg.add_vertices([0,1,2]) 

Traceback (most recent call last): 

... 

RuntimeError: Partition must be specified (e.g. left=True). 

sage: bg.add_vertices([0,1,2], left=True, right=True) 

Traceback (most recent call last): 

... 

RuntimeError: Only one partition may be specified. 

sage: bg.add_vertices([0,1,2], right=True) 

Traceback (most recent call last): 

... 

RuntimeError: Cannot add duplicate vertex to other partition. 

sage: (bg.left, bg.right) 

({0, 1, 2}, set()) 

""" 

# sanity check on partition specifiers 

if left and right: # also triggered if both lists are specified 

raise RuntimeError("Only one partition may be specified.") 

if not (left or right): 

raise RuntimeError("Partition must be specified (e.g. left=True).") 

 

# handle partitions 

if left and (not hasattr(left, "__iter__")): 

new_left = set(vertices) 

new_right = set() 

elif right and (not hasattr(right, "__iter__")): 

new_left = set() 

new_right = set(vertices) 

else: 

# simplify to always work with left 

if right: 

left = [not tf for tf in right] 

new_left = set() 

new_right = set() 

for tf, vv in zip(left, vertices): 

if tf: 

new_left.add(vv) 

else: 

new_right.add(vv) 

 

# check that we're not trying to add vertices to the wrong sets 

# or that a vertex is to be placed in both 

if ((new_left & self.right) or 

(new_right & self.left) or 

(new_right & new_left)): 

raise RuntimeError( 

"Cannot add duplicate vertex to other partition.") 

 

# add vertices 

Graph.add_vertices(self, vertices) 

self.left.update(new_left) 

self.right.update(new_right) 

 

return 

 

def delete_vertex(self, vertex, in_order=False): 

""" 

Deletes vertex, removing all incident edges. Deleting a non-existent 

vertex will raise an exception. 

 

INPUT: 

 

- ``vertex`` -- a vertex to delete. 

 

- ``in_order`` -- (default ``False``) if ``True``, this deletes the 

`i`-th vertex in the sorted list of vertices, 

i.e. ``G.vertices()[i]``. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(4)) 

sage: B 

Bipartite cycle graph: graph on 4 vertices 

sage: B.delete_vertex(0) 

sage: B 

Bipartite cycle graph: graph on 3 vertices 

sage: B.left 

{2} 

sage: B.edges() 

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

sage: B.delete_vertex(3) 

sage: B.right 

{1} 

sage: B.edges() 

[(1, 2, None)] 

sage: B.delete_vertex(0) 

Traceback (most recent call last): 

... 

RuntimeError: Vertex (0) not in the graph. 

 

:: 

 

sage: g = Graph({'a':['b'], 'c':['b']}) 

sage: bg = BipartiteGraph(g) # finds bipartition 

sage: bg.vertices() 

['a', 'b', 'c'] 

sage: bg.delete_vertex('a') 

sage: bg.edges() 

[('b', 'c', None)] 

sage: bg.vertices() 

['b', 'c'] 

sage: bg2 = BipartiteGraph(g) 

sage: bg2.delete_vertex(0, in_order=True) 

sage: bg2 == bg 

True 

""" 

# cache vertex lookup if requested 

if in_order: 

vertex = self.vertices()[vertex] 

 

# delete from the graph 

Graph.delete_vertex(self, vertex) 

 

# now remove from partition (exception already thrown for non-existant 

# vertex) 

try: 

self.left.remove(vertex) 

except Exception: 

try: 

self.right.remove(vertex) 

except Exception: 

raise RuntimeError( 

"Vertex (%s) not found in partitions" % vertex) 

 

def delete_vertices(self, vertices): 

""" 

Remove vertices from the bipartite graph taken from an iterable 

sequence of vertices. Deleting a non-existent vertex will raise an 

exception. 

 

INPUT: 

 

- ``vertices`` -- a sequence of vertices to remove. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(4)) 

sage: B 

Bipartite cycle graph: graph on 4 vertices 

sage: B.delete_vertices([0,3]) 

sage: B 

Bipartite cycle graph: graph on 2 vertices 

sage: B.left 

{2} 

sage: B.right 

{1} 

sage: B.edges() 

[(1, 2, None)] 

sage: B.delete_vertices([0]) 

Traceback (most recent call last): 

... 

RuntimeError: Vertex (0) not in the graph. 

""" 

# remove vertices from the graph 

Graph.delete_vertices(self, vertices) 

 

# now remove vertices from partition lists (exception already thrown 

# for non-existant vertices) 

for vertex in vertices: 

try: 

self.left.remove(vertex) 

except Exception: 

try: 

self.right.remove(vertex) 

except Exception: 

raise RuntimeError( 

"Vertex (%s) not found in partitions" % vertex) 

 

def add_edge(self, u, v=None, label=None): 

""" 

Adds an edge from ``u`` and ``v``. 

 

INPUT: 

 

- ``u`` -- the tail of an edge. 

 

- ``v`` -- (default: ``None``) the head of an edge. If ``v=None``, then 

attempt to understand ``u`` as a edge tuple. 

 

- ``label`` -- (default: ``None``) the label of the edge ``(u, v)``. 

 

The following forms are all accepted: 

 

- ``G.add_edge(1, 2)`` 

- ``G.add_edge((1, 2))`` 

- ``G.add_edges([(1, 2)])`` 

- ``G.add_edge(1, 2, 'label')`` 

- ``G.add_edge((1, 2, 'label'))`` 

- ``G.add_edges([(1, 2, 'label')])`` 

 

See ``Graph.add_edge`` for more detail. 

 

This method simply checks that the edge endpoints are in different 

partitions. If a new vertex is to be created, it will be added 

to the proper partition. If both vertices are created, the first 

one will be added to the left partition, the second to the right 

partition. 

 

TESTS:: 

 

sage: bg = BipartiteGraph() 

sage: bg.add_vertices([0,1,2], left=[True,False,True]) 

sage: bg.add_edges([(0,1), (2,1)]) 

sage: bg.add_edge(0,2) 

Traceback (most recent call last): 

... 

RuntimeError: Edge vertices must lie in different partitions. 

sage: bg.add_edge(0,3); list(bg.right) 

[1, 3] 

sage: bg.add_edge(5,6); 5 in bg.left; 6 in bg.right 

True 

True 

""" 

# logic for getting endpoints copied from generic_graph.py 

if label is None: 

if v is None: 

try: 

u, v, label = u 

except Exception: 

u, v = u 

label = None 

else: 

if v is None: 

u, v = u 

 

# check for endpoints in different partitions 

if self.left.issuperset((u, v)) or self.right.issuperset((u, v)): 

raise RuntimeError( 

"Edge vertices must lie in different partitions.") 

 

# automatically decide partitions for the newly created vertices 

if u not in self: 

self.add_vertex(u, left=(v in self.right or v not in self), right=(v in self.left)) 

if v not in self: 

self.add_vertex(v, left=(u in self.right), right=(u in self.left)) 

 

# add the edge 

Graph.add_edge(self, u, v, label) 

return 

 

def allow_loops(self, new, check=True): 

""" 

Change whether loops are permitted in the (di)graph 

 

.. NOTE:: 

 

This method overwrite the 

:meth:`~sage.graphs.generic_graph.GenericGraph.allow_loops` method 

to ensure that loops are forbidden in :class:`~BipartiteGraph`. 

 

INPUT: 

 

- ``new`` - boolean. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph() 

sage: B.allow_loops(True) 

Traceback (most recent call last): 

... 

ValueError: loops are not allowed in bipartite graphs 

""" 

if new is True: 

raise ValueError("loops are not allowed in bipartite graphs") 

 

def complement(self): 

""" 

Return a complement of this graph. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph({1: [2, 4], 3: [4, 5]}) 

sage: G = B.complement(); G 

Graph on 5 vertices 

sage: G.edges(labels=False) 

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

""" 

# This is needed because complement() of generic graph 

# would return a graph of class BipartiteGraph that is 

# not bipartite. See ticket #12376. 

return Graph(self).complement() 

 

def to_undirected(self): 

""" 

Return an undirected Graph (without bipartite constraint) of the given 

object. 

 

EXAMPLES:: 

 

sage: BipartiteGraph(graphs.CycleGraph(6)).to_undirected() 

Cycle graph: Graph on 6 vertices 

""" 

return Graph(self) 

 

def bipartition(self): 

r""" 

Returns the underlying bipartition of the bipartite graph. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(4)) 

sage: B.bipartition() 

({0, 2}, {1, 3}) 

""" 

return (self.left, self.right) 

 

def project_left(self): 

r""" 

Projects ``self`` onto left vertices. Edges are 2-paths in the 

original. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(20)) 

sage: G = B.project_left() 

sage: G.order(), G.size() 

(10, 10) 

""" 

G = Graph() 

G.add_vertices(self.left) 

for v in G: 

for u in self.neighbor_iterator(v): 

G.add_edges(((v, w) for w in self.neighbor_iterator(u)), loops=None) 

return G 

 

def project_right(self): 

r""" 

Projects ``self`` onto right vertices. Edges are 2-paths in the 

original. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(20)) 

sage: G = B.project_right() 

sage: G.order(), G.size() 

(10, 10) 

""" 

G = Graph() 

G.add_vertices(self.left) 

for v in G: 

for u in self.neighbor_iterator(v): 

G.add_edges(((v, w) for w in self.neighbor_iterator(u)), loops=None) 

return G 

 

def plot(self, *args, **kwds): 

r""" 

Overrides Graph's plot function, to illustrate the bipartite nature. 

 

EXAMPLES:: 

 

sage: B = BipartiteGraph(graphs.CycleGraph(20)) 

sage: B.plot() 

Graphics object consisting of 41 graphics primitives 

""" 

if "pos" not in kwds: 

kwds["pos"] = None 

if kwds["pos"] is None: 

pos = {} 

left = list(self.left) 

right = list(self.right) 

left.sort() 

right.sort() 

l_len = len(self.left) 

r_len = len(self.right) 

if l_len == 1: 

pos[left[0]] = [-1, 0] 

elif l_len > 1: 

i = 0 

d = 2.0 / (l_len - 1) 

for v in left: 

pos[v] = [-1, 1 - i*d] 

i += 1 

if r_len == 1: 

pos[right[0]] = [1, 0] 

elif r_len > 1: 

i = 0 

d = 2.0 / (r_len - 1) 

for v in right: 

pos[v] = [1, 1 - i*d] 

i += 1 

kwds["pos"] = pos 

return Graph.plot(self, *args, **kwds) 

 

def matching_polynomial(self, algorithm="Godsil", name=None): 

r""" 

Computes the matching polynomial. 

 

If `p(G, k)` denotes the number of `k`-matchings (matchings with `k` edges) 

in `G`, then the *matching polynomial* is defined as [Godsil93]_: 

 

.. MATH:: 

 

\mu(x)=\sum_{k \geq 0} (-1)^k p(G,k) x^{n-2k} 

 

INPUT: 

 

- ``algorithm`` - a string which must be either "Godsil" (default) 

or "rook"; "rook" is usually faster for larger graphs. 

 

- ``name`` - optional string for the variable name in the polynomial. 

 

EXAMPLES:: 

 

sage: BipartiteGraph(graphs.CubeGraph(3)).matching_polynomial() 

x^8 - 12*x^6 + 42*x^4 - 44*x^2 + 9 

 

:: 

 

sage: x = polygen(QQ) 

sage: g = BipartiteGraph(graphs.CompleteBipartiteGraph(16, 16)) 

sage: bool(factorial(16)*laguerre(16,x^2) == g.matching_polynomial(algorithm='rook')) 

True 

 

Compute the matching polynomial of a line with `60` vertices:: 

 

sage: from sage.functions.orthogonal_polys import chebyshev_U 

sage: g = next(graphs.trees(60)) 

sage: chebyshev_U(60, x/2) == BipartiteGraph(g).matching_polynomial(algorithm='rook') 

True 

 

The matching polynomial of a tree graphs is equal to its characteristic 

polynomial:: 

 

sage: g = graphs.RandomTree(20) 

sage: p = g.characteristic_polynomial() 

sage: p == BipartiteGraph(g).matching_polynomial(algorithm='rook') 

True 

 

TESTS:: 

 

sage: g = BipartiteGraph(matrix.ones(4,3)) 

sage: g.matching_polynomial() 

x^7 - 12*x^5 + 36*x^3 - 24*x 

sage: g.matching_polynomial(algorithm="rook") 

x^7 - 12*x^5 + 36*x^3 - 24*x 

""" 

if algorithm == "Godsil": 

return Graph.matching_polynomial(self, complement=False, name=name) 

elif algorithm == "rook": 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

A = self.reduced_adjacency_matrix() 

a = A.rook_vector() 

m = A.nrows() 

n = A.ncols() 

b = [0]*(m + n + 1) 

for i in range(min(m, n) + 1): 

b[m + n - 2*i] = a[i]*(-1)**i 

if name is None: 

name = 'x' 

K = PolynomialRing(A.base_ring(), name) 

p = K(b) 

return p 

else: 

raise ValueError('algorithm must be one of "Godsil" or "rook".') 

 

def load_afile(self, fname): 

r""" 

Loads into the current object the bipartite graph specified in the 

given file name. This file should follow David MacKay's alist format, 

see 

http://www.inference.phy.cam.ac.uk/mackay/codes/data.html 

for examples and definition of the format. 

 

EXAMPLES:: 

 

sage: file_name = os.path.join(SAGE_TMP, 'deleteme.alist.txt') 

sage: fi = open(file_name, 'w') 

sage: _ = fi.write("7 4 \n 3 4 \n 3 3 1 3 1 1 1 \n 3 3 3 4 \n\ 

1 2 4 \n 1 3 4 \n 1 0 0 \n 2 3 4 \n\ 

2 0 0 \n 3 0 0 \n 4 0 0 \n\ 

1 2 3 0 \n 1 4 5 0 \n 2 4 6 0 \n 1 2 4 7 \n") 

sage: fi.close(); 

sage: B = BipartiteGraph() 

sage: B.load_afile(file_name) 

Bipartite graph on 11 vertices 

sage: B.edges() 

[(0, 7, None), 

(0, 8, None), 

(0, 10, None), 

(1, 7, None), 

(1, 9, None), 

(1, 10, None), 

(2, 7, None), 

(3, 8, None), 

(3, 9, None), 

(3, 10, None), 

(4, 8, None), 

(5, 9, None), 

(6, 10, None)] 

sage: B2 = BipartiteGraph(file_name) 

sage: B2 == B 

True 

""" 

# open the file 

try: 

fi = open(fname, "r") 

except IOError: 

print("Unable to open file <<" + fname + ">>.") 

return None 

 

# read header information 

num_cols, num_rows = [int(_) for _ in fi.readline().split()] 

max_col_degree, max_row_degree = [int(_) for _ in fi.readline().split()] 

col_degrees = [int(_) for _ in fi.readline().split()] 

row_degrees = [int(_) for _ in fi.readline().split()] 

 

# sanity checks on header info 

if len(col_degrees) != num_cols: 

print("Invalid Alist format: ") 

print("Number of column degree entries does not match number " + 

"of columns.") 

return None 

if len(row_degrees) != num_rows: 

print("Invalid Alist format: ") 

print("Number of row degree entries does not match number " + 

"of rows.") 

return None 

 

# clear out self 

self.clear() 

self.add_vertices(range(num_cols), left=True) 

self.add_vertices(range(num_cols, num_cols + num_rows), right=True) 

 

# read adjacency information 

for cidx in range(num_cols): 

for ridx in map(int, fi.readline().split()): 

# A-list uses 1-based indices with 0's as place-holders 

if ridx > 0: 

self.add_edge(cidx, num_cols + ridx - 1) 

 

#NOTE:: we could read in the row adjacency information as well to 

# double-check.... 

#NOTE:: we could check the actual node degrees against the reported 

# node degrees.... 

 

# now we have all the edges in our graph, just fill in the 

# bipartite partitioning 

self.left = set(range(num_cols)) 

self.right = set(range(num_cols, num_cols + num_rows)) 

 

# return self for chaining calls if desired 

return self 

 

def save_afile(self, fname): 

r""" 

Save the graph to file in alist format. 

 

Saves this graph to file in David MacKay's alist format, see 

http://www.inference.phy.cam.ac.uk/mackay/codes/data.html 

for examples and definition of the format. 

 

EXAMPLES:: 

 

sage: M = Matrix([(1,1,1,0,0,0,0), (1,0,0,1,1,0,0), 

....: (0,1,0,1,0,1,0), (1,1,0,1,0,0,1)]) 

sage: M 

[1 1 1 0 0 0 0] 

[1 0 0 1 1 0 0] 

[0 1 0 1 0 1 0] 

[1 1 0 1 0 0 1] 

sage: b = BipartiteGraph(M) 

sage: file_name = os.path.join(SAGE_TMP, 'deleteme.alist.txt') 

sage: b.save_afile(file_name) 

sage: b2 = BipartiteGraph(file_name) 

sage: b == b2 

True 

 

TESTS:: 

 

sage: file_name = os.path.join(SAGE_TMP, 'deleteme.alist.txt') 

sage: for order in range(3, 13, 3): 

....: num_chks = int(order / 3) 

....: num_vars = order - num_chks 

....: partition = (list(range(num_vars)), list(range(num_vars, num_vars+num_chks))) 

....: for idx in range(100): 

....: g = graphs.RandomGNP(order, 0.5) 

....: try: 

....: b = BipartiteGraph(g, partition, check=False) 

....: b.save_afile(file_name) 

....: b2 = BipartiteGraph(file_name) 

....: if b != b2: 

....: print("Load/save failed for code with edges:") 

....: print(b.edges()) 

....: break 

....: except Exception: 

....: print("Exception encountered for graph of order "+ str(order)) 

....: print("with edges: ") 

....: g.edges() 

....: raise 

""" 

# open the file 

try: 

fi = open(fname, "w") 

except IOError: 

print("Unable to open file <<" + fname + ">>.") 

return 

 

# prep: handy lists, functions for extracting adjacent nodes 

vnodes = list(self.left) 

cnodes = list(self.right) 

vnodes.sort() 

cnodes.sort() 

max_vdeg = max(self.degree(vnodes)) 

max_cdeg = max(self.degree(cnodes)) 

num_vnodes = len(vnodes) 

vnbr_str = lambda idx: str(idx - num_vnodes + 1) 

cnbr_str = lambda idx: str(idx + 1) 

 

# write header information 

fi.write("%d %d\n" % (len(vnodes), len(cnodes))) 

fi.write("%d %d\n" % (max_vdeg, max_cdeg)) 

fi.write(" ".join(map(str, self.degree(vnodes))) + "\n") 

fi.write(" ".join(map(str, self.degree(cnodes))) + "\n") 

for vidx in vnodes: 

nbrs = self.neighbors(vidx) 

fi.write(" ".join(map(vnbr_str, nbrs))) 

fi.write(" 0"*(max_vdeg - len(nbrs)) + "\n") 

for cidx in cnodes: 

nbrs = self.neighbors(cidx) 

fi.write(" ".join(map(cnbr_str, nbrs))) 

fi.write(" 0"*(max_cdeg - len(nbrs)) + "\n") 

 

# done 

fi.close() 

 

# return self for chaining calls if desired 

return 

 

def __edge2idx(self, v1, v2, left, right): 

r""" 

Translate an edge to its reduced adjacency matrix position. 

 

Returns (row index, column index) for the given pair of vertices. 

 

EXAMPLES:: 

 

sage: P = graphs.PetersenGraph() 

sage: partition = [list(range(5)), list(range(5,10))] 

sage: B = BipartiteGraph(P, partition, check=False) 

sage: B._BipartiteGraph__edge2idx(2,7,list(range(5)),list(range(5,10))) 

(2, 2) 

""" 

try: 

if v1 in self.left: # note uses attribute for faster lookup 

return (right.index(v2), left.index(v1)) 

else: 

return (right.index(v1), left.index(v2)) 

except ValueError: 

raise ValueError( 

"Tried to map invalid edge (%d,%d) to vertex indices" % 

(v1, v2)) 

 

def reduced_adjacency_matrix(self, sparse=True): 

r""" 

Return the reduced adjacency matrix for the given graph. 

 

A reduced adjacency matrix contains only the non-redundant portion of 

the full adjacency matrix for the bipartite graph. Specifically, for 

zero matrices of the appropriate size, for the reduced adjacency 

matrix ``H``, the full adjacency matrix is ``[[0, H'], [H, 0]]``. 

 

This method supports the named argument 'sparse' which defaults to 

``True``. When enabled, the returned matrix will be sparse. 

 

EXAMPLES: 

 

Bipartite graphs that are not weighted will return a matrix over ZZ:: 

 

sage: M = Matrix([(1,1,1,0,0,0,0), (1,0,0,1,1,0,0), 

....: (0,1,0,1,0,1,0), (1,1,0,1,0,0,1)]) 

sage: B = BipartiteGraph(M) 

sage: N = B.reduced_adjacency_matrix() 

sage: N 

[1 1 1 0 0 0 0] 

[1 0 0 1 1 0 0] 

[0 1 0 1 0 1 0] 

[1 1 0 1 0 0 1] 

sage: N == M 

True 

sage: N[0,0].parent() 

Integer Ring 

 

Multi-edge graphs also return a matrix over ZZ:: 

 

sage: M = Matrix([(1,1,2,0,0), (0,2,1,1,1), (0,1,2,1,1)]) 

sage: B = BipartiteGraph(M, multiedges=True, sparse=True) 

sage: N = B.reduced_adjacency_matrix() 

sage: N == M 

True 

sage: N[0,0].parent() 

Integer Ring 

 

Weighted graphs will return a matrix over the ring given by their 

(first) weights:: 

 

sage: F.<a> = GF(4) 

sage: MS = MatrixSpace(F, 2, 3) 

sage: M = MS.matrix([[0, 1, a+1], [a, 1, 1]]) 

sage: B = BipartiteGraph(M, weighted=True, sparse=True) 

sage: N = B.reduced_adjacency_matrix(sparse=False) 

sage: N == M 

True 

sage: N[0,0].parent() 

Finite Field in a of size 2^2 

 

TESTS:: 

 

sage: B = BipartiteGraph() 

sage: B.reduced_adjacency_matrix() 

[] 

sage: M = Matrix([[0,0], [0,0]]) 

sage: BipartiteGraph(M).reduced_adjacency_matrix() == M 

True 

sage: M = Matrix([[10,2/3], [0,0]]) 

sage: B = BipartiteGraph(M, weighted=True, sparse=True) 

sage: M == B.reduced_adjacency_matrix() 

True 

 

""" 

if self.multiple_edges() and self.weighted(): 

raise NotImplementedError( 

"Don't know how to represent weights for a multigraph.") 

if self.is_directed(): 

raise NotImplementedError( 

"Reduced adjacency matrix does not exist for directed graphs.") 

 

# create sorted lists of left and right edges 

left = list(self.left) 

right = list(self.right) 

left.sort() 

right.sort() 

 

# create dictionary of edges, values are weights for weighted graph, 

# otherwise the number of edges (always 1 for simple graphs) 

D = {} 

if self.weighted(): 

for (v1, v2, weight) in self.edge_iterator(): 

D[self.__edge2idx(v1, v2, left, right)] = weight 

else: 

# if we're normal or multi-edge, just create the matrix over ZZ 

for (v1, v2, name) in self.edge_iterator(): 

idx = self.__edge2idx(v1, v2, left, right) 

if idx in D: 

D[idx] = 1 + D[idx] 

else: 

D[idx] = 1 

 

# now construct and return the matrix from the dictionary we created 

from sage.matrix.constructor import matrix 

return matrix(len(self.right), len(self.left), D, sparse=sparse) 

 

def matching(self, value_only=False, algorithm=None, 

use_edge_labels=False, solver=None, verbose=0): 

r""" 

Return a maximum matching of the graph represented by the list of its 

edges. 

 

Given a graph `G` such that each edge `e` has a weight `w_e`, a maximum 

matching is a subset `S` of the edges of `G` of maximum weight such that 

no two edges of `S` are incident with each other. 

 

INPUT: 

 

- ``value_only`` -- boolean (default: ``False``); when set to ``True``, 

only the cardinal (or the weight) of the matching is returned 

 

- ``algorithm`` -- string (default: ``"Hopcroft-Karp"`` if 

``use_edge_labels==False``, otherwise ``"Edmonds"``) 

 

- ``"Hopcroft-Karp"`` selects the default bipartite graph algorithm as 

implemented in NetworkX 

 

- ``"Eppstein"`` selects Eppstein's algorithm as implemented in 

NetworkX 

 

- ``"Edmonds"`` selects Edmonds' algorithm as implemented in NetworkX 

 

- ``"LP"`` uses a Linear Program formulation of the matching problem 

 

- ``use_edge_labels`` -- boolean (default: ``False``) 

 

- when set to ``True``, computes a weighted matching where each edge 

is weighted by its label (if an edge has no label, `1` is assumed); 

only if ``algorithm`` is ``"Edmonds"``, ``"LP"`` 

 

- when set to ``False``, each edge has weight `1` 

 

- ``solver`` -- (default: ``None``) a specific Linear Program (LP) 

solver to be used 

 

- ``verbose`` -- integer (default: ``0``); sets the level of verbosity: 

set to 0 by default, which means quiet 

 

.. SEEALSO:: 

 

- :wikipedia:`Matching_(graph_theory)` 

- :meth:`~Graph.matching` 

 

EXAMPLES: 

 

Maximum matching in a cycle graph:: 

 

sage: G = BipartiteGraph(graphs.CycleGraph(10)) 

sage: G.matching() 

[(0, 1, None), (2, 3, None), (4, 5, None), (6, 7, None), (8, 9, None)] 

 

The size of a maximum matching in a complete bipartite graph using 

Eppstein:: 

 

sage: G = BipartiteGraph(graphs.CompleteBipartiteGraph(4,5)) 

sage: G.matching(algorithm="Eppstein", value_only=True) 

4 

 

TESTS: 

 

If ``algorithm`` is not set to one of the supported algorithms, an 

exception is raised:: 

 

sage: G = BipartiteGraph(graphs.CompleteBipartiteGraph(4,5)) 

sage: G.matching(algorithm="somethingdifferent") 

Traceback (most recent call last): 

... 

ValueError: algorithm must be "Hopcroft-Karp", "Eppstein", "Edmonds" or "LP" 

 

Maximum matching in a weighted bipartite graph:: 

 

sage: G = graphs.CycleGraph(4) 

sage: B = BipartiteGraph([(u,v,2) for u,v in G.edges(labels=0)]) 

sage: B.matching(use_edge_labels=True) 

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

sage: B.matching(use_edge_labels=True, value_only=True) 

4 

sage: B.matching(use_edge_labels=True, value_only=True, algorithm='Edmonds') 

4 

sage: B.matching(use_edge_labels=True, value_only=True, algorithm='LP') 

4.0 

sage: B.matching(use_edge_labels=True, value_only=True, algorithm='Eppstein') 

Traceback (most recent call last): 

... 

ValueError: use_edge_labels can not be used with "Hopcroft-Karp" or "Eppstein" 

sage: B.matching(use_edge_labels=True, value_only=True, algorithm='Hopcroft-Karp') 

Traceback (most recent call last): 

... 

ValueError: use_edge_labels can not be used with "Hopcroft-Karp" or "Eppstein" 

sage: B.matching(use_edge_labels=False, value_only=True, algorithm='Hopcroft-Karp') 

2 

sage: B.matching(use_edge_labels=False, value_only=True, algorithm='Eppstein') 

2 

sage: B.matching(use_edge_labels=False, value_only=True, algorithm='Edmonds') 

2 

sage: B.matching(use_edge_labels=False, value_only=True, algorithm='LP') 

2 

 

With multiedges enabled:: 

 

sage: G = BipartiteGraph(graphs.CubeGraph(3)) 

sage: for e in G.edges(): 

....: G.set_edge_label(e[0], e[1], int(e[0]) + int(e[1])) 

....: 

sage: G.allow_multiple_edges(True) 

sage: G.matching(use_edge_labels=True, value_only=True) 

444 

""" 

from sage.rings.real_mpfr import RR 

def weight(x): 

if x in RR: 

return x 

else: 

return 1 

 

if algorithm is None: 

algorithm = "Edmonds" if use_edge_labels else "Hopcroft-Karp" 

 

if algorithm == "Hopcroft-Karp" or algorithm == "Eppstein": 

if use_edge_labels: 

raise ValueError('use_edge_labels can not be used with ' + 

'"Hopcroft-Karp" or "Eppstein"') 

W = dict() 

L = dict() 

for u,v,l in self.edge_iterator(): 

if not (u, v) in L or ( use_edge_labels and W[u, v] < weight(l) ): 

L[u, v] = l 

if use_edge_labels: 

W[u, v] = weight(l) 

import networkx 

g = networkx.Graph() 

if use_edge_labels: 

for u, v in W: 

g.add_edge(u, v, attr_dict={"weight": W[u, v]}) 

else: 

for u, v in L: 

g.add_edge(u, v) 

if algorithm == "Hopcroft-Karp": 

d = networkx.bipartite.hopcroft_karp_matching(g) 

else: 

d = networkx.bipartite.eppstein_matching(g) 

if value_only: 

if use_edge_labels: 

return sum(W[u, v] for u, v in iteritems(d) if u < v) 

else: 

return Integer(len(d) // 2) 

else: 

return [(u, v, L[u, v]) for u, v in iteritems(d) if u < v] 

elif algorithm == "Edmonds" or algorithm == "LP": 

return Graph.matching(self, value_only=value_only, 

algorithm=algorithm, 

use_edge_labels=use_edge_labels, 

solver=solver, verbose=verbose) 

else: 

raise ValueError('algorithm must be "Hopcroft-Karp", ' + 

'"Eppstein", "Edmonds" or "LP"')