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

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

5093

5094

5095

5096

5097

5098

5099

5100

5101

5102

5103

5104

5105

5106

5107

5108

5109

5110

5111

5112

5113

5114

5115

5116

5117

5118

5119

5120

5121

5122

5123

5124

5125

5126

5127

5128

5129

5130

5131

5132

5133

5134

5135

5136

5137

5138

5139

5140

5141

5142

5143

5144

5145

5146

5147

5148

5149

5150

5151

5152

5153

5154

5155

5156

5157

5158

5159

5160

5161

5162

5163

5164

5165

5166

5167

5168

5169

5170

5171

5172

5173

5174

5175

5176

5177

5178

5179

5180

5181

5182

5183

5184

5185

5186

5187

5188

5189

5190

5191

5192

5193

5194

5195

5196

5197

5198

5199

5200

5201

5202

5203

5204

5205

5206

5207

5208

5209

5210

5211

5212

5213

5214

5215

5216

5217

5218

5219

5220

5221

5222

5223

5224

5225

5226

5227

5228

5229

5230

5231

5232

5233

5234

5235

5236

5237

5238

5239

5240

5241

5242

5243

5244

5245

5246

5247

5248

5249

5250

5251

5252

5253

5254

5255

5256

5257

5258

5259

5260

5261

5262

5263

5264

5265

5266

5267

5268

5269

5270

5271

5272

5273

5274

5275

5276

5277

5278

5279

5280

5281

5282

5283

5284

5285

5286

5287

5288

5289

5290

5291

5292

5293

5294

5295

5296

5297

5298

5299

5300

5301

5302

5303

5304

5305

5306

5307

5308

5309

5310

5311

5312

5313

5314

5315

5316

5317

5318

5319

5320

5321

5322

5323

5324

5325

5326

5327

5328

5329

5330

5331

5332

5333

5334

5335

5336

5337

5338

5339

5340

5341

5342

5343

5344

5345

5346

5347

5348

5349

5350

5351

5352

5353

5354

5355

5356

5357

5358

5359

5360

5361

5362

5363

5364

5365

5366

5367

5368

5369

5370

5371

5372

5373

5374

5375

5376

5377

5378

5379

5380

5381

5382

5383

5384

5385

5386

5387

5388

5389

5390

5391

5392

5393

5394

5395

5396

5397

5398

5399

5400

5401

5402

5403

5404

5405

5406

5407

5408

5409

5410

5411

5412

5413

5414

5415

5416

5417

5418

5419

5420

5421

5422

5423

5424

5425

5426

5427

5428

5429

5430

5431

5432

5433

5434

5435

5436

5437

5438

5439

5440

5441

5442

5443

5444

5445

5446

5447

5448

5449

5450

5451

5452

5453

5454

5455

5456

5457

5458

5459

5460

5461

5462

5463

5464

5465

5466

5467

5468

5469

5470

5471

5472

5473

5474

5475

5476

5477

5478

5479

5480

5481

5482

5483

5484

5485

5486

5487

5488

5489

5490

5491

5492

5493

5494

5495

5496

5497

5498

5499

5500

5501

5502

5503

5504

5505

5506

5507

5508

5509

5510

5511

5512

5513

5514

5515

5516

5517

5518

5519

5520

5521

5522

5523

5524

5525

5526

5527

5528

5529

5530

5531

5532

5533

5534

5535

5536

5537

5538

5539

5540

5541

5542

5543

5544

5545

5546

5547

5548

5549

5550

5551

5552

5553

5554

5555

5556

5557

5558

5559

5560

5561

5562

5563

5564

5565

5566

5567

5568

5569

5570

5571

5572

5573

5574

5575

5576

5577

5578

5579

5580

5581

5582

5583

5584

5585

5586

5587

5588

5589

5590

5591

5592

5593

5594

5595

5596

5597

5598

5599

5600

5601

5602

5603

5604

5605

5606

5607

5608

5609

5610

5611

5612

5613

5614

5615

5616

5617

5618

5619

5620

5621

5622

5623

5624

5625

5626

5627

5628

5629

5630

5631

5632

5633

5634

5635

5636

5637

5638

5639

5640

5641

5642

5643

5644

5645

5646

5647

5648

5649

5650

5651

5652

5653

5654

5655

5656

5657

5658

5659

5660

5661

5662

5663

5664

5665

5666

5667

5668

5669

5670

5671

5672

5673

5674

5675

5676

5677

5678

5679

5680

5681

5682

5683

5684

5685

5686

5687

5688

5689

5690

5691

5692

5693

5694

5695

5696

5697

5698

5699

5700

5701

5702

5703

5704

5705

5706

5707

5708

5709

5710

5711

5712

5713

5714

5715

5716

5717

5718

5719

5720

5721

5722

5723

5724

5725

5726

5727

5728

5729

5730

5731

5732

5733

5734

5735

5736

5737

5738

5739

5740

5741

5742

5743

5744

5745

5746

5747

5748

5749

5750

5751

5752

5753

5754

5755

5756

5757

5758

5759

5760

5761

5762

5763

5764

5765

5766

5767

5768

5769

5770

5771

5772

5773

5774

5775

5776

5777

5778

5779

5780

5781

5782

5783

5784

5785

5786

5787

5788

5789

5790

5791

5792

5793

5794

5795

5796

5797

5798

5799

5800

5801

5802

5803

5804

5805

5806

5807

5808

5809

5810

5811

5812

5813

5814

5815

5816

5817

5818

5819

5820

5821

5822

5823

5824

5825

5826

5827

5828

5829

5830

5831

5832

5833

5834

5835

5836

5837

5838

5839

5840

5841

5842

5843

5844

5845

5846

5847

5848

5849

5850

5851

5852

5853

5854

5855

5856

5857

5858

5859

5860

5861

5862

5863

5864

5865

5866

5867

5868

5869

5870

5871

5872

5873

5874

5875

5876

5877

5878

5879

5880

5881

5882

5883

5884

5885

5886

5887

5888

5889

5890

5891

5892

5893

5894

5895

5896

5897

5898

5899

5900

5901

5902

5903

5904

5905

5906

5907

5908

5909

5910

5911

5912

5913

5914

5915

5916

5917

5918

5919

5920

5921

5922

5923

5924

5925

5926

5927

5928

5929

5930

5931

5932

5933

5934

5935

5936

5937

5938

5939

5940

5941

5942

5943

5944

5945

5946

5947

5948

5949

5950

5951

5952

5953

5954

5955

5956

5957

5958

5959

5960

5961

5962

5963

5964

5965

5966

5967

5968

5969

5970

5971

5972

5973

5974

5975

5976

5977

5978

5979

5980

5981

5982

5983

5984

5985

5986

5987

5988

5989

5990

5991

5992

5993

5994

5995

5996

5997

5998

5999

6000

6001

6002

6003

6004

6005

6006

6007

6008

6009

6010

6011

6012

6013

6014

6015

6016

6017

6018

6019

6020

6021

6022

6023

6024

6025

6026

6027

6028

6029

6030

6031

6032

6033

6034

6035

6036

6037

6038

6039

6040

6041

6042

6043

6044

6045

6046

6047

6048

6049

6050

6051

6052

6053

6054

6055

6056

6057

6058

6059

6060

6061

6062

6063

6064

6065

6066

6067

6068

6069

6070

6071

6072

6073

6074

6075

6076

6077

6078

6079

6080

6081

6082

6083

6084

6085

6086

6087

6088

6089

6090

6091

6092

6093

6094

6095

6096

6097

6098

6099

6100

6101

6102

6103

6104

6105

6106

6107

6108

6109

6110

6111

6112

6113

6114

6115

6116

6117

6118

6119

6120

6121

6122

6123

6124

6125

6126

6127

6128

6129

6130

6131

6132

6133

6134

6135

6136

6137

6138

6139

6140

6141

6142

6143

6144

6145

6146

6147

6148

6149

6150

6151

6152

6153

6154

6155

6156

6157

6158

6159

6160

6161

6162

6163

6164

6165

6166

6167

6168

6169

6170

6171

6172

6173

6174

6175

6176

6177

6178

6179

6180

6181

6182

6183

6184

6185

6186

6187

6188

6189

6190

6191

6192

6193

6194

6195

6196

6197

6198

6199

6200

6201

6202

6203

6204

6205

6206

6207

6208

6209

6210

6211

6212

6213

6214

6215

6216

6217

6218

6219

6220

6221

6222

6223

6224

6225

6226

6227

6228

6229

6230

6231

6232

6233

6234

6235

6236

6237

6238

6239

6240

6241

6242

6243

6244

6245

6246

6247

6248

6249

6250

6251

6252

6253

6254

6255

6256

6257

6258

6259

6260

6261

6262

6263

6264

6265

6266

6267

6268

6269

6270

6271

6272

6273

6274

6275

6276

6277

6278

6279

6280

6281

6282

6283

6284

6285

6286

6287

6288

6289

6290

6291

6292

6293

6294

6295

6296

6297

6298

6299

6300

6301

6302

6303

6304

6305

6306

6307

6308

6309

6310

6311

6312

6313

6314

6315

6316

6317

6318

6319

6320

6321

6322

6323

6324

6325

6326

6327

6328

6329

6330

6331

6332

6333

6334

6335

6336

6337

6338

6339

6340

6341

6342

6343

6344

6345

6346

6347

6348

6349

6350

6351

6352

6353

6354

6355

6356

6357

6358

6359

6360

6361

6362

6363

6364

6365

6366

6367

6368

6369

6370

6371

6372

6373

6374

6375

6376

6377

6378

6379

6380

6381

6382

6383

6384

6385

6386

6387

6388

6389

6390

6391

6392

6393

6394

6395

6396

6397

6398

6399

6400

6401

6402

6403

6404

6405

6406

6407

6408

6409

6410

6411

6412

6413

6414

6415

6416

6417

6418

6419

6420

6421

6422

6423

6424

6425

6426

6427

6428

6429

6430

6431

6432

6433

6434

6435

6436

6437

6438

6439

6440

6441

6442

6443

6444

6445

6446

6447

6448

6449

6450

6451

6452

6453

6454

6455

6456

6457

6458

6459

6460

6461

6462

6463

6464

6465

6466

6467

6468

6469

6470

6471

6472

6473

6474

6475

6476

6477

6478

6479

6480

6481

6482

6483

6484

6485

6486

6487

6488

6489

6490

6491

6492

6493

6494

6495

6496

6497

6498

6499

6500

6501

6502

6503

6504

6505

6506

6507

6508

6509

6510

6511

6512

6513

6514

6515

6516

6517

6518

6519

6520

6521

6522

6523

6524

6525

6526

6527

6528

6529

6530

6531

6532

6533

6534

6535

6536

6537

6538

6539

6540

6541

6542

6543

6544

6545

6546

6547

6548

6549

6550

6551

6552

6553

6554

6555

6556

6557

6558

6559

6560

6561

6562

6563

6564

6565

6566

6567

6568

6569

6570

6571

6572

6573

6574

6575

6576

6577

6578

6579

6580

6581

6582

6583

6584

6585

6586

6587

6588

6589

6590

6591

6592

6593

6594

6595

6596

6597

6598

6599

6600

6601

6602

6603

6604

6605

6606

6607

6608

6609

6610

6611

6612

6613

6614

6615

6616

6617

6618

6619

6620

6621

6622

6623

6624

6625

6626

6627

6628

6629

6630

6631

6632

6633

6634

6635

6636

6637

6638

6639

6640

6641

6642

6643

6644

6645

6646

6647

6648

6649

6650

6651

6652

6653

6654

6655

6656

6657

6658

6659

6660

6661

6662

6663

6664

6665

6666

6667

6668

6669

6670

6671

6672

6673

6674

6675

6676

6677

6678

6679

6680

6681

6682

6683

6684

6685

6686

6687

6688

6689

6690

6691

6692

6693

6694

6695

6696

6697

6698

6699

6700

6701

6702

6703

6704

6705

6706

6707

6708

6709

6710

6711

6712

6713

6714

6715

6716

6717

6718

6719

6720

6721

6722

6723

6724

6725

6726

6727

6728

6729

6730

6731

6732

6733

6734

6735

6736

6737

6738

6739

6740

6741

6742

6743

6744

6745

6746

6747

6748

6749

6750

6751

6752

6753

6754

6755

6756

6757

6758

6759

6760

6761

6762

6763

6764

6765

6766

6767

6768

6769

6770

6771

6772

6773

6774

6775

6776

6777

6778

6779

6780

6781

6782

6783

6784

6785

6786

6787

6788

6789

6790

6791

6792

6793

6794

6795

6796

6797

6798

6799

6800

6801

6802

6803

6804

6805

6806

6807

6808

6809

6810

6811

6812

6813

6814

6815

6816

6817

6818

6819

6820

6821

6822

6823

6824

6825

6826

6827

6828

6829

6830

6831

6832

6833

6834

6835

6836

6837

6838

6839

6840

6841

6842

6843

6844

6845

6846

6847

6848

6849

6850

6851

6852

6853

6854

6855

6856

6857

6858

6859

6860

6861

6862

6863

6864

6865

6866

6867

6868

6869

6870

6871

6872

6873

6874

6875

6876

6877

6878

6879

6880

6881

6882

6883

6884

6885

6886

6887

6888

6889

6890

6891

6892

6893

6894

6895

6896

6897

6898

6899

6900

6901

6902

6903

6904

6905

6906

6907

6908

6909

6910

6911

6912

6913

6914

6915

6916

6917

6918

6919

6920

6921

6922

6923

6924

6925

6926

6927

6928

6929

6930

6931

6932

6933

6934

6935

6936

6937

6938

6939

6940

6941

6942

6943

6944

6945

6946

6947

6948

6949

6950

6951

6952

6953

6954

6955

6956

6957

6958

6959

6960

6961

6962

6963

6964

6965

6966

6967

6968

6969

6970

6971

6972

6973

6974

6975

6976

6977

6978

6979

6980

6981

6982

6983

6984

6985

6986

6987

6988

6989

6990

6991

6992

6993

6994

6995

6996

6997

6998

6999

7000

7001

7002

7003

7004

7005

7006

7007

7008

7009

7010

7011

7012

7013

7014

7015

7016

7017

7018

7019

7020

7021

7022

7023

7024

7025

7026

7027

7028

7029

7030

7031

7032

7033

7034

7035

7036

7037

7038

7039

7040

7041

7042

7043

7044

7045

7046

7047

7048

7049

7050

7051

7052

7053

7054

7055

7056

7057

7058

7059

7060

7061

7062

7063

7064

7065

7066

7067

7068

7069

7070

7071

7072

7073

7074

7075

7076

7077

7078

7079

7080

7081

7082

7083

7084

7085

7086

7087

7088

7089

7090

7091

7092

7093

7094

7095

7096

7097

7098

7099

7100

7101

7102

7103

7104

7105

7106

7107

7108

7109

7110

7111

7112

7113

7114

7115

7116

7117

7118

7119

7120

7121

7122

7123

7124

7125

7126

7127

7128

7129

7130

7131

7132

7133

7134

7135

7136

7137

7138

7139

7140

7141

7142

7143

7144

7145

7146

7147

7148

7149

7150

7151

7152

7153

7154

7155

7156

7157

7158

7159

7160

7161

7162

7163

7164

7165

7166

7167

7168

7169

7170

7171

7172

7173

7174

7175

7176

7177

7178

7179

7180

7181

7182

7183

7184

7185

7186

7187

7188

7189

7190

7191

7192

7193

7194

7195

7196

7197

7198

7199

7200

7201

7202

7203

7204

7205

7206

7207

7208

7209

7210

7211

7212

7213

7214

7215

7216

7217

7218

7219

7220

7221

7222

7223

7224

7225

7226

7227

7228

7229

7230

7231

7232

7233

7234

7235

7236

7237

7238

7239

7240

7241

7242

7243

7244

7245

7246

7247

7248

7249

7250

7251

7252

7253

7254

7255

7256

7257

7258

7259

7260

7261

7262

7263

7264

7265

7266

7267

7268

7269

7270

7271

7272

7273

7274

7275

7276

7277

7278

7279

7280

7281

7282

7283

7284

7285

7286

7287

7288

7289

7290

7291

7292

7293

7294

7295

7296

7297

7298

7299

7300

7301

7302

7303

7304

7305

7306

7307

7308

7309

7310

7311

7312

7313

7314

7315

7316

7317

7318

7319

7320

7321

7322

7323

7324

7325

7326

7327

7328

7329

7330

7331

7332

7333

7334

7335

7336

7337

7338

7339

7340

7341

7342

7343

7344

7345

7346

7347

7348

7349

7350

7351

7352

7353

7354

7355

7356

7357

7358

7359

7360

7361

7362

7363

7364

7365

7366

7367

7368

7369

7370

7371

7372

7373

7374

7375

7376

7377

7378

7379

7380

7381

7382

7383

7384

7385

7386

7387

7388

7389

7390

7391

7392

7393

7394

7395

7396

7397

7398

7399

7400

7401

7402

7403

7404

7405

7406

7407

7408

7409

7410

7411

7412

7413

7414

7415

7416

7417

7418

7419

7420

7421

7422

7423

7424

7425

7426

7427

7428

7429

7430

7431

7432

7433

7434

7435

7436

7437

7438

7439

7440

7441

7442

7443

7444

7445

7446

7447

7448

7449

7450

7451

7452

7453

7454

7455

7456

7457

7458

7459

7460

7461

7462

7463

7464

7465

7466

7467

7468

7469

7470

7471

7472

7473

7474

7475

7476

7477

7478

7479

7480

7481

7482

7483

7484

7485

7486

7487

7488

7489

7490

7491

7492

7493

7494

7495

7496

7497

7498

7499

7500

7501

7502

7503

7504

7505

7506

7507

7508

7509

7510

7511

7512

7513

7514

7515

7516

7517

7518

7519

7520

7521

7522

7523

7524

7525

7526

7527

7528

7529

7530

7531

7532

7533

7534

7535

7536

7537

7538

7539

7540

7541

7542

7543

7544

7545

7546

7547

7548

7549

7550

7551

7552

7553

7554

7555

7556

7557

7558

7559

7560

7561

7562

7563

7564

7565

7566

7567

7568

7569

7570

7571

7572

7573

7574

7575

7576

7577

7578

7579

7580

7581

7582

7583

7584

7585

7586

7587

7588

7589

7590

7591

7592

7593

7594

7595

7596

7597

7598

7599

7600

7601

7602

7603

7604

7605

7606

7607

7608

7609

7610

7611

7612

7613

7614

7615

7616

7617

7618

7619

7620

7621

7622

7623

7624

7625

7626

7627

7628

7629

7630

7631

7632

7633

7634

7635

7636

7637

7638

7639

7640

7641

7642

7643

7644

7645

7646

7647

7648

7649

7650

7651

7652

7653

7654

7655

7656

7657

7658

7659

7660

7661

7662

7663

7664

7665

7666

7667

7668

7669

7670

7671

7672

7673

7674

7675

7676

7677

7678

7679

7680

7681

7682

7683

7684

7685

7686

7687

7688

7689

7690

7691

7692

7693

7694

7695

7696

7697

7698

7699

7700

7701

7702

7703

7704

7705

7706

7707

7708

7709

7710

7711

7712

7713

7714

7715

7716

7717

7718

7719

7720

7721

7722

7723

7724

7725

7726

7727

7728

7729

7730

7731

7732

7733

7734

7735

7736

7737

7738

7739

7740

7741

7742

7743

7744

7745

7746

7747

7748

7749

7750

7751

7752

7753

7754

7755

7756

7757

7758

7759

7760

7761

7762

7763

7764

7765

7766

7767

7768

7769

7770

7771

7772

7773

7774

7775

7776

7777

7778

7779

7780

7781

7782

7783

7784

7785

7786

7787

7788

7789

7790

7791

7792

7793

7794

7795

7796

7797

7798

7799

7800

7801

7802

7803

7804

7805

7806

7807

7808

7809

7810

7811

7812

7813

7814

7815

7816

7817

7818

7819

7820

7821

7822

7823

7824

7825

7826

7827

7828

7829

7830

7831

7832

7833

7834

7835

7836

7837

7838

7839

7840

7841

7842

7843

7844

7845

7846

7847

7848

7849

7850

7851

7852

7853

7854

7855

7856

7857

7858

7859

7860

7861

7862

7863

7864

7865

7866

7867

7868

7869

7870

7871

7872

7873

7874

7875

7876

7877

7878

7879

7880

7881

7882

7883

7884

7885

7886

7887

7888

7889

7890

7891

7892

7893

7894

7895

7896

7897

7898

7899

7900

7901

7902

7903

7904

7905

7906

7907

7908

7909

7910

7911

7912

7913

7914

7915

7916

7917

7918

7919

7920

7921

7922

7923

7924

7925

7926

7927

7928

7929

7930

7931

7932

7933

7934

7935

7936

7937

7938

7939

7940

7941

7942

7943

7944

7945

7946

7947

7948

7949

7950

7951

7952

7953

7954

7955

7956

7957

7958

7959

7960

7961

7962

7963

7964

7965

7966

7967

7968

7969

7970

7971

7972

7973

7974

7975

7976

7977

7978

7979

7980

7981

7982

7983

7984

7985

7986

7987

7988

7989

7990

7991

7992

7993

7994

7995

7996

7997

7998

7999

8000

8001

8002

8003

8004

8005

8006

8007

8008

8009

8010

8011

8012

8013

8014

8015

8016

8017

8018

8019

8020

8021

8022

8023

8024

8025

8026

8027

8028

8029

8030

8031

8032

8033

8034

8035

8036

8037

8038

8039

8040

8041

8042

8043

8044

8045

8046

8047

8048

8049

8050

8051

8052

8053

8054

8055

8056

8057

8058

8059

8060

8061

8062

8063

8064

8065

8066

8067

8068

8069

8070

8071

8072

8073

8074

8075

8076

8077

8078

8079

8080

8081

8082

8083

8084

8085

8086

8087

8088

8089

8090

8091

8092

8093

8094

8095

8096

8097

8098

8099

8100

8101

8102

8103

8104

8105

8106

8107

8108

8109

8110

8111

8112

8113

8114

8115

8116

8117

8118

8119

8120

8121

8122

8123

8124

8125

8126

8127

8128

8129

8130

8131

8132

8133

8134

8135

8136

8137

8138

8139

8140

8141

8142

8143

8144

8145

8146

8147

8148

8149

8150

8151

8152

8153

8154

8155

8156

8157

8158

8159

8160

8161

8162

8163

8164

8165

8166

8167

8168

8169

8170

8171

8172

8173

8174

8175

8176

8177

8178

8179

8180

8181

8182

8183

8184

8185

8186

8187

8188

8189

8190

8191

8192

8193

8194

8195

8196

8197

8198

8199

8200

8201

8202

8203

8204

8205

8206

8207

8208

8209

8210

8211

8212

8213

8214

8215

# -*- coding: utf-8 -*- 

r""" 

Undirected graphs 

 

This module implements functions and operations involving undirected 

graphs. 

 

{INDEX_OF_METHODS} 

 

AUTHORS: 

 

- Robert L. Miller (2006-10-22): initial version 

 

- William Stein (2006-12-05): Editing 

 

- Robert L. Miller (2007-01-13): refactoring, adjusting for 

NetworkX-0.33, fixed plotting bugs (2007-01-23): basic tutorial, 

edge labels, loops, multiple edges and arcs (2007-02-07): graph6 

and sparse6 formats, matrix input 

 

- Emily Kirkmann (2007-02-11): added graph_border option to plot 

and show 

 

- Robert L. Miller (2007-02-12): vertex color-maps, graph 

boundaries, graph6 helper functions in Cython 

 

- Robert L. Miller Sage Days 3 (2007-02-17-21): 3d plotting in 

Tachyon 

 

- Robert L. Miller (2007-02-25): display a partition 

 

- Robert L. Miller (2007-02-28): associate arbitrary objects to 

vertices, edge and arc label display (in 2d), edge coloring 

 

- Robert L. Miller (2007-03-21): Automorphism group, isomorphism 

check, canonical label 

 

- Robert L. Miller (2007-06-07-09): NetworkX function wrapping 

 

- Michael W. Hansen (2007-06-09): Topological sort generation 

 

- Emily Kirkman, Robert L. Miller Sage Days 4: Finished wrapping 

NetworkX 

 

- Emily Kirkman (2007-07-21): Genus (including circular planar, 

all embeddings and all planar embeddings), all paths, interior 

paths 

 

- Bobby Moretti (2007-08-12): fixed up plotting of graphs with 

edge colors differentiated by label 

 

- Jason Grout (2007-09-25): Added functions, bug fixes, and 

general enhancements 

 

- Robert L. Miller (Sage Days 7): Edge labeled graph isomorphism 

 

- Tom Boothby (Sage Days 7): Miscellaneous awesomeness 

 

- Tom Boothby (2008-01-09): Added graphviz output 

 

- David Joyner (2009-2): Fixed docstring bug related to GAP. 

 

- Stephen Hartke (2009-07-26): Fixed bug in blocks_and_cut_vertices() 

that caused an incorrect result when the vertex 0 was a cut vertex. 

 

- Stephen Hartke (2009-08-22): Fixed bug in blocks_and_cut_vertices() 

where the list of cut_vertices is not treated as a set. 

 

- Anders Jonsson (2009-10-10): Counting of spanning trees and out-trees added. 

 

- Nathann Cohen (2009-09) : Cliquer, Connectivity, Flows 

and everything that uses Linear Programming 

and class numerical.MIP 

 

- Nicolas M. Thiery (2010-02): graph layout code refactoring, dot2tex/graphviz interface 

 

- David Coudert (2012-04) : Reduction rules in vertex_cover. 

 

- Birk Eisermann (2012-06): added recognition of weakly chordal graphs and 

long-hole-free / long-antihole-free graphs 

 

- Alexandre P. Zuge (2013-07): added join operation. 

 

- Amritanshu Prasad (2014-08): added clique polynomial 

 

Graph Format 

------------ 

 

Supported formats 

~~~~~~~~~~~~~~~~~ 

 

Sage Graphs can be created from a wide range of inputs. A few 

examples are covered here. 

 

 

- NetworkX dictionary format: 

 

:: 

 

sage: d = {0: [1,4,5], 1: [2,6], 2: [3,7], 3: [4,8], 4: [9], \ 

5: [7, 8], 6: [8,9], 7: [9]} 

sage: G = Graph(d); G 

Graph on 10 vertices 

sage: G.plot().show() # or G.show() 

 

- A NetworkX graph: 

 

:: 

 

sage: import networkx 

sage: K = networkx.complete_bipartite_graph(12,7) 

sage: G = Graph(K) 

sage: G.degree() 

[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 12, 12, 12, 12, 12, 12, 12] 

 

- graph6 or sparse6 format: 

 

:: 

 

sage: s = ':I`AKGsaOs`cI]Gb~' 

sage: G = Graph(s, sparse=True); G 

Looped multi-graph on 10 vertices 

sage: G.plot().show() # or G.show() 

 

Note that the ``\`` character is an escape character in Python, and 

also a character used by graph6 strings: 

 

:: 

 

sage: G = Graph('Ihe\n@GUA') 

Traceback (most recent call last): 

... 

RuntimeError: The string (Ihe) seems corrupt: for n = 10, the string is too short. 

 

In Python, the escaped character ``\`` is represented by ``\\``: 

 

:: 

 

sage: G = Graph('Ihe\\n@GUA') 

sage: G.plot().show() # or G.show() 

 

- adjacency matrix: In an adjacency matrix, each column and each 

row represent a vertex. If a 1 shows up in row `i`, column 

`j`, there is an edge `(i,j)`. 

 

:: 

 

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

(0,1,0,1,0,0,0,1,0,0), (0,0,1,0,1,0,0,0,1,0),(1,0,0,1,0,0,0,0,0,1), \ 

(1,0,0,0,0,0,0,1,1,0), (0,1,0,0,0,0,0,0,1,1),(0,0,1,0,0,1,0,0,0,1), \ 

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

sage: M 

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

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

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

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

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

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

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

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

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

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

sage: G = Graph(M); G 

Graph on 10 vertices 

sage: G.plot().show() # or G.show() 

 

- incidence matrix: In an incidence matrix, each row represents a 

vertex and each column represents an edge. 

 

:: 

 

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

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

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

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

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

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

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

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

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

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

sage: M 

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

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

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

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

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

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

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

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

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

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

sage: G = Graph(M); G 

Graph on 10 vertices 

sage: G.plot().show() # or G.show() 

sage: DiGraph(matrix(2,[0,0,-1,1]), format="incidence_matrix") 

Traceback (most recent call last): 

... 

ValueError: There must be two nonzero entries (-1 & 1) per column. 

 

- a list of edges:: 

 

sage: g = Graph([(1,3),(3,8),(5,2)]) 

sage: g 

Graph on 5 vertices 

 

- an igraph Graph:: 

 

sage: import igraph # optional - python_igraph 

sage: g = Graph(igraph.Graph([(1,3),(3,2),(0,2)])) # optional - python_igraph 

sage: g # optional - python_igraph 

Graph on 4 vertices 

 

Generators 

---------- 

 

Use ``graphs(n)`` to iterate through all non-isomorphic graphs of given size:: 

 

sage: for g in graphs(4): 

....: print(g.spectrum()) 

[0, 0, 0, 0] 

[1, 0, 0, -1] 

[1.4142135623..., 0, 0, -1.4142135623...] 

[2, 0, -1, -1] 

[1.7320508075..., 0, 0, -1.7320508075...] 

[1, 1, -1, -1] 

[1.6180339887..., 0.6180339887..., -0.6180339887..., -1.6180339887...] 

[2.1700864866..., 0.3111078174..., -1, -1.4811943040...] 

[2, 0, 0, -2] 

[2.5615528128..., 0, -1, -1.5615528128...] 

[3, -1, -1, -1] 

 

Similarly ``graphs()`` will iterate through all graphs. The complete 

graph of 4 vertices is of course the smallest graph with chromatic number 

bigger than three:: 

 

sage: for g in graphs(): 

....: if g.chromatic_number() > 3: 

....: break 

sage: g.is_isomorphic(graphs.CompleteGraph(4)) 

True 

 

For some commonly used graphs to play with, type 

 

:: 

 

sage: graphs.[tab] # not tested 

 

and hit {tab}. Most of these graphs come with their own custom 

plot, so you can see how people usually visualize these graphs. 

 

:: 

 

sage: G = graphs.PetersenGraph() 

sage: G.plot().show() # or G.show() 

sage: G.degree_histogram() 

[0, 0, 0, 10] 

sage: G.adjacency_matrix() 

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

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

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

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

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

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

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

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

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

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

 

:: 

 

sage: S = G.subgraph([0,1,2,3]) 

sage: S.plot().show() # or S.show() 

sage: S.density() 

1/2 

 

:: 

 

sage: G = GraphQuery(display_cols=['graph6'], num_vertices=7, diameter=5) 

sage: L = G.get_graphs_list() 

sage: graphs_list.show_graphs(L) 

 

.. _Graph:labels: 

 

Labels 

------ 

 

Each vertex can have any hashable object as a label. These are 

things like strings, numbers, and tuples. Each edge is given a 

default label of ``None``, but if specified, edges can 

have any label at all. Edges between vertices `u` and 

`v` are represented typically as ``(u, v, l)``, where 

``l`` is the label for the edge. 

 

Note that vertex labels themselves cannot be mutable items:: 

 

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

sage: G = Graph({ 0 : { M : None } }) 

Traceback (most recent call last): 

... 

TypeError: mutable matrices are unhashable 

 

However, if one wants to define a dictionary, with the same keys 

and arbitrary objects for entries, one can make that association:: 

 

sage: d = {0 : graphs.DodecahedralGraph(), 1 : graphs.FlowerSnark(), \ 

2 : graphs.MoebiusKantorGraph(), 3 : graphs.PetersenGraph() } 

sage: d[2] 

Moebius-Kantor Graph: Graph on 16 vertices 

sage: T = graphs.TetrahedralGraph() 

sage: T.vertices() 

[0, 1, 2, 3] 

sage: T.set_vertices(d) 

sage: T.get_vertex(1) 

Flower Snark: Graph on 20 vertices 

 

Database 

-------- 

 

There is a database available for searching for graphs that satisfy 

a certain set of parameters, including number of vertices and 

edges, density, maximum and minimum degree, diameter, radius, and 

connectivity. To see a list of all search parameter keywords broken 

down by their designated table names, type 

 

:: 

 

sage: graph_db_info() 

{...} 

 

For more details on data types or keyword input, enter 

 

:: 

 

sage: GraphQuery? # not tested 

 

The results of a query can be viewed with the show method, or can be 

viewed individually by iterating through the results: 

 

:: 

 

sage: Q = GraphQuery(display_cols=['graph6'],num_vertices=7, diameter=5) 

sage: Q.show() 

Graph6 

-------------------- 

F?`po 

F?gqg 

F@?]O 

F@OKg 

F@R@o 

FA_pW 

FEOhW 

FGC{o 

FIAHo 

 

Show each graph as you iterate through the results: 

 

:: 

 

sage: for g in Q: 

....: show(g) 

 

Visualization 

------------- 

 

To see a graph `G` you are working with, there 

are three main options. You can view the graph in two dimensions via 

matplotlib with ``show()``. :: 

 

sage: G = graphs.RandomGNP(15,.3) 

sage: G.show() 

 

And you can view it in three dimensions via jmol with ``show3d()``. :: 

 

sage: G.show3d() 

 

Or it can be rendered with `\LaTeX`. This requires the right 

additions to a standard `\mbox{\rm\TeX}` installation. Then standard 

Sage commands, such as ``view(G)`` will display the graph, or 

``latex(G)`` will produce a string suitable for inclusion in a 

`\LaTeX` document. More details on this are at 

the :mod:`sage.graphs.graph_latex` module. :: 

 

sage: from sage.graphs.graph_latex import check_tkz_graph 

sage: check_tkz_graph() # random - depends on TeX installation 

sage: latex(G) 

\begin{tikzpicture} 

... 

\end{tikzpicture} 

 

Mutability 

---------- 

 

Graphs are mutable, and thus unusable as dictionary keys, unless 

``data_structure="static_sparse"`` is used:: 

 

sage: G = graphs.PetersenGraph() 

sage: {G:1}[G] 

Traceback (most recent call last): 

... 

TypeError: This graph is mutable, and thus not hashable. Create an immutable copy by `g.copy(immutable=True)` 

sage: G_immutable = Graph(G, immutable=True) 

sage: G_immutable == G 

True 

sage: {G_immutable:1}[G_immutable] 

1 

 

Methods 

------- 

""" 

 

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

# Copyright (C) 2006 - 2007 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 

import six 

from six.moves import range 

 

from copy import copy 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

from sage.misc.superseded import deprecation 

from sage.rings.integer import Integer 

from sage.rings.integer_ring import ZZ 

import sage.graphs.generic_graph_pyx as generic_graph_pyx 

from sage.graphs.generic_graph import GenericGraph 

from sage.graphs.digraph import DiGraph 

from sage.graphs.independent_sets import IndependentSets 

from sage.combinat.combinatorial_map import combinatorial_map 

from sage.misc.rest_index_of_methods import doc_index, gen_thematic_rest_table_index 

 

class Graph(GenericGraph): 

r""" 

Undirected graph. 

 

A graph is a set of vertices connected by edges. See also the 

:wikipedia:`Wikipedia article on graphs <Graph_(mathematics)>`. For a 

collection of pre-defined graphs, see the 

:mod:`~sage.graphs.graph_generators` module. 

 

A :class:`Graph` object has many methods whose list can be obtained by 

typing ``g.<tab>`` (i.e. hit the 'tab' key) or by reading the documentation 

of :mod:`~sage.graphs.graph`, :mod:`~sage.graphs.generic_graph`, and 

:mod:`~sage.graphs.digraph`. 

 

INPUT: 

 

By default, a :class:`Graph` object is simple (i.e. no *loops* nor *multiple 

edges*) and unweighted. This can be easily tuned with the appropriate flags 

(see below). 

 

- ``data`` -- can be any of the following (see the ``format`` argument): 

 

#. ``Graph()`` -- build a graph on 0 vertices. 

 

#. ``Graph(5)`` -- return an edgeless graph on the 5 vertices 0,...,4. 

 

#. ``Graph([list_of_vertices,list_of_edges])`` -- returns a graph with 

given vertices/edges. 

 

To bypass auto-detection, prefer the more explicit 

``Graph([V,E],format='vertices_and_edges')``. 

 

#. ``Graph(list_of_edges)`` -- return a graph with a given list of edges 

(see documentation of 

:meth:`~sage.graphs.generic_graph.GenericGraph.add_edges`). 

 

To bypass auto-detection, prefer the more explicit ``Graph(L, 

format='list_of_edges')``. 

 

#. ``Graph({1:[2,3,4],3:[4]})`` -- return a graph by associating to each 

vertex the list of its neighbors. 

 

To bypass auto-detection, prefer the more explicit ``Graph(D, 

format='dict_of_lists')``. 

 

#. ``Graph({1: {2: 'a', 3:'b'} ,3:{2:'c'}})`` -- return a graph by 

associating a list of neighbors to each vertex and providing its edge 

label. 

 

To bypass auto-detection, prefer the more explicit ``Graph(D, 

format='dict_of_dicts')``. 

 

For graphs with multiple edges, you can provide a list of labels 

instead, e.g.: ``Graph({1: {2: ['a1', 'a2'], 3:['b']} ,3:{2:['c']}})``. 

 

#. ``Graph(a_symmetric_matrix)`` -- return a graph with given (weighted) 

adjacency matrix (see documentation of 

:meth:`~sage.graphs.generic_graph.GenericGraph.adjacency_matrix`). 

 

To bypass auto-detection, prefer the more explicit ``Graph(M, 

format='adjacency_matrix')``. To take weights into account, use 

``format='weighted_adjacency_matrix'`` instead. 

 

#. ``Graph(a_nonsymmetric_matrix)`` -- return a graph with given incidence 

matrix (see documentation of 

:meth:`~sage.graphs.generic_graph.GenericGraph.incidence_matrix`). 

 

To bypass auto-detection, prefer the more explicit ``Graph(M, 

format='incidence_matrix')``. 

 

#. ``Graph([V, f])`` -- return a graph from a vertex set ``V`` and a 

*symmetric* function ``f``. The graph contains an edge `u,v` whenever 

``f(u,v)`` is ``True``.. Example: ``Graph([ [1..10], lambda x,y: 

abs(x-y).is_square()])`` 

 

#. ``Graph(':I`ES@obGkqegW~')`` -- return a graph from a graph6 or sparse6 

string (see documentation of :meth:`graph6_string` or 

:meth:`sparse6_string`). 

 

#. ``Graph(a_seidel_matrix, format='seidel_adjacency_matrix')`` -- return 

a graph with a given Seidel adjacency matrix (see documentation of 

:meth:`seidel_adjacency_matrix`). 

 

#. ``Graph(another_graph)`` -- return a graph from a Sage (di)graph, 

`pygraphviz <https://pygraphviz.github.io/>`__ graph, `NetworkX 

<https://networkx.github.io/>`__ graph, or `igraph 

<http://igraph.org/python/>`__ graph. 

 

- ``pos`` - a positioning dictionary (cf. documentation of 

:meth:`~sage.graphs.generic_graph.GenericGraph.layout`). For example, to 

draw 4 vertices on a square:: 

 

{0: [-1,-1], 

1: [ 1,-1], 

2: [ 1, 1], 

3: [-1, 1]} 

 

- ``name`` - (must be an explicitly named parameter, 

i.e., ``name="complete")`` gives the graph a name 

 

- ``loops`` - boolean, whether to allow loops (ignored 

if data is an instance of the ``Graph`` class) 

 

- ``multiedges`` - boolean, whether to allow multiple 

edges (ignored if data is an instance of the ``Graph`` class). 

 

- ``weighted`` - whether graph thinks of itself as weighted or not. See 

:meth:`~sage.graphs.generic_graph.GenericGraph.weighted`. 

 

- ``format`` - if set to ``None`` (default), :class:`Graph` tries to guess 

input's format. To avoid this possibly time-consuming step, one of the 

following values can be specified (see description above): ``"int"``, 

``"graph6"``, ``"sparse6"``, ``"rule"``, ``"list_of_edges"``, 

``"dict_of_lists"``, ``"dict_of_dicts"``, ``"adjacency_matrix"``, 

``"weighted_adjacency_matrix"``, ``"seidel_adjacency_matrix"``, 

``"incidence_matrix"``, ``"NX"``, ``"igraph"``. 

 

- ``sparse`` (boolean) -- ``sparse=True`` is an alias for 

``data_structure="sparse"``, and ``sparse=False`` is an alias for 

``data_structure="dense"``. 

 

- ``data_structure`` -- one of the following (for more information, see 

:mod:`~sage.graphs.base.overview`) 

 

* ``"dense"`` -- selects the :mod:`~sage.graphs.base.dense_graph` 

backend. 

 

* ``"sparse"`` -- selects the :mod:`~sage.graphs.base.sparse_graph` 

backend. 

 

* ``"static_sparse"`` -- selects the 

:mod:`~sage.graphs.base.static_sparse_backend` (this backend is faster 

than the sparse backend and smaller in memory, and it is immutable, so 

that the resulting graphs can be used as dictionary keys). 

 

- ``immutable`` (boolean) -- whether to create a immutable graph. Note that 

``immutable=True`` is actually a shortcut for 

``data_structure='static_sparse'``. Set to ``False`` by default. 

 

- ``vertex_labels`` - Whether to allow any object as a vertex (slower), or 

only the integers `0,...,n-1`, where `n` is the number of vertices. 

 

- ``convert_empty_dict_labels_to_None`` - this arguments sets 

the default edge labels used by NetworkX (empty dictionaries) 

to be replaced by None, the default Sage edge label. It is 

set to ``True`` iff a NetworkX graph is on the input. 

 

EXAMPLES: 

 

We illustrate the first seven input formats (the other two 

involve packages that are currently not standard in Sage): 

 

#. An integer giving the number of vertices:: 

 

sage: g = Graph(5); g 

Graph on 5 vertices 

sage: g.vertices() 

[0, 1, 2, 3, 4] 

sage: g.edges() 

[] 

 

#. A dictionary of dictionaries:: 

 

sage: g = Graph({0:{1:'x',2:'z',3:'a'}, 2:{5:'out'}}); g 

Graph on 5 vertices 

 

The labels ('x', 'z', 'a', 'out') are labels for edges. For 

example, 'out' is the label for the edge on 2 and 5. Labels can be 

used as weights, if all the labels share some common parent. 

 

:: 

 

sage: a,b,c,d,e,f = sorted(SymmetricGroup(3)) 

sage: Graph({b:{d:'c',e:'p'}, c:{d:'p',e:'c'}}) 

Graph on 4 vertices 

 

#. A dictionary of lists:: 

 

sage: g = Graph({0:[1,2,3], 2:[4]}); g 

Graph on 5 vertices 

 

#. A list of vertices and a function describing adjacencies. Note 

that the list of vertices and the function must be enclosed in a 

list (i.e., [list of vertices, function]). 

 

Construct the Paley graph over GF(13). 

 

:: 

 

sage: g=Graph([GF(13), lambda i,j: i!=j and (i-j).is_square()]) 

sage: g.vertices() 

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 

sage: g.adjacency_matrix() 

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

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

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

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

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

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

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

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

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

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

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

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

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

 

Construct the line graph of a complete graph. 

 

:: 

 

sage: g=graphs.CompleteGraph(4) 

sage: line_graph=Graph([g.edges(labels=false), \ 

lambda i,j: len(set(i).intersection(set(j)))>0], \ 

loops=False) 

sage: line_graph.vertices() 

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

sage: line_graph.adjacency_matrix() 

[0 1 1 1 1 0] 

[1 0 1 1 0 1] 

[1 1 0 0 1 1] 

[1 1 0 0 1 1] 

[1 0 1 1 0 1] 

[0 1 1 1 1 0] 

 

#. A graph6 or sparse6 string: Sage automatically recognizes 

whether a string is in graph6 or sparse6 format:: 

 

sage: s = ':I`AKGsaOs`cI]Gb~' 

sage: Graph(s,sparse=True) 

Looped multi-graph on 10 vertices 

 

:: 

 

sage: G = Graph('G?????') 

sage: G = Graph("G'?G?C") 

Traceback (most recent call last): 

... 

RuntimeError: The string seems corrupt: valid characters are 

?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 

sage: G = Graph('G??????') 

Traceback (most recent call last): 

... 

RuntimeError: The string (G??????) seems corrupt: for n = 8, the string is too long. 

 

:: 

 

sage: G = Graph(":I'AKGsaOs`cI]Gb~") 

Traceback (most recent call last): 

... 

RuntimeError: The string seems corrupt: valid characters are 

?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 

 

There are also list functions to take care of lists of graphs:: 

 

sage: s = ':IgMoqoCUOqeb\n:I`AKGsaOs`cI]Gb~\n:I`EDOAEQ?PccSsge\N\n' 

sage: graphs_list.from_sparse6(s) 

[Looped multi-graph on 10 vertices, Looped multi-graph on 10 vertices, Looped multi-graph on 10 vertices] 

 

#. A Sage matrix: 

Note: If format is not specified, then Sage assumes a symmetric square 

matrix is an adjacency matrix, otherwise an incidence matrix. 

 

- an adjacency matrix:: 

 

sage: M = graphs.PetersenGraph().am(); M 

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

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

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

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

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

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

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

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

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

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

sage: Graph(M) 

Graph on 10 vertices 

 

:: 

 

sage: Graph(matrix([[1,2],[2,4]]),loops=True,sparse=True) 

Looped multi-graph on 2 vertices 

 

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

[ 0 1 -1] 

[ 1 0 -1/2] 

[ -1 -1/2 0] 

sage: G = Graph(M,sparse=True); G 

Graph on 3 vertices 

sage: G.weighted() 

True 

 

- an incidence matrix:: 

 

sage: M = Matrix(6, [-1,0,0,0,1, 1,-1,0,0,0, 0,1,-1,0,0, 0,0,1,-1,0, 0,0,0,1,-1, 0,0,0,0,0]); M 

[-1 0 0 0 1] 

[ 1 -1 0 0 0] 

[ 0 1 -1 0 0] 

[ 0 0 1 -1 0] 

[ 0 0 0 1 -1] 

[ 0 0 0 0 0] 

sage: Graph(M) 

Graph on 6 vertices 

 

sage: Graph(Matrix([[1],[1],[1]])) 

Traceback (most recent call last): 

... 

ValueError: There must be one or two nonzero entries per column in an incidence matrix. Got entries [1, 1, 1] in column 0 

sage: Graph(Matrix([[1],[1],[0]])) 

Graph on 3 vertices 

 

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

[ 0 1 -1] 

[ 1 0 -1] 

[-1 -1 0] 

sage: Graph(M,sparse=True) 

Graph on 3 vertices 

 

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

[ 0 1 1] 

[ 1 0 1] 

[-1 -1 0] 

sage: Graph(M) 

Traceback (most recent call last): 

... 

ValueError: There must be one or two nonzero entries per column in an incidence matrix. Got entries [1, 1] in column 2 

 

Check that :trac:`9714` is fixed:: 

 

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

sage: GA = Graph(MA, format='adjacency_matrix') 

sage: MI = GA.incidence_matrix(oriented=False) 

sage: MI 

[2 1 1 0 0 0] 

[0 1 1 2 2 0] 

[0 0 0 0 0 2] 

sage: Graph(MI).edges(labels=None) 

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

 

sage: M = Matrix([[1], [-1]]); M 

[ 1] 

[-1] 

sage: Graph(M).edges() 

[(0, 1, None)] 

 

#. A Seidel adjacency matrix:: 

 

sage: from sage.combinat.matrices.hadamard_matrix import \ 

....: regular_symmetric_hadamard_matrix_with_constant_diagonal as rshcd 

sage: m=rshcd(16,1)- matrix.identity(16) 

sage: Graph(m,format="seidel_adjacency_matrix").is_strongly_regular(parameters=True) 

(16, 6, 2, 2) 

 

#. a list of edges, or labelled edges:: 

 

sage: g = Graph([(1,3),(3,8),(5,2)]) 

sage: g 

Graph on 5 vertices 

 

sage: g = Graph([(1,2,"Peace"),(7,-9,"and"),(77,2, "Love")]) 

sage: g 

Graph on 5 vertices 

sage: g = Graph([(0, 2, '0'), (0, 2, '1'), (3, 3, '2')], loops=True, multiedges=True) 

sage: g.loops() 

[(3, 3, '2')] 

 

#. A NetworkX MultiGraph:: 

 

sage: import networkx 

sage: g = networkx.MultiGraph({0:[1,2,3], 2:[4]}) 

sage: Graph(g) 

Graph on 5 vertices 

 

#. A NetworkX graph:: 

 

sage: import networkx 

sage: g = networkx.Graph({0:[1,2,3], 2:[4]}) 

sage: DiGraph(g) 

Digraph on 5 vertices 

 

#. An igraph Graph (see also 

:meth:`~sage.graphs.generic_graph.GenericGraph.igraph_graph`):: 

 

sage: import igraph # optional - python_igraph 

sage: g = igraph.Graph([(0,1),(0,2)]) # optional - python_igraph 

sage: Graph(g) # optional - python_igraph 

Graph on 3 vertices 

 

If ``vertex_labels`` is ``True``, the names of the vertices are given by 

the vertex attribute ``'name'``, if available:: 

 

sage: g = igraph.Graph([(0,1),(0,2)], vertex_attrs={'name':['a','b','c']}) # optional - python_igraph 

sage: Graph(g).vertices() # optional - python_igraph 

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

sage: g = igraph.Graph([(0,1),(0,2)], vertex_attrs={'label':['a','b','c']}) # optional - python_igraph 

sage: Graph(g).vertices() # optional - python_igraph 

[0, 1, 2] 

 

If the igraph Graph has edge attributes, they are used as edge labels:: 

 

sage: g = igraph.Graph([(0,1),(0,2)], edge_attrs={'name':['a','b'], 'weight':[1,3]}) # optional - python_igraph 

sage: Graph(g).edges() # optional - python_igraph 

[(0, 1, {'name': 'a', 'weight': 1}), (0, 2, {'name': 'b', 'weight': 3})] 

 

 

When defining an undirected graph from a function ``f``, it is *very* 

important that ``f`` be symmetric. If it is not, anything can happen:: 

 

sage: f_sym = lambda x,y : abs(x-y) == 1 

sage: f_nonsym = lambda x,y : (x-y) == 1 

sage: G_sym = Graph([[4,6,1,5,3,7,2,0], f_sym]) 

sage: G_sym.is_isomorphic(graphs.PathGraph(8)) 

True 

sage: G_nonsym = Graph([[4,6,1,5,3,7,2,0], f_nonsym]) 

sage: G_nonsym.size() 

4 

sage: G_nonsym.is_isomorphic(G_sym) 

False 

 

By default, graphs are mutable and can thus not be used as a dictionary 

key:: 

 

sage: G = graphs.PetersenGraph() 

sage: {G:1}[G] 

Traceback (most recent call last): 

... 

TypeError: This graph is mutable, and thus not hashable. Create an immutable copy by `g.copy(immutable=True)` 

 

When providing the optional arguments ``data_structure="static_sparse"`` 

or ``immutable=True`` (both mean the same), then an immutable graph 

results. :: 

 

sage: G_imm = Graph(G, immutable=True) 

sage: H_imm = Graph(G, data_structure='static_sparse') 

sage: G_imm == H_imm == G 

True 

sage: {G_imm:1}[H_imm] 

1 

 

TESTS:: 

 

sage: Graph(4,format="HeyHeyHey") 

Traceback (most recent call last): 

... 

ValueError: Unknown input format 'HeyHeyHey' 

 

sage: Graph(igraph.Graph(directed=True)) # optional - python_igraph 

Traceback (most recent call last): 

... 

ValueError: An *undirected* igraph graph was expected. To build an directed graph, call the DiGraph constructor. 

 

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

sage: Graph(m,format="seidel_adjacency_matrix") 

Graph on 2 vertices 

sage: m[0,1]=1 

sage: Graph(m,format="seidel_adjacency_matrix") 

Traceback (most recent call last): 

... 

ValueError: Graph's Seidel adjacency matrix must be symmetric 

 

sage: m[0,1]=-1; m[1,1]=1 

sage: Graph(m,format="seidel_adjacency_matrix") 

Traceback (most recent call last): 

... 

ValueError: Graph's Seidel adjacency matrix must have 0s on the main diagonal 

 

From a a list of vertices and a list of edges:: 

 

sage: G = Graph([[1,2,3],[(1,2)]]); G 

Graph on 3 vertices 

sage: G.edges() 

[(1, 2, None)] 

""" 

_directed = False 

 

def __init__(self, data=None, pos=None, loops=None, format=None, 

weighted=None, implementation='c_graph', 

data_structure="sparse", vertex_labels=True, name=None, 

multiedges=None, convert_empty_dict_labels_to_None=None, 

sparse=True, immutable=False): 

""" 

TESTS:: 

 

sage: G = Graph() 

sage: loads(dumps(G)) == G 

True 

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

sage: Graph(a).adjacency_matrix() == a 

True 

 

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

sage: Graph(a,sparse=True).adjacency_matrix() == a 

True 

 

The positions are copied when the graph is built from another graph :: 

 

sage: g = graphs.PetersenGraph() 

sage: h = Graph(g) 

sage: g.get_pos() == h.get_pos() 

True 

 

The position dictionary is not the input one (:trac:`22424`):: 

 

sage: my_pos = {0:(0,0), 1:(1,1)} 

sage: G = Graph([[0,1], [(0,1)]], pos=my_pos) 

sage: my_pos == G._pos 

True 

sage: my_pos is G._pos 

False 

 

Or from a DiGraph :: 

 

sage: d = DiGraph(g) 

sage: h = Graph(d) 

sage: g.get_pos() == h.get_pos() 

True 

 

Loops are not counted as multiedges (see :trac:`11693`) and edges are 

not counted twice :: 

 

sage: Graph({1:[1]}).num_edges() 

1 

sage: Graph({1:[2,2]}).num_edges() 

2 

 

An empty list or dictionary defines a simple graph 

(:trac:`10441` and :trac:`12910`):: 

 

sage: Graph([]) 

Graph on 0 vertices 

sage: Graph({}) 

Graph on 0 vertices 

sage: # not "Multi-graph on 0 vertices" 

 

Verify that the int format works as expected (:trac:`12557`):: 

 

sage: Graph(2).adjacency_matrix() 

[0 0] 

[0 0] 

sage: Graph(3) == Graph(3,format='int') 

True 

 

Problem with weighted adjacency matrix (:trac:`13919`):: 

 

sage: B = {0:{1:2,2:5,3:4},1:{2:2,4:7},2:{3:1,4:4,5:3},3:{5:4},4:{5:1,6:5},5:{6:7}} 

sage: grafo3 = Graph(B,weighted=True) 

sage: matad = grafo3.weighted_adjacency_matrix() 

sage: grafo4 = Graph(matad,format = "adjacency_matrix", weighted=True) 

sage: grafo4.shortest_path(0,6,by_weight=True) 

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

 

Graphs returned when setting ``immutable=False`` are mutable:: 

 

sage: g = graphs.PetersenGraph() 

sage: g = Graph(g.edges(),immutable=False) 

sage: g.add_edge("Hey", "Heyyyyyyy") 

 

And their name is set:: 

 

sage: g = graphs.PetersenGraph() 

sage: Graph(g, immutable=True) 

Petersen graph: Graph on 10 vertices 

 

Check error messages for graphs built from incidence matrices (see 

:trac:`18440`):: 

 

sage: Graph(matrix([[-1, 1, 0],[1, 0, 0]])) 

Traceback (most recent call last): 

... 

ValueError: Column 1 of the (oriented) incidence matrix contains 

only one nonzero value 

sage: Graph(matrix([[1,1],[1,1],[1,0]])) 

Traceback (most recent call last): 

... 

ValueError: There must be one or two nonzero entries per column in an incidence matrix. Got entries [1, 1, 1] in column 0 

sage: Graph(matrix([[3,1,1],[0,1,1]])) 

Traceback (most recent call last): 

... 

ValueError: Each column of a non-oriented incidence matrix must sum 

to 2, but column 0 does not 

""" 

GenericGraph.__init__(self) 

 

from sage.structure.element import is_Matrix 

 

if sparse is False: 

if data_structure != "sparse": 

raise ValueError("The 'sparse' argument is an alias for " 

"'data_structure'. Please do not define both.") 

data_structure = "dense" 

 

# Choice of the backend 

 

if implementation != 'c_graph': 

deprecation(18375,"The 'implementation' keyword is deprecated, " 

"and the graphs has been stored as a 'c_graph'") 

 

if multiedges or weighted: 

if data_structure == "dense": 

raise RuntimeError("Multiedge and weighted c_graphs must be sparse.") 

if immutable: 

data_structure = 'static_sparse' 

 

# If the data structure is static_sparse, we first build a graph 

# using the sparse data structure, then reencode the resulting graph 

# as a static sparse graph. 

from sage.graphs.base.sparse_graph import SparseGraphBackend 

from sage.graphs.base.dense_graph import DenseGraphBackend 

if data_structure in ["sparse", "static_sparse"]: 

CGB = SparseGraphBackend 

elif data_structure == "dense": 

CGB = DenseGraphBackend 

else: 

raise ValueError("data_structure must be equal to 'sparse', " 

"'static_sparse' or 'dense'") 

self._backend = CGB(0, directed=False) 

 

if format is None and isinstance(data, str): 

if data.startswith(">>graph6<<"): 

data = data[10:] 

format = 'graph6' 

elif data.startswith(">>sparse6<<"): 

data = data[11:] 

format = 'sparse6' 

elif data[0] == ':': 

format = 'sparse6' 

else: 

format = 'graph6' 

if format is None and is_Matrix(data): 

if data.is_symmetric(): 

format = 'adjacency_matrix' 

else: 

format = 'incidence_matrix' 

if format is None and isinstance(data, Graph): 

format = 'Graph' 

from sage.graphs.all import DiGraph 

if format is None and isinstance(data, DiGraph): 

data = data.to_undirected() 

format = 'Graph' 

if (format is None and 

isinstance(data,list) and 

len(data)>=2 and 

callable(data[1])): 

format = 'rule' 

 

if (format is None and 

isinstance(data,list) and 

len(data) == 2 and 

isinstance(data[0],list) and # a list of two lists, the second of 

isinstance(data[1],list) and # which contains iterables (the edges) 

(not data[1] or callable(getattr(data[1][0],"__iter__",None)))): 

format = "vertices_and_edges" 

 

if format is None and isinstance(data, dict): 

if not data: 

format = 'dict_of_dicts' 

else: 

val = next(iter(data.values())) 

if isinstance(val, list): 

format = 'dict_of_lists' 

elif isinstance(val, dict): 

format = 'dict_of_dicts' 

if format is None and hasattr(data, 'adj'): 

import networkx 

if isinstance(data, (networkx.DiGraph, networkx.MultiDiGraph)): 

data = data.to_undirected() 

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

format = 'NX' 

 

if (format is None and 

hasattr(data, 'vcount') and 

hasattr(data, 'get_edgelist')): 

try: 

import igraph 

except ImportError: 

raise ImportError("The data seems to be a igraph object, but "+ 

"igraph is not installed in Sage. To install "+ 

"it, run 'sage -i python_igraph'") 

if format is None and isinstance(data, igraph.Graph): 

format = 'igraph' 

if format is None and isinstance(data, (int, Integer)): 

format = 'int' 

if format is None and data is None: 

format = 'int' 

data = 0 

 

# Input is a list of edges 

if format is None and isinstance(data,list): 

format = "list_of_edges" 

if weighted is None: weighted = False 

num_verts=0 

 

if format is None: 

raise ValueError("This input cannot be turned into a graph") 

 

if format == 'weighted_adjacency_matrix': 

if weighted is False: 

raise ValueError("Format was weighted_adjacency_matrix but weighted was False.") 

if weighted is None: weighted = True 

if multiedges is None: multiedges = False 

format = 'adjacency_matrix' 

 

# At this point, 'format' has been set. We build the graph 

 

if format == 'graph6': 

if weighted is None: weighted = False 

self.allow_loops(loops if loops else False, check=False) 

self.allow_multiple_edges(multiedges if multiedges else False, check=False) 

from .graph_input import from_graph6 

from_graph6(self, data) 

 

elif format == 'sparse6': 

if weighted is None: weighted = False 

self.allow_loops(False if loops is False else True, check=False) 

self.allow_multiple_edges(False if multiedges is False else True, check=False) 

from .graph_input import from_sparse6 

from_sparse6(self, data) 

 

elif format == 'adjacency_matrix': 

from .graph_input import from_adjacency_matrix 

from_adjacency_matrix(self, data, loops=loops, multiedges=multiedges, weighted=weighted) 

 

elif format == 'incidence_matrix': 

from .graph_input import from_incidence_matrix 

from_incidence_matrix(self, data, loops=loops, multiedges=multiedges, weighted=weighted) 

 

elif format == 'seidel_adjacency_matrix': 

multiedges = False 

weighted = False 

loops = False 

self.allow_loops(False) 

self.allow_multiple_edges(False) 

from .graph_input import from_seidel_adjacency_matrix 

from_seidel_adjacency_matrix(self, data) 

elif format == 'Graph': 

if loops is None: loops = data.allows_loops() 

if multiedges is None: multiedges = data.allows_multiple_edges() 

if weighted is None: weighted = data.weighted() 

self.allow_loops(loops, check=False) 

self.allow_multiple_edges(multiedges, check=False) 

if data.get_pos() is not None: 

pos = data.get_pos() 

self.name(data.name()) 

self.add_vertices(data.vertex_iterator()) 

self.add_edges(data.edge_iterator(), loops=loops) 

elif format == 'NX': 

if convert_empty_dict_labels_to_None is not False: 

r = lambda x:None if x=={} else x 

else: 

r = lambda x:x 

if weighted is None: 

if isinstance(data, networkx.Graph): 

weighted = False 

if multiedges is None: 

multiedges = False 

if loops is None: 

loops = False 

else: 

weighted = True 

if multiedges is None: 

multiedges = True 

if loops is None: 

loops = True 

self.allow_loops(loops, check=False) 

self.allow_multiple_edges(multiedges, check=False) 

self.add_vertices(data.nodes()) 

self.add_edges((u,v,r(l)) for u,v,l in data.edges_iter(data=True)) 

elif format == 'igraph': 

if data.is_directed(): 

raise ValueError("An *undirected* igraph graph was expected. "+ 

"To build an directed graph, call the DiGraph "+ 

"constructor.") 

 

self.add_vertices(range(data.vcount())) 

self.add_edges([(e.source, e.target, e.attributes()) for e in data.es()]) 

 

if vertex_labels and 'name' in data.vertex_attributes(): 

vs = data.vs() 

self.relabel({v:vs[v]['name'] for v in self}) 

 

elif format == 'rule': 

f = data[1] 

verts = data[0] 

if loops is None: loops = any(f(v,v) for v in verts) 

if weighted is None: weighted = False 

self.allow_loops(loops, check=False) 

self.allow_multiple_edges(True if multiedges else False, check=False) 

from itertools import combinations 

self.add_vertices(verts) 

self.add_edges(e for e in combinations(verts,2) if f(*e)) 

if loops: 

self.add_edges((v,v) for v in verts if f(v,v)) 

 

elif format == "vertices_and_edges": 

self.allow_multiple_edges(bool(multiedges), check=False) 

self.allow_loops(bool(loops), check=False) 

self.add_vertices(data[0]) 

self.add_edges(data[1]) 

 

elif format == 'dict_of_dicts': 

from .graph_input import from_dict_of_dicts 

from_dict_of_dicts(self, data, loops=loops, multiedges=multiedges, weighted=weighted, 

convert_empty_dict_labels_to_None = False if convert_empty_dict_labels_to_None is None else convert_empty_dict_labels_to_None) 

 

elif format == 'dict_of_lists': 

from .graph_input import from_dict_of_lists 

from_dict_of_lists(self, data, loops=loops, multiedges=multiedges, weighted=weighted) 

 

elif format == 'int': 

self.allow_loops(loops if loops else False, check=False) 

self.allow_multiple_edges(multiedges if multiedges else False, check=False) 

if data<0: 

raise ValueError("The number of vertices cannot be strictly negative!") 

if data: 

self.add_vertices(range(data)) 

 

elif format == 'list_of_edges': 

self.allow_multiple_edges(False if multiedges is False else True, check=False) 

self.allow_loops(False if loops is False else True, check=False) 

self.add_edges(data) 

if multiedges is not True and self.has_multiple_edges(): 

deprecation(15706, "You created a graph with multiple edges " 

"from a list. Please set 'multiedges' to 'True' " 

"when you do so, as in the future the default " 

"behaviour will be to ignore those edges") 

elif multiedges is None: 

self.allow_multiple_edges(False, check=False) 

 

if loops is not True and self.has_loops(): 

deprecation(15706, "You created a graph with loops from a list. "+ 

"Please set 'loops' to 'True' when you do so, as in "+ 

"the future the default behaviour will be to ignore "+ 

"those edges") 

elif loops is None: 

self.allow_loops(False, check=False) 

else: 

raise ValueError("Unknown input format '{}'".format(format)) 

 

if weighted is None: weighted = False 

self._weighted = getattr(self,'_weighted',weighted) 

 

self._pos = copy(pos) 

 

if format != 'Graph' or name is not None: 

self.name(name) 

 

if data_structure == "static_sparse": 

from sage.graphs.base.static_sparse_backend import StaticSparseBackend 

ib = StaticSparseBackend(self, 

loops = self.allows_loops(), 

multiedges = self.allows_multiple_edges()) 

self._backend = ib 

self._immutable = True 

 

### Formats 

 

@doc_index("Basic methods") 

def graph6_string(self): 

""" 

Return the graph6 representation of the graph as an ASCII string. 

 

This is only valid for simple (no loops, no multiple edges) graphs 

on at most `2^{18}-1=262143` vertices. 

 

.. NOTE:: 

 

As the graph6 format only handles graphs with vertex set 

`\{0,...,n-1\}`, a :meth:`relabelled copy 

<sage.graphs.generic_graph.GenericGraph.relabel>` will 

be encoded, if necessary. 

 

.. SEEALSO:: 

 

* :meth:`~sage.graphs.digraph.DiGraph.dig6_string` -- 

a similar string format for directed graphs 

 

EXAMPLES:: 

 

sage: G = graphs.KrackhardtKiteGraph() 

sage: G.graph6_string() 

'IvUqwK@?G' 

 

TESTS:: 

 

sage: Graph().graph6_string() 

'?' 

""" 

n = self.order() 

if n > 262143: 

raise ValueError('graph6 format supports graphs on 0 to 262143 vertices only.') 

elif self.has_loops() or self.has_multiple_edges(): 

raise ValueError('graph6 format supports only simple graphs (no loops, no multiple edges)') 

else: 

return generic_graph_pyx.small_integer_to_graph6(n) + generic_graph_pyx.binary_string_to_graph6(self._bit_vector()) 

 

@doc_index("Basic methods") 

def sparse6_string(self): 

r""" 

Return the sparse6 representation of the graph as an ASCII string. 

 

Only valid for undirected graphs on 0 to 262143 vertices, but loops 

and multiple edges are permitted. 

 

.. NOTE:: 

 

As the sparse6 format only handles graphs whose vertex set is 

`\{0,...,n-1\}`, a :meth:`relabelled copy 

<sage.graphs.generic_graph.GenericGraph.relabel>` of your graph will 

be encoded if necessary. 

 

EXAMPLES:: 

 

sage: G = graphs.BullGraph() 

sage: G.sparse6_string() 

':Da@en' 

 

:: 

 

sage: G = Graph(loops=True, multiedges=True,data_structure="sparse") 

sage: Graph(':?',data_structure="sparse") == G 

True 

 

TESTS:: 

 

sage: G = Graph() 

sage: G.sparse6_string() 

':?' 

 

Check that :trac:`18445` is fixed:: 

 

sage: Graph(graphs.KneserGraph(5,2).sparse6_string()).size() 

15 

 

Graphs with 1 vertex are correctly handled (:trac:`24923`):: 

 

sage: Graph([(0, 0)], loops=True).sparse6_string() 

':@^' 

sage: G = Graph(_) 

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

(1, 1) 

sage: Graph([(0, 0), (0, 0)], loops=True, multiedges=True).sparse6_string() 

':@N' 

sage: H = Graph(_) 

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

(1, 2) 

""" 

n = self.order() 

if n == 0: 

return ':?' 

if n > 262143: 

raise ValueError('sparse6 format supports graphs on 0 to 262143 vertices only.') 

if n == 1: 

s = '0' * self.size() 

else: 

v_to_int = {v:i for i,v in enumerate(self.vertices())} 

edges = [sorted((v_to_int[u],v_to_int[v])) for u,v in self.edge_iterator(labels=False)] 

edges.sort(key=lambda e: (e[1],e[0])) # reverse lexicographic order 

 

# encode bit vector 

k = int((ZZ(n) - 1).nbits()) 

v = 0 

i = 0 

m = 0 

s = '' 

while m < len(edges): 

if edges[m][1] > v + 1: 

sp = generic_graph_pyx.int_to_binary_string(edges[m][1]) 

sp = '0'*(k-len(sp)) + sp 

s += '1' + sp 

v = edges[m][1] 

elif edges[m][1] == v + 1: 

sp = generic_graph_pyx.int_to_binary_string(edges[m][0]) 

sp = '0'*(k-len(sp)) + sp 

s += '1' + sp 

v += 1 

m += 1 

else: 

sp = generic_graph_pyx.int_to_binary_string(edges[m][0]) 

sp = '0'*(k-len(sp)) + sp 

s += '0' + sp 

m += 1 

 

# encode s as a 6-string, as in R(x), but padding with 1's 

# pad on the right to make a multiple of 6 

s = s + ( '1' * ((6 - len(s))%6) ) 

 

# split into groups of 6, and convert numbers to decimal, adding 63 

six_bits = '' 

for i in range(0, len(s), 6): 

six_bits += chr( int( s[i:i+6], 2) + 63 ) 

return ':' + generic_graph_pyx.small_integer_to_graph6(n) + six_bits 

 

### Attributes 

 

@doc_index("Basic methods") 

def is_directed(self): 

""" 

Since graph is undirected, returns False. 

 

EXAMPLES:: 

 

sage: Graph().is_directed() 

False 

""" 

return False 

 

@doc_index("Connectivity, orientations, trees") 

def bridges(self, labels=True): 

r""" 

Returns a list of the bridges (or cut edges). 

 

A bridge is an edge whose deletion disconnects the graph. 

A disconnected graph has no bridge. 

 

INPUT: 

 

- ``labels`` -- (default: ``True``) if ``False``, each bridge is a tuple 

`(u, v)` of vertices 

 

EXAMPLES:: 

 

sage: g = 2*graphs.PetersenGraph() 

sage: g.add_edge(1,10) 

sage: g.is_connected() 

True 

sage: g.bridges() 

[(1, 10, None)] 

 

TESTS: 

 

Ticket :trac:`23817` is solved:: 

 

sage: G = Graph() 

sage: G.add_edge(0, 1) 

sage: G.bridges() 

[(0, 1, None)] 

sage: G.allow_loops(True) 

sage: G.add_edge(0, 0) 

sage: G.add_edge(1, 1) 

sage: G.bridges() 

[(0, 1, None)] 

""" 

# Small graphs and disconnected graphs have no bridge 

if self.order() < 2 or not self.is_connected(): 

return [] 

 

B,C = self.blocks_and_cut_vertices() 

 

# A block of size 2 is a bridge, unless the vertices are connected with 

# multiple edges. 

ME = set(self.multiple_edges(labels=False)) 

my_bridges = [] 

for b in B: 

if len(b) == 2 and not tuple(b) in ME: 

if labels: 

my_bridges.append((b[0], b[1], self.edge_label(b[0], b[1]))) 

else: 

my_bridges.append(tuple(b)) 

 

return my_bridges 

 

@doc_index("Connectivity, orientations, trees") 

def spanning_trees(self): 

""" 

Returns a list of all spanning trees. 

 

If the graph is disconnected, returns the empty list. 

 

Uses the Read-Tarjan backtracking algorithm [RT75]_. 

 

EXAMPLES:: 

 

sage: G = Graph([(1,2),(1,2),(1,3),(1,3),(2,3),(1,4)],multiedges=True) 

sage: len(G.spanning_trees()) 

8 

sage: G.spanning_trees_count() 

8 

sage: G = Graph([(1,2),(2,3),(3,1),(3,4),(4,5),(4,5),(4,6)],multiedges=True) 

sage: len(G.spanning_trees()) 

6 

sage: G.spanning_trees_count() 

6 

 

.. SEEALSO:: 

 

- :meth:`~sage.graphs.generic_graph.GenericGraph.spanning_trees_count` 

-- counts the number of spanning trees. 

 

- :meth:`~sage.graphs.graph.Graph.random_spanning_tree` 

-- returns a random spanning tree. 

 

TESTS: 

 

Works with looped graphs:: 

 

sage: g = Graph({i:[i,(i+1)%6] for i in range(6)}) 

sage: g.spanning_trees() 

[Graph on 6 vertices, 

Graph on 6 vertices, 

Graph on 6 vertices, 

Graph on 6 vertices, 

Graph on 6 vertices, 

Graph on 6 vertices] 

 

REFERENCES: 

 

.. [RT75] Read, R. C. and Tarjan, R. E. 

Bounds on Backtrack Algorithms for Listing Cycles, Paths, and Spanning Trees 

Networks, Volume 5 (1975), numer 3, pages 237-252. 

""" 

 

def _recursive_spanning_trees(G,forest): 

""" 

Returns all the spanning trees of G containing forest 

""" 

if not G.is_connected(): 

return [] 

 

if G.size() == forest.size(): 

return [forest.copy()] 

else: 

# Pick an edge e from G-forest 

for e in G.edge_iterator(labels=False): 

if not forest.has_edge(e): 

break 

 

# 1) Recursive call with e removed from G 

G.delete_edge(e) 

trees = _recursive_spanning_trees(G,forest) 

G.add_edge(e) 

 

# 2) Recursive call with e include in forest 

# 

# e=xy links the CC (connected component) of forest containing x 

# with the CC containing y. Any other edge which does that 

# cannot be added to forest anymore, and B is the list of them 

c1 = forest.connected_component_containing_vertex(e[0]) 

c2 = forest.connected_component_containing_vertex(e[1]) 

G.delete_edge(e) 

B = G.edge_boundary(c1,c2,sort=False) 

G.add_edge(e) 

 

# Actual call 

forest.add_edge(e) 

G.delete_edges(B) 

trees.extend(_recursive_spanning_trees(G,forest)) 

G.add_edges(B) 

forest.delete_edge(e) 

 

return trees 

 

if self.is_connected() and len(self): 

forest = Graph([]) 

forest.add_vertices(self.vertices()) 

forest.add_edges(self.bridges()) 

return _recursive_spanning_trees(Graph(self,immutable=False,loops=False), forest) 

else: 

return [] 

 

### Properties 

@doc_index("Graph properties") 

def is_tree(self, certificate=False, output='vertex'): 

""" 

Tests if the graph is a tree 

 

The empty graph is defined to be not a tree. 

 

INPUT: 

 

- ``certificate`` (boolean) -- whether to return a certificate. The 

method only returns boolean answers when ``certificate = False`` 

(default). When it is set to ``True``, it either answers ``(True, 

None)`` when the graph is a tree and ``(False, cycle)`` when it 

contains a cycle. It returns ``(False, None)`` when the graph is 

empty or not connected. 

 

- ``output`` (``'vertex'`` (default) or ``'edge'``) -- whether the 

certificate is given as a list of vertices or a list of 

edges. 

 

When the certificate cycle is given as a list of edges, the 

edges are given as `(v_i, v_{i+1}, l)` where `v_1, v_2, \dots, 

v_n` are the vertices of the cycles (in their cyclic order). 

 

EXAMPLES:: 

 

sage: all(T.is_tree() for T in graphs.trees(15)) 

True 

 

With certificates:: 

 

sage: g = graphs.RandomTree(30) 

sage: g.is_tree(certificate=True) 

(True, None) 

sage: g.add_edge(10,-1) 

sage: g.add_edge(11,-1) 

sage: isit, cycle = g.is_tree(certificate=True) 

sage: isit 

False 

sage: -1 in cycle 

True 

 

One can also ask for the certificate as a list of edges:: 

 

sage: g = graphs.CycleGraph(4) 

sage: g.is_tree(certificate=True, output='edge') 

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

 

This is useful for graphs with multiple edges:: 

 

sage: G = Graph([(1, 2, 'a'), (1, 2, 'b')], multiedges=True) 

sage: G.is_tree(certificate=True) 

(False, [1, 2]) 

sage: G.is_tree(certificate=True, output='edge') 

(False, [(1, 2, 'a'), (2, 1, 'b')]) 

 

TESTS: 

 

:trac:`14434` is fixed:: 

 

sage: g = Graph({0:[1,4,5],3:[4,8,9],4:[9],5:[7,8],7:[9]}) 

sage: _,cycle = g.is_tree(certificate=True) 

sage: g.size() 

10 

sage: g.add_cycle(cycle) 

sage: g.size() 

10 

 

The empty graph:: 

 

sage: graphs.EmptyGraph().is_tree() 

False 

sage: graphs.EmptyGraph().is_tree(certificate=True) 

(False, None) 

 

:trac:`22912` is fixed:: 

 

sage: G = Graph([(0,0), (0,1)], loops=True) 

sage: G.is_tree(certificate=True) 

(False, [0]) 

sage: G.is_tree(certificate=True, output='edge') 

(False, [(0, 0, None)]) 

""" 

if not output in ['vertex', 'edge']: 

raise ValueError('output must be either vertex or edge') 

 

if self.order() == 0 or not self.is_connected(): 

return (False, None) if certificate else False 

 

if certificate: 

if self.num_verts() == self.num_edges() + 1: 

return (True, None) 

 

if self.allows_loops(): 

L = self.loop_edges() if output=='edge' else self.loop_vertices() 

if L: 

return False, L[:1] 

 

if self.has_multiple_edges(): 

if output == 'vertex': 

return (False, list(self.multiple_edges()[0][:2])) 

edge1, edge2 = self.multiple_edges()[:2] 

if edge1[0] != edge2[0]: 

return (False, [edge1, edge2]) 

return (False, [edge1, (edge2[1], edge2[0], edge2[2])]) 

 

if output == 'edge': 

if self.allows_multiple_edges(): 

def vertices_to_edges(x): 

return [(u[0], u[1], self.edge_label(u[0], u[1])[0]) 

for u in zip(x, x[1:] + [x[0]])] 

else: 

def vertices_to_edges(x): 

return [(u[0], u[1], self.edge_label(u[0], u[1])) 

for u in zip(x, x[1:] + [x[0]])] 

 

# This code is a depth-first search that looks for a cycle in the 

# graph. We *know* it exists as there are too many edges around. 

n = self.order() 

seen = {} 

u = next(self.vertex_iterator()) 

seen[u] = u 

stack = [(u, v) for v in self.neighbor_iterator(u)] 

while stack: 

u, v = stack.pop(-1) 

if v in seen: 

continue 

for w in self.neighbors(v): 

if u == w: 

continue 

elif w in seen: 

cycle = [v, w] 

while u != w: 

cycle.insert(0, u) 

u = seen[u] 

if output == 'vertex': 

return (False, cycle) 

return (False, vertices_to_edges(cycle)) 

else: 

stack.append((v, w)) 

seen[v] = u 

 

else: 

return self.num_verts() == self.num_edges() + 1 

 

@doc_index("Graph properties") 

def is_forest(self, certificate=False, output='vertex'): 

""" 

Tests if the graph is a forest, i.e. a disjoint union of trees. 

 

INPUT: 

 

- ``certificate`` (boolean) -- whether to return a certificate. The 

method only returns boolean answers when ``certificate = False`` 

(default). When it is set to ``True``, it either answers ``(True, 

None)`` when the graph is a forest and ``(False, cycle)`` when it 

contains a cycle. 

 

- ``output`` (``'vertex'`` (default) or ``'edge'``) -- whether the 

certificate is given as a list of vertices or a list of 

edges. 

 

EXAMPLES:: 

 

sage: seven_acre_wood = sum(graphs.trees(7), Graph()) 

sage: seven_acre_wood.is_forest() 

True 

 

With certificates:: 

 

sage: g = graphs.RandomTree(30) 

sage: g.is_forest(certificate=True) 

(True, None) 

sage: (2*g + graphs.PetersenGraph() + g).is_forest(certificate=True) 

(False, [62, 63, 68, 66, 61]) 

""" 

number_of_connected_components = len(self.connected_components()) 

isit = (self.num_verts() == 

self.num_edges() + number_of_connected_components) 

 

if not certificate: 

return isit 

else: 

if isit: 

return (True, None) 

# The graph contains a cycle, and the user wants to see it. 

 

# No need to copy the graph 

if number_of_connected_components == 1: 

return self.is_tree(certificate=True, output=output) 

 

# We try to find a cycle in each connected component 

for gg in self.connected_components_subgraphs(): 

isit, cycle = gg.is_tree(certificate=True, output=output) 

if not isit: 

return (False, cycle) 

 

@doc_index("Graph properties") 

def is_cactus(self): 

""" 

Check whether the graph is cactus graph. 

 

A graph is called *cactus graph* if it is connected and every pair of 

simple cycles have at most one common vertex. 

 

There are other definitions, see :wikipedia:`Cactus_graph`. 

 

EXAMPLES:: 

 

sage: g = Graph({1: [2], 2: [3, 4], 3: [4, 5, 6, 7], 8: [3, 5], 9: [6, 7]}) 

sage: g.is_cactus() 

True 

 

sage: c6 = graphs.CycleGraph(6) 

sage: naphthalene = c6 + c6 

sage: naphthalene.is_cactus() # Not connected 

False 

sage: naphthalene.merge_vertices([0, 6]) 

sage: naphthalene.is_cactus() 

True 

sage: naphthalene.merge_vertices([1, 7]) 

sage: naphthalene.is_cactus() 

False 

 

TESTS:: 

 

sage: all(graphs.PathGraph(i).is_cactus() for i in range(5)) 

True 

 

sage: Graph('Fli@?').is_cactus() 

False 

 

Test a graph that is not outerplanar, see :trac:`24480`:: 

 

sage: graphs.Balaban10Cage().is_cactus() 

False 

""" 

self._scream_if_not_simple() 

 

# Special cases 

if self.order() < 4: 

return True 

 

# Every cactus graph is outerplanar 

if not self.is_circular_planar(): 

return False 

 

if not self.is_connected(): 

return False 

 

# the number of faces is 1 plus the number of blocks of order > 2 

B = self.blocks_and_cut_vertices()[0] 

return len(self.faces()) == sum(1 for b in B if len(b) > 2) + 1 

 

@doc_index("Graph properties") 

def is_biconnected(self): 

""" 

Test if the graph is biconnected. 

 

A biconnected graph is a connected graph on two or more vertices that is 

not broken into disconnected pieces by deleting any single vertex. 

 

.. SEEALSO:: 

 

- :meth:`~sage.graphs.generic_graph.GenericGraph.is_connected` 

- :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cut_vertices` 

- :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cuts_tree` 

- :wikipedia:`Biconnected_graph` 

 

EXAMPLES:: 

 

sage: G = graphs.PetersenGraph() 

sage: G.is_biconnected() 

True 

sage: G.add_path([0,'a','b']) 

sage: G.is_biconnected() 

False 

sage: G.add_edge('b', 1) 

sage: G.is_biconnected() 

True 

 

TESTS:: 

 

sage: Graph().is_biconnected() 

False 

sage: Graph(1).is_biconnected() 

False 

sage: graphs.CompleteGraph(2).is_biconnected() 

True 

""" 

if self.order() < 2 or not self.is_connected(): 

return False 

if self.blocks_and_cut_vertices()[1]: 

return False 

return True 

 

@doc_index("Graph properties") 

def is_block_graph(self): 

r""" 

Return whether this graph is a block graph. 

 

A block graph is a connected graph in which every biconnected component 

(block) is a clique. 

 

.. SEEALSO:: 

 

- :wikipedia:`Block_graph` for more details on these graphs 

- :meth:`~sage.graphs.graph_generators.GraphGenerators.RandomBlockGraph` 

-- generator of random block graphs 

- :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cut_vertices` 

- :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cuts_tree` 

 

 

EXAMPLES:: 

 

sage: G = graphs.RandomBlockGraph(6, 2, kmax=4) 

sage: G.is_block_graph() 

True 

sage: from sage.graphs.isgci import graph_classes 

sage: G in graph_classes.Block 

True 

sage: graphs.CompleteGraph(4).is_block_graph() 

True 

sage: graphs.RandomTree(6).is_block_graph() 

True 

sage: graphs.PetersenGraph().is_block_graph() 

False 

sage: Graph(4).is_block_graph() 

False 

""" 

if not self.is_connected(): 

return False 

if self.is_clique(): 

return True 

 

B,C = self.blocks_and_cut_vertices() 

return all(self.is_clique(vertices=block) for block in B) 

 

@doc_index("Graph properties") 

def is_cograph(self): 

""" 

Check whether the graph is cograph. 

 

A cograph is defined recursively: the single-vertex graph is 

cograph, complement of cograph is cograph, and disjoint union 

of two cographs is cograph. There are many other 

characterizations, see :wikipedia:`Cograph`. 

 

EXAMPLES:: 

 

sage: graphs.HouseXGraph().is_cograph() 

True 

sage: graphs.HouseGraph().is_cograph() 

False 

 

.. TODO:: 

 

Implement faster recognition algorithm, as for instance 

the linear time recognition algorithm using LexBFS proposed 

in [Bre2008]_. 

 

TESTS:: 

 

sage: [graphs.PathGraph(i).is_cograph() for i in range(6)] 

[True, True, True, True, False, False] 

sage: graphs.CycleGraph(5).is_cograph() # Self-complemented 

False 

""" 

# A cograph has no 4-vertex path as an induced subgraph. 

# We will first try to "decompose" graph by complements and 

# split to connected components, and use fairly slow 

# subgraph search if that fails. 

self._scream_if_not_simple() 

if self.order() < 4: 

return True 

if self.density()*2 > 1: 

return self.complement().is_cograph() 

if not self.is_connected(): 

return all(part.is_cograph() for part in self.connected_components_subgraphs()) 

P4 = Graph({0: [1], 1: [2], 2: [3]}) 

return self.subgraph_search(P4, induced=True) is None 

 

@doc_index("Graph properties") 

def is_apex(self): 

""" 

Test if the graph is apex. 

 

A graph is apex if it can be made planar by the removal of a single 

vertex. The deleted vertex is called ``an apex`` of the graph, and a 

graph may have more than one apex. For instance, in the minimal 

nonplanar graphs `K_5` or `K_{3,3}`, every vertex is an apex. The apex 

graphs include graphs that are themselves planar, in which case again 

every vertex is an apex. The null graph is also counted as an apex graph 

even though it has no vertex to remove. If the graph is not connected, 

we say that it is apex if it has at most one non planar connected 

component and that this component is apex. See :wikipedia:`the 

wikipedia article on Apex graph <Apex_graph>` for more information. 

 

.. SEEALSO:: 

 

- :meth:`~Graph.apex_vertices` 

- :meth:`~sage.graphs.generic_graph.GenericGraph.is_planar` 

 

EXAMPLES: 

 

`K_5` and `K_{3,3}` are apex graphs, and each of their vertices is an 

apex:: 

 

sage: G = graphs.CompleteGraph(5) 

sage: G.is_apex() 

True 

sage: G = graphs.CompleteBipartiteGraph(3,3) 

sage: G.is_apex() 

True 

 

The Petersen graph is not apex:: 

 

sage: G = graphs.PetersenGraph() 

sage: G.is_apex() 

False 

 

A graph is apex if all its connected components are apex, but at most 

one is not planar:: 

 

sage: M = graphs.Grid2dGraph(3,3) 

sage: K5 = graphs.CompleteGraph(5) 

sage: (M+K5).is_apex() 

True 

sage: (M+K5+K5).is_apex() 

False 

 

TESTS: 

 

The null graph is apex:: 

 

sage: G = Graph() 

sage: G.is_apex() 

True 

 

The graph might be mutable or immutable:: 

 

sage: G = Graph(M+K5, immutable=True) 

sage: G.is_apex() 

True 

""" 

# Easy cases: null graph, subgraphs of K_5 and K_3,3 

if self.order() <= 5 or ( self.order() <= 6 and self.is_bipartite() ): 

return True 

 

return len(self.apex_vertices(k=1)) > 0 

 

@doc_index("Graph properties") 

def apex_vertices(self, k=None): 

""" 

Return the list of apex vertices. 

 

A graph is apex if it can be made planar by the removal of a single 

vertex. The deleted vertex is called ``an apex`` of the graph, and a 

graph may have more than one apex. For instance, in the minimal 

nonplanar graphs `K_5` or `K_{3,3}`, every vertex is an apex. The apex 

graphs include graphs that are themselves planar, in which case again 

every vertex is an apex. The null graph is also counted as an apex graph 

even though it has no vertex to remove. If the graph is not connected, 

we say that it is apex if it has at most one non planar connected 

component and that this component is apex. See :wikipedia:`the 

wikipedia article on Apex graph <Apex_graph>` for more information. 

 

.. SEEALSO:: 

 

- :meth:`~Graph.is_apex` 

- :meth:`~sage.graphs.generic_graph.GenericGraph.is_planar` 

 

INPUT: 

 

- ``k`` -- when set to ``None``, the method returns the list of all apex 

of the graph, possibly empty if the graph is not apex. When set to a 

positive integer, the method ends as soon as `k` apex vertices are 

found. 

 

OUTPUT: 

 

By default, the method returns the list of all apex of the graph. When 

parameter ``k`` is set to a positive integer, the returned list is 

bounded to `k` apex vertices. 

 

EXAMPLES: 

 

`K_5` and `K_{3,3}` are apex graphs, and each of their vertices is an 

apex:: 

 

sage: G = graphs.CompleteGraph(5) 

sage: G.apex_vertices() 

[0, 1, 2, 3, 4] 

sage: G = graphs.CompleteBipartiteGraph(3,3) 

sage: G.is_apex() 

True 

sage: G.apex_vertices() 

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

sage: G.apex_vertices(k=3) 

[0, 1, 2] 

 

A `4\\times 4`-grid is apex and each of its vertices is an apex. When 

adding a universal vertex, the resulting graph is apex and the universal 

vertex is the unique apex vertex :: 

 

sage: G = graphs.Grid2dGraph(4,4) 

sage: G.apex_vertices() == G.vertices() 

True 

sage: G.add_edges([('universal',v) for v in G.vertex_iterator()]) 

sage: G.apex_vertices() 

['universal'] 

 

The Petersen graph is not apex:: 

 

sage: G = graphs.PetersenGraph() 

sage: G.apex_vertices() 

[] 

 

A graph is apex if all its connected components are apex, but at most 

one is not planar:: 

 

sage: M = graphs.Grid2dGraph(3,3) 

sage: K5 = graphs.CompleteGraph(5) 

sage: (M+K5).apex_vertices() 

[9, 10, 11, 12, 13] 

sage: (M+K5+K5).apex_vertices() 

[] 

 

Neighbors of an apex of degree 2 are apex:: 

 

sage: G = graphs.Grid2dGraph(5,5) 

sage: G.add_path([(1,1),'x',(3,3)]) 

sage: G.is_planar() 

False 

sage: G.degree('x') 

2 

sage: G.apex_vertices() 

['x', (2, 2), (3, 3), (1, 1)] 

 

 

TESTS: 

 

The null graph is apex although it has no apex vertex:: 

 

sage: G = Graph() 

sage: G.apex_vertices() 

[] 

 

Parameter ``k`` cannot be a negative integer:: 

 

sage: G.apex_vertices(k=-1) 

Traceback (most recent call last): 

... 

ValueError: parameter k must be a non negative integer 

 

The graph might be mutable or immutable:: 

 

sage: G = Graph(M+K5, immutable=True) 

sage: G.apex_vertices() 

[9, 10, 11, 12, 13] 

""" 

if k is None: 

k = self.order() 

elif k < 0 : 

raise ValueError("parameter k must be a non negative integer") 

 

# Easy cases: null graph, subgraphs of K_5 and K_3,3 

if self.order() <= 5 or ( self.order() <= 6 and self.is_bipartite() ): 

return self.vertices()[:k] 

 

 

if not self.is_connected(): 

# We search for its non planar connected components. If it has more 

# than one such component, the graph is not apex. It is apex if 

# either it has no such component, in which case the graph is 

# planar, or if its unique non planar component is apex. 

 

P = [H for H in self.connected_components_subgraphs() if not H.is_planar()] 

if not P: # The graph is planar 

return self.vertices()[:k] 

elif len(P) > 1: 

return [] 

else: 

# We proceed with the non planar component 

H = Graph(P[0].edges(labels=0), immutable=False, loops=False, multiedges=False) if P[0].is_immutable() else P[0] 

 

elif self.is_planar(): 

# A planar graph is apex. 

return self.vertices()[:k] 

 

else: 

# We make a basic copy of the graph since we will modify it 

H = Graph(self.edges(labels=0), immutable=False, loops=False, multiedges=False) 

 

 

# General case: basic implementation 

# 

# Test for each vertex if the its removal makes the graph planar. 

# Obviously, we don't test vertices of degree one. Furthermore, if a 

# vertex of degree 2 is an apex, its neighbors also are. So we start 

# with vertices of degree 2. 

V = sorted([(d,u) for u,d in six.iteritems(H.degree(labels=True)) if d > 1]) 

apex = set() 

for deg,u in V: 

 

if u in apex: # True if neighbor of an apex of degree 2 

if deg == 2: 

# We ensure that its neighbors are known apex 

apex.update(H.neighbors(u)) 

if len(apex) >= k: 

return list(apex)[:k] 

continue 

 

E = H.edges_incident(u, labels=0) 

H.delete_vertex(u) 

if H.is_planar(): 

apex.add(u) 

if deg == 2: 

# The neighbors of an apex of degree 2 also are 

apex.update(self.neighbors(u)) 

 

if len(apex) >= k: 

return list(apex)[:k] 

 

H.add_edges(E) 

 

return list(apex) 

 

@doc_index("Graph properties") 

def is_overfull(self): 

r""" 

Tests whether the current graph is overfull. 

 

A graph `G` on `n` vertices and `m` edges is said to 

be overfull if: 

 

- `n` is odd 

 

- It satisfies `2m > (n-1)\Delta(G)`, where 

`\Delta(G)` denotes the maximum degree 

among all vertices in `G`. 

 

An overfull graph must have a chromatic index of `\Delta(G)+1`. 

 

EXAMPLES: 

 

A complete graph of order `n > 1` is overfull if and only if `n` is 

odd:: 

 

sage: graphs.CompleteGraph(6).is_overfull() 

False 

sage: graphs.CompleteGraph(7).is_overfull() 

True 

sage: graphs.CompleteGraph(1).is_overfull() 

False 

 

The claw graph is not overfull:: 

 

sage: from sage.graphs.graph_coloring import edge_coloring 

sage: g = graphs.ClawGraph() 

sage: g 

Claw graph: Graph on 4 vertices 

sage: edge_coloring(g, value_only=True) 

3 

sage: g.is_overfull() 

False 

 

The Holt graph is an example of a overfull graph:: 

 

sage: G = graphs.HoltGraph() 

sage: G.is_overfull() 

True 

 

Checking that all complete graphs `K_n` for even `0 \leq n \leq 100` 

are not overfull:: 

 

sage: def check_overfull_Kn_even(n): 

....: i = 0 

....: while i <= n: 

....: if graphs.CompleteGraph(i).is_overfull(): 

....: print("A complete graph of even order cannot be overfull.") 

....: return 

....: i += 2 

....: print("Complete graphs of even order up to %s are not overfull." % n) 

... 

sage: check_overfull_Kn_even(100) # long time 

Complete graphs of even order up to 100 are not overfull. 

 

The null graph, i.e. the graph with no vertices, is not overfull:: 

 

sage: Graph().is_overfull() 

False 

sage: graphs.CompleteGraph(0).is_overfull() 

False 

 

Checking that all complete graphs `K_n` for odd `1 < n \leq 100` 

are overfull:: 

 

sage: def check_overfull_Kn_odd(n): 

....: i = 3 

....: while i <= n: 

....: if not graphs.CompleteGraph(i).is_overfull(): 

....: print("A complete graph of odd order > 1 must be overfull.") 

....: return 

....: i += 2 

....: print("Complete graphs of odd order > 1 up to %s are overfull." % n) 

... 

sage: check_overfull_Kn_odd(100) # long time 

Complete graphs of odd order > 1 up to 100 are overfull. 

 

The Petersen Graph, though, is not overfull while 

its chromatic index is `\Delta+1`:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.is_overfull() 

False 

sage: from sage.graphs.graph_coloring import edge_coloring 

sage: max(g.degree()) + 1 == edge_coloring(g, value_only=True) 

True 

""" 

# # A possible optimized version. But the gain in speed is very little. 

# return bool(self._backend.num_verts() & 1) and ( # odd order n 

# 2 * self._backend.num_edges(self._directed) > #2m > \Delta(G)*(n-1) 

# max(self.degree()) * (self._backend.num_verts() - 1)) 

# unoptimized version 

return (self.order() % 2 == 1) and ( 

2 * self.size() > max(self.degree()) * (self.order() - 1)) 

 

@doc_index("Graph properties") 

def is_even_hole_free(self, certificate = False): 

r""" 

Tests whether ``self`` contains an induced even hole. 

 

A Hole is a cycle of length at least 4 (included). It is said 

to be even (resp. odd) if its length is even (resp. odd). 

 

Even-hole-free graphs always contain a bisimplicial vertex, 

which ensures that their chromatic number is at most twice 

their clique number [ABCHRS08]_. 

 

INPUT: 

 

- ``certificate`` (boolean) -- When ``certificate = False``, 

this method only returns ``True`` or ``False``. If 

``certificate = True``, the subgraph found is returned 

instead of ``False``. 

 

EXAMPLES: 

 

Is the Petersen Graph even-hole-free :: 

 

sage: g = graphs.PetersenGraph() 

sage: g.is_even_hole_free() 

False 

 

As any chordal graph is hole-free, interval graphs behave the 

same way:: 

 

sage: g = graphs.RandomIntervalGraph(20) 

sage: g.is_even_hole_free() 

True 

 

It is clear, though, that a random Bipartite Graph which is 

not a forest has an even hole:: 

 

sage: g = graphs.RandomBipartite(10, 10, .5) 

sage: g.is_even_hole_free() and not g.is_forest() 

False 

 

We can check the certificate returned is indeed an even 

cycle:: 

 

sage: if not g.is_forest(): 

....: cycle = g.is_even_hole_free(certificate = True) 

....: if cycle.order() % 2 == 1: 

....: print("Error !") 

....: if not cycle.is_isomorphic( 

....: graphs.CycleGraph(cycle.order())): 

....: print("Error !") 

... 

sage: print("Everything is Fine !") 

Everything is Fine ! 

 

TESTS: 

 

Bug reported in :trac:`9925`, and fixed by :trac:`9420`:: 

 

sage: g = Graph(':SiBFGaCEF_@CE`DEGH`CEFGaCDGaCDEHaDEF`CEH`ABCDEF', loops=False, multiedges=False) 

sage: g.is_even_hole_free() 

False 

sage: g.is_even_hole_free(certificate = True) 

Subgraph of (): Graph on 4 vertices 

 

Making sure there are no other counter-examples around :: 

 

sage: t = lambda x : (Graph(x).is_forest() or 

....: isinstance(Graph(x).is_even_hole_free(certificate = True),Graph)) 

sage: all( t(graphs.RandomBipartite(10,10,.5)) for i in range(100) ) 

True 

 

REFERENCE: 

 

.. [ABCHRS08] \L. Addario-Berry, M. Chudnovsky, F. Havet, B. Reed, P. Seymour 

Bisimplicial vertices in even-hole-free graphs 

Journal of Combinatorial Theory, Series B 

vol 98, n.6 pp 1119-1164, 2008 

""" 

from sage.graphs.graph_generators import GraphGenerators 

 

girth = self.girth() 

 

if girth > self.order(): 

start = 4 

 

elif girth % 2 == 0: 

if not certificate: 

return False 

start = girth 

 

else: 

start = girth + 1 

 

while start <= self.order(): 

 

 

subgraph = self.subgraph_search(GraphGenerators().CycleGraph(start), induced = True) 

 

if not subgraph is None: 

if certificate: 

return subgraph 

else: 

return False 

 

start = start + 2 

 

return True 

 

@doc_index("Graph properties") 

def is_odd_hole_free(self, certificate = False): 

r""" 

Tests whether ``self`` contains an induced odd hole. 

 

A Hole is a cycle of length at least 4 (included). It is said 

to be even (resp. odd) if its length is even (resp. odd). 

 

It is interesting to notice that while it is polynomial to 

check whether a graph has an odd hole or an odd antihole [CRST06]_, it is 

not known whether testing for one of these two cases 

independently is polynomial too. 

 

INPUT: 

 

- ``certificate`` (boolean) -- When ``certificate = False``, 

this method only returns ``True`` or ``False``. If 

``certificate = True``, the subgraph found is returned 

instead of ``False``. 

 

EXAMPLES: 

 

Is the Petersen Graph odd-hole-free :: 

 

sage: g = graphs.PetersenGraph() 

sage: g.is_odd_hole_free() 

False 

 

Which was to be expected, as its girth is 5 :: 

 

sage: g.girth() 

5 

 

We can check the certificate returned is indeed a 5-cycle:: 

 

sage: cycle = g.is_odd_hole_free(certificate = True) 

sage: cycle.is_isomorphic(graphs.CycleGraph(5)) 

True 

 

As any chordal graph is hole-free, no interval graph has an odd hole:: 

 

sage: g = graphs.RandomIntervalGraph(20) 

sage: g.is_odd_hole_free() 

True 

 

REFERENCES: 

 

.. [CRST06] \M. Chudnovsky, G. Cornuejols, X. Liu, P. Seymour, K. Vuskovic 

Recognizing berge graphs 

Combinatorica vol 25, n 2, pages 143--186 

2005 

""" 

from sage.graphs.graph_generators import GraphGenerators 

 

girth = self.odd_girth() 

 

if girth > self.order(): 

return True 

if girth == 3: 

start = 5 

 

else: 

if not certificate: 

return False 

start = girth 

 

while start <= self.order(): 

 

subgraph = self.subgraph_search(GraphGenerators().CycleGraph(start), induced = True) 

 

if not subgraph is None: 

if certificate: 

return subgraph 

else: 

return False 

 

start += 2 

 

return True 

 

@doc_index("Graph properties") 

def is_bipartite(self, certificate = False): 

""" 

Returns ``True`` if graph `G` is bipartite, ``False`` if not. 

 

Traverse the graph G with breadth-first-search and color nodes. 

 

INPUT: 

 

- ``certificate`` -- whether to return a certificate (``False`` by 

default). If set to ``True``, the certificate returned in a proper 

2-coloring when `G` is bipartite, and an odd cycle otherwise. 

 

EXAMPLES:: 

 

sage: graphs.CycleGraph(4).is_bipartite() 

True 

sage: graphs.CycleGraph(5).is_bipartite() 

False 

sage: graphs.RandomBipartite(100,100,0.7).is_bipartite() 

True 

 

A random graph is very rarely bipartite:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.is_bipartite() 

False 

sage: false, oddcycle = g.is_bipartite(certificate = True) 

sage: len(oddcycle) % 2 

1 

""" 

color = {} 

 

# For any uncolored vertex in the graph (to ensure we do the right job 

# when the graph is not connected !) 

for u in self: 

if u in color: 

continue 

 

# Let us run a BFS starting from u 

queue = [u] 

color[u] = 1 

while queue: 

v = queue.pop(0) 

c = 1-color[v] 

for w in self.neighbor_iterator(v): 

 

# If the vertex has already been colored 

if w in color: 

 

# The graph is not bipartite ! 

if color[w] == color[v]: 

 

# Should we return an odd cycle ? 

if certificate: 

 

# We build the first half of the cycle, i.e. a 

# u-w path 

cycle = self.shortest_path(u,w) 

 

# The second half is a v-u path, but there may 

# be common vertices in the two paths. But we 

# can avoid that ! 

 

for v in self.shortest_path(v,u): 

if v in cycle: 

return False, cycle[cycle.index(v):] 

else: 

cycle.append(v) 

else: 

return False 

 

# We color a new vertex 

else: 

color[w] = c 

queue.append(w) 

if certificate: 

return True, color 

else: 

return True 

 

@doc_index("Graph properties") 

def is_triangle_free(self, algorithm='bitset'): 

r""" 

Returns whether ``self`` is triangle-free 

 

INPUT: 

 

- ``algorithm`` -- (default: ``'bitset'``) specifies the algorithm to 

use among: 

 

- ``'matrix'`` -- tests if the trace of the adjacency matrix is 

positive. 

 

- ``'bitset'`` -- encodes adjacencies into bitsets and uses fast 

bitset operations to test if the input graph contains a 

triangle. This method is generally faster than standard matrix 

multiplication. 

 

EXAMPLES: 

 

The Petersen Graph is triangle-free:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.is_triangle_free() 

True 

 

or a complete Bipartite Graph:: 

 

sage: G = graphs.CompleteBipartiteGraph(5,6) 

sage: G.is_triangle_free(algorithm='matrix') 

True 

sage: G.is_triangle_free(algorithm='bitset') 

True 

 

a tripartite graph, though, contains many triangles:: 

 

sage: G = (3 * graphs.CompleteGraph(5)).complement() 

sage: G.is_triangle_free(algorithm='matrix') 

False 

sage: G.is_triangle_free(algorithm='bitset') 

False 

 

TESTS: 

 

Comparison of algorithms:: 

 

sage: for i in range(10): # long time 

....: G = graphs.RandomBarabasiAlbert(50,2) 

....: bm = G.is_triangle_free(algorithm='matrix') 

....: bb = G.is_triangle_free(algorithm='bitset') 

....: if bm != bb: 

....: print("That's not good!") 

 

Asking for an unknown algorithm:: 

 

sage: g.is_triangle_free(algorithm='tip top') 

Traceback (most recent call last): 

... 

ValueError: Algorithm 'tip top' not yet implemented. Please contribute. 

 

Check the empty graph:: 

 

sage: graphs.EmptyGraph().is_triangle_free() 

True 

""" 

if self.order() == 0: 

return True 

 

if algorithm=='bitset': 

from sage.data_structures.bitset import Bitset 

N = self.num_verts() 

map = {} 

i = 0 

B = {} 

for u in self.vertex_iterator(): 

map[u] = i 

i += 1 

B[u] = Bitset(capacity=N) 

# map adjacency to bitsets 

for u,v in self.edge_iterator(labels=None): 

B[u].add(map[v]) 

B[v].add(map[u]) 

# map lengths 2 paths to bitsets 

BB = Bitset(capacity=N) 

for u in self.vertex_iterator(): 

BB.clear() 

for v in self.vertex_iterator(): 

if B[u]&B[v]: 

BB.add(map[v]) 

# search for triangles 

if B[u]&BB: 

return False 

return True 

 

elif algorithm=='matrix': 

return (self.adjacency_matrix()**3).trace() == 0 

 

else: 

raise ValueError("Algorithm '%s' not yet implemented. Please contribute." %(algorithm)) 

 

@doc_index("Graph properties") 

def is_split(self): 

r""" 

Returns ``True`` if the graph is a Split graph, ``False`` otherwise. 

 

A Graph `G` is said to be a split graph if its vertices `V(G)` 

can be partitioned into two sets `K` and `I` such that the 

vertices of `K` induce a complete graph, and those of `I` are 

an independent set. 

 

There is a simple test to check whether a graph is a split 

graph (see, for instance, the book "Graph Classes, a survey" 

[GraphClasses]_ page 203) : 

 

Given the degree sequence `d_1 \geq ... \geq d_n` of `G`, a graph 

is a split graph if and only if : 

 

.. MATH:: 

 

\sum_{i=1}^\omega d_i = \omega (\omega - 1) + \sum_{i=\omega + 1}^nd_i 

 

where `\omega = max \{i:d_i\geq i-1\}`. 

 

 

EXAMPLES: 

 

Split graphs are, in particular, chordal graphs. Hence, The Petersen graph 

can not be split:: 

 

sage: graphs.PetersenGraph().is_split() 

False 

 

We can easily build some "random" split graph by creating a 

complete graph, and adding vertices only connected 

to some random vertices of the clique:: 

 

sage: g = graphs.CompleteGraph(10) 

sage: sets = Subsets(Set(range(10))) 

sage: for i in range(10, 25): 

....: g.add_edges([(i,k) for k in sets.random_element()]) 

sage: g.is_split() 

True 

 

Another caracterisation of split graph states that a graph is a split graph 

if and only if does not contain the 4-cycle, 5-cycle or 2K_2 as an induced 

subgraph. Hence for the above graph we have:: 

 

sage: sum([g.subgraph_search_count(H,induced=True) for H in [graphs.CycleGraph(4),graphs.CycleGraph(5), 2*graphs.CompleteGraph(2)]]) 

0 

 

 

REFERENCES: 

 

.. [GraphClasses] \A. Brandstadt, VB Le and JP Spinrad 

Graph classes: a survey 

SIAM Monographs on Discrete Mathematics and Applications}, 

1999 

""" 

self._scream_if_not_simple() 

# our degree sequence is numbered from 0 to n-1, so to avoid 

# any mistake, let's fix it :-) 

degree_sequence = [0] + sorted(self.degree(), reverse = True) 

 

for (i, d) in enumerate(degree_sequence): 

if d >= i - 1: 

omega = i 

else: 

break 

 

left = sum(degree_sequence[:omega + 1]) 

right = omega * (omega - 1) + sum(degree_sequence[omega + 1:]) 

 

return left == right 

 

@doc_index("Algorithmically hard stuff") 

def treewidth(self,k=None,certificate=False,algorithm=None): 

r""" 

Computes the tree-width of `G` (and provides a decomposition) 

 

INPUT: 

 

- ``k`` (integer) -- the width to be considered. When ``k`` is an 

integer, the method checks that the graph has treewidth `\leq k`. If 

``k`` is ``None`` (default), the method computes the optimal 

tree-width. 

 

- ``certificate`` -- whether to return the tree-decomposition itself. 

 

- ``algorithm`` -- whether to use ``"sage"`` or ``"tdlib"`` (requires 

the installation of the 'tdlib' package). The default behaviour is to 

use 'tdlib' if it is available, and Sage's own algorithm when it is 

not. 

 

OUTPUT: 

 

``g.treewidth()`` returns the treewidth of ``g``. When ``k`` is 

specified, it returns ``False`` when no tree-decomposition of width 

`\leq k` exists or ``True`` otherwise. When ``certificate=True``, 

the tree-decomposition is also returned. 

 

ALGORITHM: 

 

This function virtually explores the graph of all pairs 

``(vertex_cut,cc)``, where ``vertex_cut`` is a vertex cut of the 

graph of cardinality `\leq k+1`, and ``connected_component`` is a 

connected component of the graph induced by ``G-vertex_cut``. 

 

We deduce that the pair ``(vertex_cut,cc)`` is feasible with 

tree-width `k` if ``cc`` is empty, or if a vertex ``v`` from 

``vertex_cut`` can be replaced with a vertex from ``cc``, such that 

the pair ``(vertex_cut+v,cc-v)`` is feasible. 

 

.. NOTE:: 

 

The implementation would be much faster if ``cc``, the argument of the 

recursive function, was a bitset. It would also be very nice to not copy 

the graph in order to compute connected components, for this is really a 

waste of time. 

 

.. SEEALSO:: 

 

:meth:`~sage.graphs.graph_decompositions.vertex_separation.path_decomposition` 

computes the pathwidth of a graph. See also the 

:mod:`~sage.graphs.graph_decompositions.vertex_separation` module. 

 

EXAMPLES: 

 

The PetersenGraph has treewidth 4:: 

 

sage: graphs.PetersenGraph().treewidth() 

4 

sage: graphs.PetersenGraph().treewidth(certificate=True) 

Tree decomposition: Graph on 6 vertices 

 

The treewidth of a 2d grid is its smallest side:: 

 

sage: graphs.Grid2dGraph(2,5).treewidth() 

2 

sage: graphs.Grid2dGraph(3,5).treewidth() 

3 

 

TESTS:: 

 

sage: g = graphs.PathGraph(3) 

sage: g.treewidth() 

1 

sage: g = 2*graphs.PathGraph(3) 

sage: g.treewidth() 

1 

sage: g.treewidth(certificate=True) 

Tree decomposition: Graph on 4 vertices 

sage: g.treewidth(2) 

True 

sage: g.treewidth(1) 

True 

sage: Graph(1).treewidth() 

0 

sage: Graph(0).treewidth() 

-1 

sage: graphs.PetersenGraph().treewidth(k=2) 

False 

sage: graphs.PetersenGraph().treewidth(k=6) 

True 

sage: graphs.PetersenGraph().treewidth(certificate=True).is_tree() 

True 

sage: graphs.PetersenGraph().treewidth(k=3,certificate=True) 

False 

sage: graphs.PetersenGraph().treewidth(k=4,certificate=True) 

Tree decomposition: Graph on 6 vertices 

 

All edges do appear (:trac:`17893`):: 

 

sage: from itertools import combinations 

sage: g = graphs.PathGraph(10) 

sage: td = g.treewidth(certificate=True) 

sage: for bag in td: 

....: g.delete_edges(list(combinations(bag,2))) 

sage: g.size() 

0 

 

:trac:`19358`:: 

 

sage: g = Graph() 

sage: for i in range(3): 

....: for j in range(2): 

....: g.add_path([i,(i,j),(i+1)%3]) 

sage: g.treewidth() 

2 

 

The decomposition is a tree (:trac:`23546`):: 

 

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

sage: t = g.treewidth(certificate=True) 

sage: t.is_tree() 

True 

sage: vertices = set() 

sage: for s in t.vertices(): 

....: vertices = vertices.union(s) 

sage: vertices == set(g.vertices()) 

True 

 

Trivially true:: 

 

sage: graphs.PetersenGraph().treewidth(k=35) 

True 

sage: graphs.PetersenGraph().treewidth(k=35,certificate=True) 

Tree decomposition: Graph on 1 vertex 

 

Bad input: 

 

sage: graphs.PetersenGraph().treewidth(k=-3) 

Traceback (most recent call last): 

... 

ValueError: k(=-3) must be a nonnegative integer 

""" 

g = self 

 

# Check Input 

if algorithm is None: 

try: 

import sage.graphs.graph_decompositions.tdlib as tdlib 

algorithm = "tdlib" 

except ImportError: 

algorithm = "sage" 

elif (algorithm != "sage" and 

algorithm != "tdlib"): 

raise ValueError("'algorithm' must be equal to 'tdlib', 'sage', or None") 

 

if k is not None and k<0: 

raise ValueError("k(={}) must be a nonnegative integer".format(k)) 

 

# Stupid cases 

if g.order() == 0: 

if certificate: return Graph() 

elif k is None: return -1 

else: return True 

 

if k is not None and k >= g.order()-1: 

if certificate: 

from sage.sets.set import Set 

return Graph({Set(g.vertices()):[]}, 

name="Tree decomposition") 

return True 

 

# TDLIB 

if algorithm == 'tdlib': 

try: 

import sage.graphs.graph_decompositions.tdlib as tdlib 

except ImportError: 

from sage.misc.package import PackageNotFoundError 

raise PackageNotFoundError("tdlib") 

 

T = tdlib.treedecomposition_exact(g, -1 if k is None else k) 

width = tdlib.get_width(T) 

 

if certificate: 

return T if (k is None or width <= k) else False 

elif k is None: 

return width 

else: 

return (width <= k) 

 

# Disconnected cases 

if not g.is_connected(): 

if certificate is False: 

if k is None: 

return max(cc.treewidth() for cc in g.connected_components_subgraphs()) 

else: 

return all(cc.treewidth(k) for cc in g.connected_components_subgraphs()) 

else: 

T = [cc.treewidth(certificate=True) for cc in g.connected_components_subgraphs()] 

tree = Graph([sum([t.vertices() for t in T],[]), sum([t.edges(labels=False) for t in T],[])], name="Tree decomposition") 

v = next(T[0].vertex_iterator()) 

for t in T[1:]: 

tree.add_edge(next(t.vertex_iterator()),v) 

return tree 

 

# Forcing k to be defined 

if k is None: 

for i in range(max(0,g.clique_number()-1,min(g.degree())), 

g.order()+1): 

ans = g.treewidth(k=i, certificate=certificate) 

if ans: 

return ans if certificate else i 

 

# This is the recursion described in the method's documentation. All 

# computations are cached, and depends on the pair ``cut, 

# connected_component`` only. 

# 

# It returns either a boolean or the corresponding tree-decomposition, as a 

# list of edges between vertex cuts (as it is done for the complete 

# tree-decomposition at the end of the main function. 

from sage.misc.cachefunc import cached_function 

@cached_function 

def rec(cut,cc): 

# Easy cases 

if len(cut) > k: 

return False 

if len(cc)+len(cut) <= k+1: 

return [(cut,cut.union(cc))] if certificate else True 

 

# We explore all possible extensions of the cut 

for v in cc: 

 

# New cuts and connected components, with v respectively added and 

# removed 

cutv = cut.union([v]) 

ccv = cc.difference([v]) 

 

# The values returned by the recursive calls. 

sons = [] 

 

# Removing v may have disconnected cc. We iterate on its connected 

# components 

for cci in g.subgraph(ccv).connected_components(): 

 

# The recursive subcalls. We remove on-the-fly the vertices from 

# the cut which play no role in separating the connected 

# component from the rest of the graph. 

reduced_cut = frozenset([x for x in cutv if any(xx in cci for xx in g.neighbors(x))]) 

son = rec(reduced_cut,frozenset(cci)) 

if son is False: 

break 

 

if certificate: 

sons.extend(son) 

sons.append((cut,cutv)) 

sons.append((cutv,reduced_cut)) 

 

# Weird Python syntax which is useful once in a lifetime : if break 

# was never called in the loop above, we return "sons". 

else: 

return sons if certificate else True 

 

return False 

 

# Main call to rec function, i.e. rec({v},V-{v}) 

V = g.vertices() 

v = frozenset([V.pop(0)]) 

TD = rec(v,frozenset(V)) 

 

if TD is False: 

return False 

 

if not certificate: 

return True 

 

# Building the Tree-Decomposition graph. Its vertices are cuts of the 

# decomposition, and there is an edge from a cut C1 to a cut C2 if C2 is an 

# immediate subcall of C1 

from sage.sets.set import Set 

G = Graph(name="Tree decomposition") 

G.add_edges(((Set(x),Set(y)) for x,y in TD), loops=False) 

 

# The Tree-Decomposition contains a lot of useless nodes. 

# 

# We merge all edges between two sets S,S' where S is a subset of S' 

changed = True 

while changed: 

changed=False 

for v in G.vertices(): 

for u in G.neighbors(v): 

if u.issuperset(v): 

G.merge_vertices([u,v]) # the new vertex is named 'u' 

changed = True 

break 

 

return G 

 

@doc_index("Algorithmically hard stuff") 

def is_perfect(self, certificate = False): 

r""" 

Tests whether the graph is perfect. 

 

A graph `G` is said to be perfect if `\chi(H)=\omega(H)` hold 

for any induced subgraph `H\subseteq_i G` (and so for `G` 

itself, too), where `\chi(H)` represents the chromatic number 

of `H`, and `\omega(H)` its clique number. The Strong Perfect 

Graph Theorem [SPGT]_ gives another characterization of 

perfect graphs: 

 

A graph is perfect if and only if it contains no odd hole 

(cycle on an odd number `k` of vertices, `k>3`) nor any odd 

antihole (complement of a hole) as an induced subgraph. 

 

INPUT: 

 

- ``certificate`` (boolean) -- whether to return 

a certificate (default : ``False``) 

 

OUTPUT: 

 

When ``certificate = False``, this function returns 

a boolean value. When ``certificate = True``, it returns 

a subgraph of ``self`` isomorphic to an odd hole or an odd 

antihole if any, and ``None`` otherwise. 

 

EXAMPLES: 

 

A Bipartite Graph is always perfect :: 

 

sage: g = graphs.RandomBipartite(8,4,.5) 

sage: g.is_perfect() 

True 

 

So is the line graph of a bipartite graph:: 

 

sage: g = graphs.RandomBipartite(4,3,0.7) 

sage: g.line_graph().is_perfect() # long time 

True 

 

As well as the Cartesian product of two complete graphs:: 

 

sage: g = graphs.CompleteGraph(3).cartesian_product(graphs.CompleteGraph(3)) 

sage: g.is_perfect() 

True 

 

Interval Graphs, which are chordal graphs, too :: 

 

sage: g = graphs.RandomIntervalGraph(7) 

sage: g.is_perfect() 

True 

 

The PetersenGraph, which is triangle-free and 

has chromatic number 3 is obviously not perfect:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.is_perfect() 

False 

 

We can obtain an induced 5-cycle as a certificate:: 

 

sage: g.is_perfect(certificate = True) 

Subgraph of (Petersen graph): Graph on 5 vertices 

 

TESTS: 

 

Check that :trac:`13546` has been fixed:: 

 

sage: Graph(':FgGE@I@GxGs', loops=False, multiedges=False).is_perfect() 

False 

sage: g = Graph({0: [2, 3, 4, 5], 

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

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

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

....: 4: [0, 1, 2, 6], 

....: 5: [0, 1, 2, 3], 

....: 6: [1, 2, 3, 4]}) 

sage: g.is_perfect() 

False 

 

REFERENCES: 

 

.. [SPGT] \M. Chudnovsky, N. Robertson, P. Seymour, R. Thomas. 

The strong perfect graph theorem 

Annals of Mathematics 

vol 164, number 1, pages 51--230 

2006 

 

TESTS:: 

 

sage: Graph(':Ab').is_perfect() 

Traceback (most recent call last): 

... 

ValueError: This method is only defined for simple graphs, and yours is not one of them ! 

sage: g = Graph() 

sage: g.allow_loops(True) 

sage: g.add_edge(0,0) 

sage: g.edges() 

[(0, 0, None)] 

sage: g.is_perfect() 

Traceback (most recent call last): 

... 

ValueError: This method is only defined for simple graphs, and yours is not one of them ! 

 

""" 

 

if self.has_multiple_edges() or self.has_loops(): 

raise ValueError("This method is only defined for simple graphs," 

" and yours is not one of them !") 

if self.is_bipartite(): 

 

return True if not certificate else None 

 

self_complement = self.complement() 

 

self_complement.remove_loops() 

self_complement.remove_multiple_edges() 

 

if self_complement.is_bipartite(): 

return True if not certificate else None 

 

answer = self.is_odd_hole_free(certificate = certificate) 

if not (answer is True): 

return answer 

 

return self_complement.is_odd_hole_free(certificate = certificate) 

 

@doc_index("Graph properties") 

def odd_girth(self): 

r""" 

Returns the odd girth of self. 

 

The odd girth of a graph is defined as the smallest cycle of odd length. 

 

OUTPUT: 

 

The odd girth of ``self``. 

 

EXAMPLES: 

 

The McGee graph has girth 7 and therefore its odd girth is 7 as well. :: 

 

sage: G = graphs.McGeeGraph() 

sage: G.odd_girth() 

7 

 

Any complete graph on more than 2 vertices contains a triangle and has 

thus odd girth 3. :: 

 

sage: G = graphs.CompleteGraph(10) 

sage: G.odd_girth() 

3 

 

Every bipartite graph has no odd cycles and consequently odd girth of 

infinity. :: 

 

sage: G = graphs.CompleteBipartiteGraph(100,100) 

sage: G.odd_girth() 

+Infinity 

 

.. SEEALSO:: 

 

* :meth:`~sage.graphs.generic_graph.GenericGraph.girth` -- computes 

the girth of a graph. 

 

REFERENCES: 

 

The property relating the odd girth to the coefficients of the 

characteristic polynomial is an old result from algebraic graph theory 

see 

 

.. [Har62] Harary, F (1962). The determinant of the adjacency matrix of 

a graph, SIAM Review 4, 202-210 

 

.. [Biggs93] Biggs, N. L. Algebraic Graph Theory, 2nd ed. Cambridge, 

England: Cambridge University Press, pp. 45, 1993. 

 

TESTS:: 

 

sage: graphs.CycleGraph(5).odd_girth() 

5 

sage: graphs.CycleGraph(11).odd_girth() 

11 

""" 

ch = ((self.am()).charpoly()).coefficients(sparse=False) 

n = self.order() 

 

for i in range(n-1,-1,-2): 

if ch[i] != 0: 

return n-i 

 

from sage.rings.infinity import Infinity 

 

return Infinity 

 

@doc_index("Graph properties") 

def is_edge_transitive(self): 

""" 

Returns true if self is an edge transitive graph. 

 

A graph is edge-transitive if its automorphism group acts transitively 

on its edge set. 

 

Equivalently, if there exists for any pair of edges `uv,u'v'\in E(G)` an 

automorphism `\phi` of `G` such that `\phi(uv)=u'v'` (note this does not 

necessarily mean that `\phi(u)=u'` and `\phi(v)=v'`). 

 

See :wikipedia:`the wikipedia article on edge-transitive graphs 

<Edge-transitive_graph>` for more information. 

 

.. SEEALSO:: 

 

- :meth:`~Graph.is_arc_transitive` 

- :meth:`~Graph.is_half_transitive` 

- :meth:`~Graph.is_semi_symmetric` 

 

EXAMPLES:: 

 

sage: P = graphs.PetersenGraph() 

sage: P.is_edge_transitive() 

True 

sage: C = graphs.CubeGraph(3) 

sage: C.is_edge_transitive() 

True 

sage: G = graphs.GrayGraph() 

sage: G.is_edge_transitive() 

True 

sage: P = graphs.PathGraph(4) 

sage: P.is_edge_transitive() 

False 

""" 

from sage.interfaces.gap import gap 

 

if self.size() == 0: 

return True 

 

A = self.automorphism_group() 

e = next(self.edge_iterator(labels=False)) 

e = [A._domain_to_gap[e[0]], A._domain_to_gap[e[1]]] 

 

return gap("OrbitLength("+str(A._gap_())+",Set(" + str(e) + "),OnSets);") == self.size() 

 

@doc_index("Graph properties") 

def is_arc_transitive(self): 

""" 

Returns true if self is an arc-transitive graph 

 

A graph is arc-transitive if its automorphism group acts transitively on 

its pairs of adjacent vertices. 

 

Equivalently, if there exists for any pair of edges `uv,u'v'\in E(G)` an 

automorphism `\phi_1` of `G` such that `\phi_1(u)=u'` and 

`\phi_1(v)=v'`, as well as another automorphism `\phi_2` of `G` such 

that `\phi_2(u)=v'` and `\phi_2(v)=u'` 

 

See :wikipedia:`the wikipedia article on arc-transitive graphs 

<arc-transitive_graph>` for more information. 

 

.. SEEALSO:: 

 

- :meth:`~Graph.is_edge_transitive` 

- :meth:`~Graph.is_half_transitive` 

- :meth:`~Graph.is_semi_symmetric` 

 

EXAMPLES:: 

 

sage: P = graphs.PetersenGraph() 

sage: P.is_arc_transitive() 

True 

sage: G = graphs.GrayGraph() 

sage: G.is_arc_transitive() 

False 

""" 

 

from sage.interfaces.gap import gap 

 

if self.size() == 0: 

return True 

 

A = self.automorphism_group() 

e = next(self.edge_iterator(labels=False)) 

e = [A._domain_to_gap[e[0]], A._domain_to_gap[e[1]]] 

 

return gap("OrbitLength("+str(A._gap_())+",Set(" + str(e) + "),OnTuples);") == 2*self.size() 

 

@doc_index("Graph properties") 

def is_half_transitive(self): 

""" 

Returns true if self is a half-transitive graph. 

 

A graph is half-transitive if it is both vertex and edge transitive 

but not arc-transitive. 

 

See :wikipedia:`the wikipedia article on half-transitive graphs 

<half-transitive_graph>` for more information. 

 

.. SEEALSO:: 

 

- :meth:`~Graph.is_edge_transitive` 

- :meth:`~Graph.is_arc_transitive` 

- :meth:`~Graph.is_semi_symmetric` 

 

EXAMPLES: 

 

The Petersen Graph is not half-transitive:: 

 

sage: P = graphs.PetersenGraph() 

sage: P.is_half_transitive() 

False 

 

The smallest half-transitive graph is the Holt Graph:: 

 

sage: H = graphs.HoltGraph() 

sage: H.is_half_transitive() 

True 

""" 

 

# A half-transitive graph always has only vertices of even degree 

if not all(d%2 == 0 for d in self.degree_iterator()): 

return False 

 

return (self.is_edge_transitive() and 

self.is_vertex_transitive() and 

not self.is_arc_transitive()) 

 

@doc_index("Graph properties") 

def is_semi_symmetric(self): 

""" 

Returns true if self is semi-symmetric. 

 

A graph is semi-symmetric if it is regular, edge-transitive but not 

vertex-transitive. 

 

See :wikipedia:`the wikipedia article on semi-symmetric graphs 

<Semi-symmetric_graph>` for more information. 

 

.. SEEALSO:: 

 

- :meth:`~Graph.is_edge_transitive` 

- :meth:`~Graph.is_arc_transitive` 

- :meth:`~Graph.is_half_transitive` 

 

EXAMPLES: 

 

The Petersen graph is not semi-symmetric:: 

 

sage: P = graphs.PetersenGraph() 

sage: P.is_semi_symmetric() 

False 

 

The Gray graph is the smallest possible cubic semi-symmetric graph:: 

 

sage: G = graphs.GrayGraph() 

sage: G.is_semi_symmetric() 

True 

 

Another well known semi-symmetric graph is the Ljubljana graph:: 

 

sage: L = graphs.LjubljanaGraph() 

sage: L.is_semi_symmetric() 

True 

""" 

# A semi-symmetric graph is always bipartite 

if not self.is_bipartite(): 

return False 

 

return (self.is_regular() and 

self.is_edge_transitive() and not 

self.is_vertex_transitive()) 

 

@doc_index("Connectivity, orientations, trees") 

def degree_constrained_subgraph(self, bounds, solver=None, verbose=0): 

r""" 

Returns a degree-constrained subgraph. 

 

Given a graph `G` and two functions `f, g:V(G)\rightarrow \mathbb Z` 

such that `f \leq g`, a degree-constrained subgraph in `G` is 

a subgraph `G' \subseteq G` such that for any vertex `v \in G`, 

`f(v) \leq d_{G'}(v) \leq g(v)`. 

 

INPUT: 

 

- ``bounds`` -- (default: ``None``) Two possibilities: 

 

- A dictionary whose keys are the vertices, and values a pair of 

real values ``(min,max)`` corresponding to the values 

`(f(v),g(v))`. 

 

- A function associating to each vertex a pair of 

real values ``(min,max)`` corresponding to the values 

`(f(v),g(v))`. 

 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

OUTPUT: 

 

- When a solution exists, this method outputs the degree-constained 

subgraph as a Graph object. 

 

- When no solution exists, returns ``False``. 

 

.. NOTE:: 

 

- This algorithm computes the degree-constrained subgraph of minimum weight. 

- If the graph's edges are weighted, these are taken into account. 

- This problem can be solved in polynomial time. 

 

EXAMPLES: 

 

Is there a perfect matching in an even cycle? :: 

 

sage: g = graphs.CycleGraph(6) 

sage: bounds = lambda x: [1,1] 

sage: m = g.degree_constrained_subgraph(bounds=bounds) 

sage: m.size() 

3 

""" 

self._scream_if_not_simple() 

from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException 

 

p = MixedIntegerLinearProgram(maximization=False, solver=solver) 

b = p.new_variable(binary=True) 

 

reorder = lambda x,y: (x,y) if x<y else (y,x) 

 

if isinstance(bounds,dict): 

f_bounds = lambda x: bounds[x] 

else: 

f_bounds = bounds 

 

 

if self.weighted(): 

from sage.rings.real_mpfr import RR 

weight = lambda x: x if x in RR else 1 

else: 

weight = lambda x: 1 

 

for v in self: 

minimum,maximum = f_bounds(v) 

p.add_constraint(p.sum( b[reorder(x,y)]*weight(l) for x,y,l in self.edges_incident(v)), min=minimum, max=maximum) 

 

p.set_objective(p.sum( b[reorder(x,y)]*weight(l) for x,y,l in self.edge_iterator())) 

 

try: 

p.solve(log=verbose) 

g = copy(self) 

b = p.get_values(b) 

g.delete_edges([(x,y) for x,y,_ in g.edge_iterator() if b[reorder(x,y)] < 0.5]) 

return g 

 

 

except MIPSolverException: 

return False 

 

 

### Orientations 

 

@doc_index("Connectivity, orientations, trees") 

def strong_orientation(self): 

r""" 

Returns a strongly connected orientation of the current graph. 

 

An orientation of an undirected graph is a digraph obtained by giving an 

unique direction to each of its edges. An orientation is said to be 

strong if there is a directed path between each pair of vertices. See 

also the :wikipedia:`Strongly_connected_component`. 

 

If the graph is 2-edge-connected, a strongly connected orientation 

can be found in linear time. If the given graph is not 2-connected, 

the orientation returned will ensure that each 2-connected component 

has a strongly connected orientation. 

 

OUTPUT: 

 

A digraph representing an orientation of the current graph. 

 

.. NOTE:: 

 

- This method assumes the graph is connected. 

- This algorithm works in O(m). 

 

EXAMPLES: 

 

For a 2-regular graph, a strong orientation gives to each vertex 

an out-degree equal to 1:: 

 

sage: g = graphs.CycleGraph(5) 

sage: g.strong_orientation().out_degree() 

[1, 1, 1, 1, 1] 

 

The Petersen Graph is 2-edge connected. It then has a strongly 

connected orientation:: 

 

sage: g = graphs.PetersenGraph() 

sage: o = g.strong_orientation() 

sage: len(o.strongly_connected_components()) 

1 

 

The same goes for the CubeGraph in any dimension :: 

 

sage: all(len(graphs.CubeGraph(i).strong_orientation().strongly_connected_components()) == 1 for i in range(2,6)) 

True 

 

A multigraph also has a strong orientation :: 

 

sage: g = Graph([(1,2),(1,2)],multiedges=True) 

sage: g.strong_orientation() 

Multi-digraph on 2 vertices 

 

""" 

from sage.graphs.all import DiGraph 

d = DiGraph(multiedges=self.allows_multiple_edges()) 

 

id = {} 

i = 0 

 

# The algorithm works through a depth-first search. Any edge 

# used in the depth-first search is oriented in the direction 

# in which it has been used. All the other edges are oriented 

# backward 

 

v = next(self.vertex_iterator()) 

seen = {} 

i=1 

 

# Time at which the vertices have been discovered 

seen[v] = i 

 

# indicates the stack of edges to explore 

next_ = self.edges_incident(v) 

 

while next_: 

e = next_.pop(-1) 

 

# Ignore loops 

if e[0] == e[1]: 

continue 

 

# We assume e[0] to be a `seen` vertex 

e = e if seen.get(e[0],False) is not False else (e[1],e[0],e[2]) 

 

# If we discovered a new vertex 

if seen.get(e[1],False) is False: 

d.add_edge(e) 

next_.extend([ee for ee in self.edges_incident(e[1]) if (((e[0],e[1]) != (ee[0],ee[1])) and ((e[0],e[1]) != (ee[1],ee[0])))]) 

i+=1 

seen[e[1]]=i 

 

# Else, we orient the edges backward 

else: 

if seen[e[0]] < seen[e[1]]: 

d.add_edge((e[1],e[0],e[2])) 

else: 

d.add_edge(e) 

 

# Case of multiple edges. If another edge has already been inserted, we add the new one 

# in the opposite direction. 

tmp = None 

for e in self.multiple_edges(): 

if tmp == (e[0],e[1]): 

if d.has_edge(e[0],e[1]): 

d.add_edge(e[1],e[0],e[2]) 

else: 

d.add_edge(e) 

tmp = (e[0],e[1]) 

 

return d 

 

@doc_index("Connectivity, orientations, trees") 

def minimum_outdegree_orientation(self, use_edge_labels=False, solver=None, verbose=0): 

r""" 

Returns an orientation of ``self`` with the smallest possible maximum 

outdegree. 

 

Given a Graph `G`, it is polynomial to compute an orientation 

`D` of the edges of `G` such that the maximum out-degree in 

`D` is minimized. This problem, though, is NP-complete in the 

weighted case [AMOZ06]_. 

 

INPUT: 

 

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

 

- When set to ``True``, uses edge labels as weights to 

compute the orientation and assumes a weight of `1` 

when there is no value available for a given edge. 

 

- When set to ``False`` (default), gives a weight of 1 

to all the edges. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

EXAMPLES: 

 

Given a complete bipartite graph `K_{n,m}`, the maximum out-degree 

of an optimal orientation is `\left\lceil \frac {nm} {n+m}\right\rceil`:: 

 

sage: g = graphs.CompleteBipartiteGraph(3,4) 

sage: o = g.minimum_outdegree_orientation() 

sage: max(o.out_degree()) == ceil((4*3)/(3+4)) 

True 

 

REFERENCES: 

 

.. [AMOZ06] Asahiro, Y. and Miyano, E. and Ono, H. and Zenmyo, K. 

Graph orientation algorithms to minimize the maximum outdegree 

Proceedings of the 12th Computing: The Australasian Theory Symposium 

Volume 51, page 20 

Australian Computer Society, Inc. 2006 

""" 

self._scream_if_not_simple() 

if self.is_directed(): 

raise ValueError("Cannot compute an orientation of a DiGraph. "+\ 

"Please convert it to a Graph if you really mean it.") 

 

if use_edge_labels: 

from sage.rings.real_mpfr import RR 

weight = lambda u,v : self.edge_label(u,v) if self.edge_label(u,v) in RR else 1 

else: 

weight = lambda u,v : 1 

 

from sage.numerical.mip import MixedIntegerLinearProgram 

 

p = MixedIntegerLinearProgram(maximization=False, solver=solver) 

 

# The orientation of an edge is boolean 

# and indicates whether the edge uv 

# with u<v goes from u to v ( equal to 0 ) 

# or from v to u ( equal to 1) 

orientation = p.new_variable(binary=True) 

 

degree = p.new_variable(nonnegative=True) 

 

# Whether an edge adjacent to a vertex u counts 

# positively or negatively 

outgoing = lambda u,v,variable : (1-variable) if u>v else variable 

 

for u in self: 

p.add_constraint(p.sum(weight(u,v)*outgoing(u,v,orientation[min(u,v),max(u,v)]) for v in self.neighbors(u))-degree['max'], max=0) 

 

p.set_objective(degree['max']) 

 

p.solve(log=verbose) 

 

orientation = p.get_values(orientation) 

 

# All the edges from self are doubled in O 

# ( one in each direction ) 

from sage.graphs.digraph import DiGraph 

O = DiGraph(self) 

 

# Builds the list of edges that should be removed 

edges=[] 

 

for u,v in self.edge_iterator(labels=None): 

# assumes u<v 

if u>v: 

u,v=v,u 

 

if orientation[min(u,v),max(u,v)] == 1: 

edges.append((max(u,v),min(u,v))) 

else: 

edges.append((min(u,v),max(u,v))) 

 

O.delete_edges(edges) 

 

return O 

 

@doc_index("Connectivity, orientations, trees") 

def bounded_outdegree_orientation(self, bound): 

r""" 

Computes an orientation of ``self`` such that every vertex `v` 

has out-degree less than `b(v)` 

 

INPUT: 

 

- ``bound`` -- Maximum bound on the out-degree. Can be of 

three different types : 

 

* An integer `k`. In this case, computes an orientation 

whose maximum out-degree is less than `k`. 

 

* A dictionary associating to each vertex its associated 

maximum out-degree. 

 

* A function associating to each vertex its associated 

maximum out-degree. 

 

OUTPUT: 

 

A DiGraph representing the orientation if it exists. A 

``ValueError`` exception is raised otherwise. 

 

ALGORITHM: 

 

The problem is solved through a maximum flow : 

 

Given a graph `G`, we create a ``DiGraph`` `D` defined on 

`E(G)\cup V(G)\cup \{s,t\}`. We then link `s` to all of `V(G)` 

(these edges having a capacity equal to the bound associated 

to each element of `V(G)`), and all the elements of `E(G)` to 

`t` . We then link each `v \in V(G)` to each of its incident 

edges in `G`. A maximum integer flow of value `|E(G)|` 

corresponds to an admissible orientation of `G`. Otherwise, 

none exists. 

 

EXAMPLES: 

 

There is always an orientation of a graph `G` such that a 

vertex `v` has out-degree at most `\lceil \frac {d(v)} 2 

\rceil`:: 

 

sage: g = graphs.RandomGNP(40, .4) 

sage: b = lambda v : ceil(g.degree(v)/2) 

sage: D = g.bounded_outdegree_orientation(b) 

sage: all( D.out_degree(v) <= b(v) for v in g ) 

True 

 

 

Chvatal's graph, being 4-regular, can be oriented in such a 

way that its maximum out-degree is 2:: 

 

sage: g = graphs.ChvatalGraph() 

sage: D = g.bounded_outdegree_orientation(2) 

sage: max(D.out_degree()) 

2 

 

For any graph `G`, it is possible to compute an orientation 

such that the maximum out-degree is at most the maximum 

average degree of `G` divided by 2. Anything less, though, is 

impossible. 

 

sage: g = graphs.RandomGNP(40, .4) 

sage: mad = g.maximum_average_degree() 

 

Hence this is possible :: 

 

sage: d = g.bounded_outdegree_orientation(ceil(mad/2)) 

 

While this is not:: 

 

sage: try: 

....: g.bounded_outdegree_orientation(ceil(mad/2-1)) 

....: print("Error") 

....: except ValueError: 

....: pass 

 

TESTS: 

 

As previously for random graphs, but more intensively:: 

 

sage: for i in range(30): # long time (up to 6s on sage.math, 2012) 

....: g = graphs.RandomGNP(40, .4) 

....: b = lambda v : ceil(g.degree(v)/2) 

....: D = g.bounded_outdegree_orientation(b) 

....: if not ( 

....: all( D.out_degree(v) <= b(v) for v in g ) or 

....: D.size() != g.size()): 

....: print("Something wrong happened") 

 

""" 

self._scream_if_not_simple() 

from sage.graphs.all import DiGraph 

n = self.order() 

 

if n == 0: 

return DiGraph() 

 

vertices = self.vertices() 

vertices_id = dict((y, x) for x,y in enumerate(vertices)) 

 

b = {} 

 

 

# Checking the input type. We make a dictionary out of it 

if isinstance(bound, dict): 

b = bound 

else: 

try: 

b = dict(zip(vertices,map(bound, vertices))) 

 

except TypeError: 

b = dict(zip(vertices, [bound]*n)) 

 

d = DiGraph() 

 

# Adding the edges (s,v) and ((u,v),t) 

d.add_edges( ('s', vertices_id[v], b[v]) for v in vertices) 

 

d.add_edges( ((vertices_id[u], vertices_id[v]), 't', 1) 

for (u,v) in self.edges(labels=None) ) 

 

# each v is linked to its incident edges 

 

for u,v in self.edges(labels = None): 

u,v = vertices_id[u], vertices_id[v] 

d.add_edge(u, (u,v), 1) 

d.add_edge(v, (u,v), 1) 

 

# Solving the maximum flow 

value, flow = d.flow('s','t', value_only = False, integer = True, use_edge_labels = True) 

 

if value != self.size(): 

raise ValueError("No orientation exists for the given bound") 

 

D = DiGraph() 

D.add_vertices(vertices) 

 

# The flow graph may not contain all the vertices, if they are 

# not part of the flow... 

 

for u in [x for x in range(n) if x in flow]: 

 

for (uu,vv) in flow.neighbors_out(u): 

v = vv if vv != u else uu 

D.add_edge(vertices[u], vertices[v]) 

 

# I do not like when a method destroys the embedding ;-) 

 

D.set_pos(self.get_pos()) 

 

return D 

 

@doc_index("Connectivity, orientations, trees") 

def orientations(self, implementation='c_graph', data_structure=None, sparse=None): 

r""" 

Return an iterator over orientations of ``self``. 

 

An *orientation* of an undirected graph is a directed 

graph such that every edge is assigned a direction. 

Hence there are `2^s` oriented digraphs for a simple 

graph with `s` edges. 

 

INPUT: 

 

- ``data_structure`` -- one of ``"sparse"``, ``"static_sparse"``, or 

``"dense"``; see the documentation of :class:`Graph` or 

:class:`DiGraph`; default is the data structure of ``self`` 

 

- ``sparse`` -- (optional) boolean; ``sparse=True`` is an alias for 

``data_structure="sparse"``, and ``sparse=False`` is an alias for 

``data_structure="dense"`` 

 

.. WARNING:: 

 

This always considers multiple edges of graphs as 

distinguishable, and hence, may have repeated digraphs. 

 

EXAMPLES:: 

 

sage: G = Graph([[1,2,3], [(1, 2, 'a'), (1, 3, 'b')]], format='vertices_and_edges') 

sage: it = G.orientations() 

sage: D = next(it) 

sage: D.edges() 

[(1, 2, 'a'), (1, 3, 'b')] 

sage: D = next(it) 

sage: D.edges() 

[(1, 2, 'a'), (3, 1, 'b')] 

 

TESTS:: 

 

sage: G = Graph() 

sage: D = [g for g in G.orientations()] 

sage: len(D) 

1 

sage: D[0] 

Digraph on 0 vertices 

 

sage: G = Graph(5) 

sage: it = G.orientations() 

sage: D = next(it) 

sage: D.size() 

0 

 

sage: G = Graph([[1,2,'a'], [1,2,'b']], multiedges=True) 

sage: len(list(G.orientations())) 

4 

 

sage: G = Graph([[1,2], [1,1]], loops=True) 

sage: len(list(G.orientations())) 

2 

 

sage: G = Graph([[1,2],[2,3]]) 

sage: next(G.orientations()) 

Digraph on 3 vertices 

sage: G = graphs.PetersenGraph() 

sage: next(G.orientations()) 

An orientation of Petersen graph: Digraph on 10 vertices 

 

An orientation must have the same ground set of vertices as the original 

graph (:trac:`24366`):: 

 

sage: G = Graph(1) 

sage: next(G.orientations()) 

Digraph on 1 vertex 

""" 

if sparse is not None: 

if data_structure is not None: 

raise ValueError("cannot specify both 'sparse' and 'data_structure'") 

data_structure = "sparse" if sparse else "dense" 

if data_structure is None: 

from sage.graphs.base.dense_graph import DenseGraphBackend 

from sage.graphs.base.sparse_graph import SparseGraphBackend 

if isinstance(self._backend, DenseGraphBackend): 

data_structure = "dense" 

elif isinstance(self._backend, SparseGraphBackend): 

data_structure = "sparse" 

else: 

data_structure = "static_sparse" 

 

name = self.name() 

if name != '': 

name = 'An orientation of ' + name 

 

if self.num_edges() == 0: 

D = DiGraph(data=[self.vertices(), []], 

format='vertices_and_edges', 

name=name, 

pos=self._pos, 

multiedges=self.allows_multiple_edges(), 

loops=self.allows_loops(), 

implementation=implementation, 

data_structure=data_structure) 

if hasattr(self, '_embedding'): 

D._embedding = copy(self._embedding) 

yield D 

return 

 

from itertools import product 

E = [[(u,v,label), (v,u,label)] if u != v else [(u,v,label)] 

for u,v,label in self.edges()] 

verts = self.vertices() 

for edges in product(*E): 

D = DiGraph(data=[verts, edges], 

format='vertices_and_edges', 

name=name, 

pos=self._pos, 

multiedges=self.allows_multiple_edges(), 

loops=self.allows_loops(), 

implementation=implementation, 

data_structure=data_structure) 

if hasattr(self, '_embedding'): 

D._embedding = copy(self._embedding) 

yield D 

 

### Coloring 

 

@doc_index("Basic methods") 

def bipartite_color(self): 

""" 

Return a dictionary with vertices as the keys and the color class 

as the values. 

 

Fails with an error if the graph is not bipartite. 

 

EXAMPLES:: 

 

sage: graphs.CycleGraph(4).bipartite_color() 

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

sage: graphs.CycleGraph(5).bipartite_color() 

Traceback (most recent call last): 

... 

RuntimeError: Graph is not bipartite. 

 

TESTS:: 

 

sage: Graph().bipartite_color() 

{} 

""" 

isit, certificate = self.is_bipartite(certificate = True) 

 

if isit: 

return certificate 

else: 

raise RuntimeError("Graph is not bipartite.") 

 

@doc_index("Basic methods") 

def bipartite_sets(self): 

""" 

Return `(X,Y)` where `X` and `Y` are the nodes in each bipartite set of 

graph `G`. 

 

Fails with an error if graph is not bipartite. 

 

EXAMPLES:: 

 

sage: graphs.CycleGraph(4).bipartite_sets() 

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

sage: graphs.CycleGraph(5).bipartite_sets() 

Traceback (most recent call last): 

... 

RuntimeError: Graph is not bipartite. 

""" 

color = self.bipartite_color() 

left = set([]) 

right = set([]) 

 

for u,s in six.iteritems(color): 

if s: 

left.add(u) 

else: 

right.add(u) 

 

return left, right 

 

@doc_index("Algorithmically hard stuff") 

def chromatic_index(self, solver=None, verbose=0): 

r""" 

Return the chromatic index of the graph. 

 

The chromatic index is the minimal number of colors needed to properly 

color the edges of the graph. 

 

INPUT: 

 

- ``solver`` (default: ``None``) Specify the Linear Program (LP) solver 

to be used. If set to ``None``, the default one is used. For more 

information on LP solvers and which default solver is used, see the 

method :meth:`solve 

<sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class 

:class:`MixedIntegerLinearProgram 

<sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

This method is a frontend for method 

:meth:`sage.graphs.graph_coloring.edge_coloring` that uses a mixed 

integer-linear programming formulation to compute the chromatic index. 

 

.. SEEALSO:: 

 

- :wikipedia:`Edge_coloring` for further details on edge coloring 

- :meth:`sage.graphs.graph_coloring.edge_coloring` 

- :meth:`~Graph.fractional_chromatic_index` 

- :meth:`~Graph.chromatic_number` 

 

EXAMPLES: 

 

The clique `K_n` has chromatic index `n` when `n` is odd and `n-1` when 

`n` is even:: 

 

sage: graphs.CompleteGraph(4).chromatic_index() 

3 

sage: graphs.CompleteGraph(5).chromatic_index() 

5 

sage: graphs.CompleteGraph(6).chromatic_index() 

5 

 

The path `P_n` with `n \geq 2` has chromatic index 2:: 

 

sage: graphs.PathGraph(5).chromatic_index() 

2 

 

The windmill graph with parameters `k,n` has chromatic index `(k-1)n`:: 

 

sage: k,n = 3,4 

sage: G = graphs.WindmillGraph(k,n) 

sage: G.chromatic_index() == (k-1)*n 

True 

 

TESTS: 

 

Graphs without vertices or edges:: 

 

sage: Graph().chromatic_index() 

0 

sage: Graph(2).chromatic_index() 

0 

""" 

if self.order() == 0 or self.size() == 0: 

return 0 

 

from sage.graphs.graph_coloring import edge_coloring 

return edge_coloring(self, value_only=True, solver=solver, verbose=verbose) 

 

 

@doc_index("Algorithmically hard stuff") 

def chromatic_number(self, algorithm="DLX", verbose = 0): 

r""" 

Return the minimal number of colors needed to color the vertices 

of the graph. 

 

INPUT: 

 

- ``algorithm`` -- Select an algorithm from the following supported 

algorithms: 

 

- If ``algorithm="DLX"`` (default), the chromatic number is 

computed using the dancing link algorithm. It is 

inefficient speedwise to compute the chromatic number through 

the dancing link algorithm because this algorithm computes 

*all* the possible colorings to check that one exists. 

 

- If ``algorithm="CP"``, the chromatic number is computed 

using the coefficients of the chromatic polynomial. Again, this 

method is inefficient in terms of speed and it only useful for 

small graphs. 

 

- If ``algorithm="MILP"``, the chromatic number is computed using a 

mixed integer linear program. The performance of this implementation 

is affected by whether optional MILP solvers have been installed 

(see the :mod:`MILP module <sage.numerical.mip>`, or Sage's tutorial 

on Linear Programming). 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of verbosity 

for the MILP algorithm. Its default value is 0, which means *quiet*. 

 

.. SEEALSO:: 

 

For more functions related to graph coloring, see the 

module :mod:`sage.graphs.graph_coloring`. 

 

EXAMPLES:: 

 

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

sage: G.chromatic_number(algorithm="DLX") 

3 

sage: G.chromatic_number(algorithm="MILP") 

3 

sage: G.chromatic_number(algorithm="CP") 

3 

 

A bipartite graph has (by definition) chromatic number 2:: 

 

sage: graphs.RandomBipartite(50,50,0.7).chromatic_number() 

2 

 

A complete multipartite graph with k parts has chromatic number k:: 

 

sage: all(graphs.CompleteMultipartiteGraph([5]*i).chromatic_number() == i for i in range(2,5)) 

True 

 

The complete graph has the largest chromatic number from all the graphs 

of order n. Namely its chromatic number is n:: 

 

sage: all(graphs.CompleteGraph(i).chromatic_number() == i for i in range(10)) 

True 

 

The Kneser graph with parameters (n,2) for n > 3 has chromatic number n-2:: 

 

sage: all(graphs.KneserGraph(i,2).chromatic_number() == i-2 for i in range(4,6)) 

True 

 

A snark has chromatic index 4 hence its line graph has chromatic number 4:: 

 

sage: graphs.FlowerSnark().line_graph().chromatic_number() 

4 

 

TESTS:: 

 

sage: G = Graph() 

sage: G.chromatic_number(algorithm="DLX") 

0 

sage: G.chromatic_number(algorithm="MILP") 

0 

sage: G.chromatic_number(algorithm="CP") 

0 

 

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

sage: G.chromatic_number(algorithm="foo") 

Traceback (most recent call last): 

... 

ValueError: The 'algorithm' keyword must be set to either 'DLX', 'MILP' or 'CP'. 

""" 

self._scream_if_not_simple(allow_multiple_edges=True) 

# default built-in algorithm; bad performance 

if algorithm == "DLX": 

from sage.graphs.graph_coloring import chromatic_number 

return chromatic_number(self) 

# Algorithm with good performance, but requires an optional 

# package: choose any of GLPK or CBC. 

elif algorithm == "MILP": 

from sage.graphs.graph_coloring import vertex_coloring 

return vertex_coloring(self, value_only=True, verbose = verbose) 

# another algorithm with bad performance; only good for small graphs 

elif algorithm == "CP": 

f = self.chromatic_polynomial() 

i = 0 

while f(i) == 0: 

i += 1 

return i 

else: 

raise ValueError("The 'algorithm' keyword must be set to either 'DLX', 'MILP' or 'CP'.") 

 

@doc_index("Algorithmically hard stuff") 

def coloring(self, algorithm="DLX", hex_colors=False, verbose = 0): 

r""" 

Return the first (optimal) proper vertex-coloring found. 

 

INPUT: 

 

- ``algorithm`` -- Select an algorithm from the following supported 

algorithms: 

 

- If ``algorithm="DLX"`` (default), the coloring is computed using the 

dancing link algorithm. 

 

- If ``algorithm="MILP"``, the coloring is computed using a mixed 

integer linear program. The performance of this implementation is 

affected by whether optional MILP solvers have been installed (see 

the :mod:`MILP module <sage.numerical.mip>`). 

 

- ``hex_colors`` -- (default: ``False``) if ``True``, return a 

dictionary which can easily be used for plotting. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of verbosity 

for the MILP algorithm. Its default value is 0, which means *quiet*. 

 

.. SEEALSO:: 

 

For more functions related to graph coloring, see the 

module :mod:`sage.graphs.graph_coloring`. 

 

EXAMPLES:: 

 

sage: G = Graph("Fooba") 

sage: P = G.coloring(algorithm="MILP"); P 

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

sage: P = G.coloring(algorithm="DLX"); P 

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

sage: G.plot(partition=P) 

Graphics object consisting of 16 graphics primitives 

sage: H = G.coloring(hex_colors=True, algorithm="MILP") 

sage: for c in sorted(H.keys()): 

....: print("{} {}".format(c, H[c])) 

#0000ff [4] 

#00ff00 [0, 6, 5] 

#ff0000 [2, 1, 3] 

sage: H = G.coloring(hex_colors=True, algorithm="DLX") 

sage: for c in sorted(H.keys()): 

....: print("{} {}".format(c, H[c])) 

#0000ff [4] 

#00ff00 [1, 2, 3] 

#ff0000 [0, 5, 6] 

sage: G.plot(vertex_colors=H) 

Graphics object consisting of 16 graphics primitives 

 

.. PLOT:: 

 

g = Graph("Fooba") 

sphinx_plot(g.plot(partition=g.coloring())) 

 

TESTS:: 

 

sage: G.coloring(algorithm="foo") 

Traceback (most recent call last): 

... 

ValueError: The 'algorithm' keyword must be set to either 'DLX' or 'MILP'. 

""" 

self._scream_if_not_simple(allow_multiple_edges=True) 

if algorithm == "MILP": 

from sage.graphs.graph_coloring import vertex_coloring 

return vertex_coloring(self, hex_colors=hex_colors, verbose = verbose) 

elif algorithm == "DLX": 

from sage.graphs.graph_coloring import first_coloring 

return first_coloring(self, hex_colors=hex_colors) 

else: 

raise ValueError("The 'algorithm' keyword must be set to either 'DLX' or 'MILP'.") 

 

@doc_index("Algorithmically hard stuff") 

def chromatic_symmetric_function(self, R=None): 

r""" 

Return the chromatic symmetric function of ``self``. 

 

Let `G` be a graph. The chromatic symmetric function `X_G` was 

described in [Stanley95]_, specifically Theorem 2.5 states that 

 

.. MATH:: 

 

X_G = \sum_{F \subseteq E(G)} (-1)^{|F|} p_{\lambda(F)}, 

 

where `\lambda(F)` is the partition of the sizes of the connected 

components of the subgraph induced by the edges `F` and `p_{\mu}` 

is the powersum symmetric function. 

 

INPUT: 

 

- ``R`` -- (optional) the base ring for the symmetric functions; 

this uses `\ZZ` by default 

 

EXAMPLES:: 

 

sage: s = SymmetricFunctions(ZZ).s() 

sage: G = graphs.CycleGraph(5) 

sage: XG = G.chromatic_symmetric_function(); XG 

p[1, 1, 1, 1, 1] - 5*p[2, 1, 1, 1] + 5*p[2, 2, 1] 

+ 5*p[3, 1, 1] - 5*p[3, 2] - 5*p[4, 1] + 4*p[5] 

sage: s(XG) 

30*s[1, 1, 1, 1, 1] + 10*s[2, 1, 1, 1] + 10*s[2, 2, 1] 

 

Not all graphs have a positive Schur expansion:: 

 

sage: G = graphs.ClawGraph() 

sage: XG = G.chromatic_symmetric_function(); XG 

p[1, 1, 1, 1] - 3*p[2, 1, 1] + 3*p[3, 1] - p[4] 

sage: s(XG) 

8*s[1, 1, 1, 1] + 5*s[2, 1, 1] - s[2, 2] + s[3, 1] 

 

We show that given a triangle `\{e_1, e_2, e_3\}`, we have 

`X_G = X_{G - e_1} + X_{G - e_2} - X_{G - e_1 - e_2}`:: 

 

sage: G = Graph([[1,2],[1,3],[2,3]]) 

sage: XG = G.chromatic_symmetric_function() 

sage: G1 = copy(G) 

sage: G1.delete_edge([1,2]) 

sage: XG1 = G1.chromatic_symmetric_function() 

sage: G2 = copy(G) 

sage: G2.delete_edge([1,3]) 

sage: XG2 = G2.chromatic_symmetric_function() 

sage: G3 = copy(G1) 

sage: G3.delete_edge([1,3]) 

sage: XG3 = G3.chromatic_symmetric_function() 

sage: XG == XG1 + XG2 - XG3 

True 

 

REFERENCES: 

 

.. [Stanley95] \R. P. Stanley, *A symmetric function generalization 

of the chromatic polynomial of a graph*, Adv. Math., ***111*** 

no.1 (1995), 166-194. 

""" 

from sage.combinat.sf.sf import SymmetricFunctions 

from sage.combinat.partition import _Partitions 

from sage.misc.misc import powerset 

if R is None: 

R = ZZ 

p = SymmetricFunctions(R).p() 

ret = p.zero() 

for F in powerset(self.edges()): 

la = _Partitions(self.subgraph(edges=F).connected_components_sizes()) 

ret += (-1)**len(F) * p[la] 

return ret 

 

@doc_index("Algorithmically hard stuff") 

def chromatic_quasisymmetric_function(self, t=None, R=None): 

r""" 

Return the chromatic quasisymmetric function of ``self``. 

 

Let `G` be a graph whose vertex set is totally ordered. The 

chromatic quasisymmetric function `X_G(t)` was first 

described in [SW12]_. We use the equivalent definition 

given in [BC15]_: 

 

.. MATH:: 

 

X_G(t) = \sum_{\sigma=(\sigma_1,\ldots,\sigma_n)} 

t^{\operatorname{asc}(\sigma)} 

M_{|\sigma_1|,\ldots,|\sigma_n|}, 

 

where we sum over all ordered set partitions of the vertex 

set of `G` such that each block `\sigma_i` is an independent 

(i.e., stable) set of `G`, and where 

`\operatorname{asc}(\sigma)` denotes the number of edges 

`\{u, v\}` of `G` such that `u < v` and `v` appears in a 

later part of `\sigma` than `u`. 

 

INPUT: 

 

- ``t`` -- (optional) the parameter `t`; uses the variable `t` 

in `\ZZ[t]` by default 

- ``R`` -- (optional) the base ring for the quasisymmetric 

functions; uses the parent of `t` by default 

 

EXAMPLES:: 

 

sage: G = Graph([[1,2,3], [[1,3], [2,3]]]) 

sage: G.chromatic_quasisymmetric_function() 

(2*t^2+2*t+2)*M[1, 1, 1] + M[1, 2] + t^2*M[2, 1] 

sage: G = graphs.PathGraph(4) 

sage: XG = G.chromatic_quasisymmetric_function(); XG 

(t^3+11*t^2+11*t+1)*M[1, 1, 1, 1] + (3*t^2+3*t)*M[1, 1, 2] 

+ (3*t^2+3*t)*M[1, 2, 1] + (3*t^2+3*t)*M[2, 1, 1] 

+ (t^2+t)*M[2, 2] 

sage: XG.to_symmetric_function() 

(t^3+11*t^2+11*t+1)*m[1, 1, 1, 1] + (3*t^2+3*t)*m[2, 1, 1] 

+ (t^2+t)*m[2, 2] 

sage: G = graphs.CompleteGraph(4) 

sage: G.chromatic_quasisymmetric_function() 

(t^6+3*t^5+5*t^4+6*t^3+5*t^2+3*t+1)*M[1, 1, 1, 1] 

 

Not all chromatic quasisymmetric functions are symmetric:: 

 

sage: G = Graph([[1,2], [1,5], [3,4], [3,5]]) 

sage: G.chromatic_quasisymmetric_function().is_symmetric() 

False 

 

We check that at `t = 1`, we recover the usual chromatic 

symmetric function:: 

 

sage: p = SymmetricFunctions(QQ).p() 

sage: G = graphs.CycleGraph(5) 

sage: XG = G.chromatic_quasisymmetric_function(t=1); XG 

120*M[1, 1, 1, 1, 1] + 30*M[1, 1, 1, 2] + 30*M[1, 1, 2, 1] 

+ 30*M[1, 2, 1, 1] + 10*M[1, 2, 2] + 30*M[2, 1, 1, 1] 

+ 10*M[2, 1, 2] + 10*M[2, 2, 1] 

sage: p(XG.to_symmetric_function()) 

p[1, 1, 1, 1, 1] - 5*p[2, 1, 1, 1] + 5*p[2, 2, 1] 

+ 5*p[3, 1, 1] - 5*p[3, 2] - 5*p[4, 1] + 4*p[5] 

 

sage: G = graphs.ClawGraph() 

sage: XG = G.chromatic_quasisymmetric_function(t=1); XG 

24*M[1, 1, 1, 1] + 6*M[1, 1, 2] + 6*M[1, 2, 1] + M[1, 3] 

+ 6*M[2, 1, 1] + M[3, 1] 

sage: p(XG.to_symmetric_function()) 

p[1, 1, 1, 1] - 3*p[2, 1, 1] + 3*p[3, 1] - p[4] 

 

REFERENCES: 

 

.. [SW12] John Shareshian and Michelle Wachs. 

*Chromatic quasisymmetric functions and Hessenberg varieties*. 

Configuration Spaces. CRM Series. Scuola Normale Superiore. 

(2012) pp. 433-460. 

http://www.math.miami.edu/~wachs/papers/chrom.pdf 

 

.. [BC15] Patrick Brosnan and Timothy Y. Chow. 

*Unit interval orders and the dot action on the cohomology 

of regular semisimple Hessenberg varieties*. 

(2015) :arxiv:`1511.00773v1`. 

""" 

from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions 

from sage.combinat.composition import Compositions 

from sage.combinat.set_partition_ordered import OrderedSetPartitions 

if t is None: 

t = ZZ['t'].gen() 

if R is None: 

R = t.parent() 

M = QuasiSymmetricFunctions(R).M() 

ret = M.zero() 

V = self.vertices() 

def asc(sigma): 

stat = 0 

for i, s in enumerate(sigma): 

for u in s: 

stat += sum(1 for p in sigma[i+1:] for v in p 

if v > u and self.has_edge(u, v)) 

return stat 

for sigma in OrderedSetPartitions(V): 

if any(not self.is_independent_set(s) for s in sigma): 

continue 

ret += M.term(sigma.to_composition(), t**asc(sigma)) 

return ret 

 

@doc_index("Leftovers") 

def matching(self, value_only=False, algorithm="Edmonds", 

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

r""" 

Return a maximum weighted matching of the graph 

represented by the list of its edges. 

 

For more information, see the `Wikipedia article on matchings 

<http://en.wikipedia.org/wiki/Matching_%28graph_theory%29>`_. 

 

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. 

 

As an optimization problem, it can be expressed as: 

 

.. MATH:: 

 

\mbox{Maximize : }&\sum_{e\in G.edges()} w_e b_e\\ 

\mbox{Such that : }&\forall v \in G, 

\sum_{(u,v)\in G.edges()} b_{(u,v)}\leq 1\\ 

&\forall x\in G, b_x\mbox{ is a binary variable} 

 

INPUT: 

 

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

``True``, only the cardinal (or the weight) of the matching is 

returned 

 

- ``algorithm`` -- string (default: ``"Edmonds"``) 

 

- ``"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) 

 

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

 

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

solver to be used; if set to ``None``, the default one is used 

 

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

verbosity: set to 0 by default, which means quiet 

(only useful when ``algorithm == "LP"``) 

 

For more information on LP solvers and which default solver is 

used, see the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class :class:`MixedIntegerLinearProgram 

<sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

ALGORITHM: 

 

The problem is solved using Edmond's algorithm implemented in 

NetworkX, or using Linear Programming depending on the value of 

``algorithm``. 

 

EXAMPLES: 

 

Maximum matching in a Pappus Graph:: 

 

sage: g = graphs.PappusGraph() 

sage: g.matching(value_only=True) 

9 

 

Same test with the Linear Program formulation:: 

 

sage: g = graphs.PappusGraph() 

sage: g.matching(algorithm="LP", value_only=True) 

9 

 

.. PLOT:: 

 

g = graphs.PappusGraph() 

sphinx_plot(g.plot(edge_colors={"red":g.matching()})) 

 

TESTS: 

 

When ``use_edge_labels`` is set to ``False``, 

with Edmonds' algorithm and LP formulation:: 

 

sage: g = Graph([(0,1,0), (1,2,999), (2,3,-5)]) 

sage: g.matching() 

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

sage: g.matching(algorithm="LP") 

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

 

When ``use_edge_labels`` is set to ``True``, 

with Edmonds' algorithm and LP formulation:: 

 

sage: g = Graph([(0,1,0), (1,2,999), (2,3,-5)]) 

sage: g.matching(use_edge_labels=True) 

[(1, 2, 999)] 

sage: g.matching(algorithm="LP", use_edge_labels=True) 

[(1, 2, 999)] 

 

With loops and multiedges:: 

 

sage: edge_list = [(0,0,5), (0,1,1), (0,2,2), (0,3,3), (1,2,6) 

....: , (1,2,3), (1,3,3), (2,3,3)] 

sage: g = Graph(edge_list, loops=True, multiedges=True) 

sage: g.matching(use_edge_labels=True) 

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

 

 

TESTS: 

 

If ``algorithm`` is set to anything different from ``"Edmonds"`` or 

``"LP"``, an exception is raised:: 

 

sage: g = graphs.PappusGraph() 

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

Traceback (most recent call last): 

... 

ValueError: algorithm must be set to either "Edmonds" or "LP" 

""" 

from sage.rings.real_mpfr import RR 

def weight(x): 

if x in RR: 

return x 

else: 

return 1 

 

W = dict() 

L = dict() 

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

if u is v: 

continue 

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) 

 

if algorithm == "Edmonds": 

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) 

d = networkx.max_weight_matching(g) 

if value_only: 

if use_edge_labels: 

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

else: 

return Integer(len(d) // 2) 

else: 

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

 

elif algorithm == "LP": 

g = self 

from sage.numerical.mip import MixedIntegerLinearProgram 

# returns the weight of an edge considering it may not be 

# weighted ... 

p = MixedIntegerLinearProgram(maximization=True, solver=solver) 

b = p.new_variable(binary=True) 

if use_edge_labels: 

p.set_objective( p.sum( W[u, v] * b[u, v] for u, v in W ) ) 

else: 

p.set_objective( p.sum( b[u, v] for u, v in L ) ) 

# for any vertex v, there is at most one edge incident to v in 

# the maximum matching 

for v in g.vertex_iterator(): 

p.add_constraint( 

p.sum(b[min(u, v), max(u,v)] 

for u in self.neighbors(v) if u != v), max=1) 

if value_only: 

if use_edge_labels: 

return p.solve(objective_only=True, log=verbose) 

else: 

return Integer(round(p.solve(objective_only=True, log=verbose))) 

else: 

p.solve(log=verbose) 

b = p.get_values(b) 

return [(u, v, L[u, v]) for u, v in L if b[u, v] == 1] 

 

else: 

raise ValueError('algorithm must be set to either "Edmonds" or "LP"') 

 

 

@doc_index("Algorithmically hard stuff") 

def has_homomorphism_to(self, H, core = False, solver = None, verbose = 0): 

r""" 

Checks whether there is a homomorphism between two graphs. 

 

A homomorphism from a graph `G` to a graph `H` is a function 

`\phi:V(G)\mapsto V(H)` such that for any edge `uv \in E(G)` the pair 

`\phi(u)\phi(v)` is an edge of `H`. 

 

Saying that a graph can be `k`-colored is equivalent to saying that it 

has a homomorphism to `K_k`, the complete graph on `k` elements. 

 

For more information, see the `Wikipedia article on graph homomorphisms 

<Graph_homomorphism>`_. 

 

INPUT: 

 

- ``H`` -- the graph to which ``self`` should be sent. 

 

- ``core`` (boolean) -- whether to minimize the size of the mapping's 

image (see note below). This is set to ``False`` by default. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

.. NOTE:: 

 

One can compute the core of a graph (with respect to homomorphism) 

with this method :: 

 

sage: g = graphs.CycleGraph(10) 

sage: mapping = g.has_homomorphism_to(g, core = True) 

sage: print("The size of the core is {}".format(len(set(mapping.values())))) 

The size of the core is 2 

 

OUTPUT: 

 

This method returns ``False`` when the homomorphism does not exist, and 

returns the homomorphism otherwise as a dictionary associating a vertex 

of `H` to a vertex of `G`. 

 

EXAMPLES: 

 

Is Petersen's graph 3-colorable:: 

 

sage: P = graphs.PetersenGraph() 

sage: P.has_homomorphism_to(graphs.CompleteGraph(3)) is not False 

True 

 

An odd cycle admits a homomorphism to a smaller odd cycle, but not to an 

even cycle:: 

 

sage: g = graphs.CycleGraph(9) 

sage: g.has_homomorphism_to(graphs.CycleGraph(5)) is not False 

True 

sage: g.has_homomorphism_to(graphs.CycleGraph(7)) is not False 

True 

sage: g.has_homomorphism_to(graphs.CycleGraph(4)) is not False 

False 

""" 

self._scream_if_not_simple() 

from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException 

p = MixedIntegerLinearProgram(solver=solver, maximization = False) 

b = p.new_variable(binary = True) 

 

# Each vertex has an image 

for ug in self: 

p.add_constraint(p.sum(b[ug,uh] for uh in H) == 1) 

 

nonedges = H.complement().edges(labels = False) 

for ug,vg in self.edges(labels = False): 

# Two adjacent vertices cannot be mapped to the same element 

for uh in H: 

p.add_constraint(b[ug,uh] + b[vg,uh] <= 1) 

 

# Two adjacent vertices cannot be mapped to no adjacent vertices 

for uh,vh in nonedges: 

p.add_constraint(b[ug,uh] + b[vg,vh] <= 1) 

p.add_constraint(b[ug,vh] + b[vg,uh] <= 1) 

 

# Minimize the mapping's size 

if core: 

 

# the value of m is one if the corresponding vertex of h is used. 

m = p.new_variable(nonnegative=True) 

for uh in H: 

for ug in self: 

p.add_constraint(b[ug,uh] <= m[uh]) 

 

p.set_objective(p.sum(m[vh] for vh in H)) 

 

try: 

p.solve(log = verbose) 

b = p.get_values(b) 

mapping = dict(x[0] for x in b.items() if x[1]) 

return mapping 

 

except MIPSolverException: 

return False 

 

@doc_index("Leftovers") 

def fractional_chromatic_index(self, solver="PPL", verbose_constraints=False, verbose=0): 

r""" 

Return the fractional chromatic index of the graph. 

 

The fractional chromatic index is a relaxed version of edge-coloring. An 

edge coloring of a graph being actually a covering of its edges into the 

smallest possible number of matchings, the fractional chromatic index of 

a graph `G` is the smallest real value `\chi_f(G)` such that there 

exists a list of matchings `M_1, ..., M_k` of `G` and coefficients 

`\alpha_1, ..., \alpha_k` with the property that each edge is covered by 

the matchings in the following relaxed way 

 

.. MATH:: 

 

\forall e \in E(G), \sum_{e \in M_i} \alpha_i \geq 1 

 

For more information, see :wikipedia:`Fractional_coloring`. 

 

ALGORITHM: 

 

The fractional chromatic index is computed through Linear Programming 

through its dual. The LP solved by sage is actually: 

 

.. MATH:: 

 

\mbox{Maximize : }&\sum_{e\in E(G)} r_{e}\\ 

\mbox{Such that : }&\\ 

&\forall M\text{ matching }\subseteq G, \sum_{e\in M}r_{v}\leq 1\\ 

 

INPUT: 

 

- ``solver`` -- (default: ``"PPL"``) Specify a Linear Program (LP) 

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

.. NOTE:: 

 

The default solver used here is ``"PPL"`` which provides exact 

results, i.e. a rational number, although this may be slower that 

using other solvers. Be aware that this method may loop endlessly 

when using some non exact solvers as reported in :trac:`23658` and 

:trac:`23798`. 

 

- ``verbose_constraints`` -- boolean (default: ``False``) whether to 

display which constraints are being generated. 

 

- ``verbose`` -- integer (default: `0`) level of verbosity required from 

the LP solver 

 

EXAMPLES: 

 

The fractional chromatic index of a `C_5` is `5/2`:: 

 

sage: g = graphs.CycleGraph(5) 

sage: g.fractional_chromatic_index() 

5/2 

 

TESTS: 

 

Issue reported in :trac:`23658` and :trac:`23798` with non exact solvers:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.fractional_chromatic_index(solver='GLPK') # known bug (#23798) 

3.0 

sage: g.fractional_chromatic_index(solver='PPL') 

3 

""" 

self._scream_if_not_simple() 

 

if not self.order(): 

return 0 

if not self.size(): 

return 1 

 

from sage.numerical.mip import MixedIntegerLinearProgram 

 

# 

# Initialize LP for maximum weigth matching 

M = MixedIntegerLinearProgram(solver=solver, constraint_generation=True) 

 

# One variable per edge 

b = M.new_variable(binary=True, nonnegative=True) 

B = lambda x,y : b[x,y] if x<y else b[y,x] 

 

# We want to select at most one incident edge per vertex (matching) 

for u in self.vertex_iterator(): 

M.add_constraint( M.sum( B(x,y) for x,y in self.edges_incident(u, labels=0) ) <= 1 ) 

 

# 

# Initialize LP for fractional chromatic number 

p = MixedIntegerLinearProgram(solver=solver, constraint_generation=True) 

 

# One variable per edge 

r = p.new_variable(nonnegative=True) 

R = lambda x,y : r[x,y] if x<y else r[y,x] 

 

# We want to maximize the sum of weights on the edges 

p.set_objective( p.sum( R(u,v) for u,v in self.edge_iterator(labels=False))) 

 

# Each edge being by itself a matching, its weight can not be more than 

# 1 

for u,v in self.edge_iterator(labels=False): 

p.add_constraint( R(u,v), max = 1) 

 

obj = p.solve(log=verbose) 

 

while True: 

 

# Update the weights of edges for the matching problem 

M.set_objective( M.sum( p.get_values(R(u,v)) * B(u,v) for u,v in self.edge_iterator(labels=0) ) ) 

 

# If the maximum matching has weight at most 1, we are done ! 

if M.solve(log=verbose) <= 1: 

break 

 

# Otherwise, we add a new constraint 

matching = [(u,v) for u,v in self.edge_iterator(labels=0) if M.get_values(B(u,v)) == 1] 

p.add_constraint( p.sum( R(u,v) for u,v in matching), max=1) 

if verbose_constraints: 

print("Adding a constraint on matching : {}".format(matching)) 

 

# And solve again 

obj = p.solve(log=verbose) 

 

# Accomplished ! 

return obj 

 

@doc_index("Leftovers") 

def maximum_average_degree(self, value_only=True, solver=None, verbose=0): 

r""" 

Return the Maximum Average Degree (MAD) of the current graph. 

 

The Maximum Average Degree (MAD) of a graph is defined as 

the average degree of its densest subgraph. More formally, 

``Mad(G) = \max_{H\subseteq G} Ad(H)``, where `Ad(G)` denotes 

the average degree of `G`. 

 

This can be computed in polynomial time. 

 

INPUT: 

 

- ``value_only`` (boolean) -- ``True`` by default 

 

- If ``value_only=True``, only the numerical 

value of the `MAD` is returned. 

 

- Else, the subgraph of `G` realizing the `MAD` 

is returned. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

EXAMPLES: 

 

In any graph, the `Mad` is always larger than the average 

degree:: 

 

sage: g = graphs.RandomGNP(20,.3) 

sage: mad_g = g.maximum_average_degree() 

sage: g.average_degree() <= mad_g 

True 

 

Unlike the average degree, the `Mad` of the disjoint 

union of two graphs is the maximum of the `Mad` of each 

graphs:: 

 

sage: h = graphs.RandomGNP(20,.3) 

sage: mad_h = h.maximum_average_degree() 

sage: (g+h).maximum_average_degree() == max(mad_g, mad_h) 

True 

 

The subgraph of a regular graph realizing the maximum 

average degree is always the whole graph :: 

 

sage: g = graphs.CompleteGraph(5) 

sage: mad_g = g.maximum_average_degree(value_only=False) 

sage: g.is_isomorphic(mad_g) 

True 

 

This also works for complete bipartite graphs :: 

 

sage: g = graphs.CompleteBipartiteGraph(3,4) 

sage: mad_g = g.maximum_average_degree(value_only=False) 

sage: g.is_isomorphic(mad_g) 

True 

""" 

self._scream_if_not_simple() 

g = self 

from sage.numerical.mip import MixedIntegerLinearProgram 

 

p = MixedIntegerLinearProgram(maximization=True, solver = solver) 

 

d = p.new_variable(nonnegative=True) 

one = p.new_variable(nonnegative=True) 

 

# Reorders u and v so that uv and vu are not considered 

# to be different edges 

reorder = lambda u,v : (min(u,v),max(u,v)) 

 

for u,v in g.edge_iterator(labels=False): 

p.add_constraint( one[ reorder(u,v) ] - 2*d[u] , max = 0 ) 

p.add_constraint( one[ reorder(u,v) ] - 2*d[v] , max = 0 ) 

 

p.add_constraint( p.sum(d[v] for v in g), max = 1) 

 

p.set_objective( p.sum( one[reorder(u,v)] for u,v in g.edge_iterator(labels=False)) ) 

 

obj = p.solve(log = verbose) 

 

# Paying attention to numerical error : 

# The zero values could be something like 0.000000000001 

# so I can not write l > 0 

# And the non-zero, though they should be equal to 

# 1/(order of the optimal subgraph) may be a bit lower 

 

# setting the minimum to 1/(10 * size of the whole graph ) 

# should be safe :-) 

m = 1/(10 *Integer(g.order())) 

g_mad = g.subgraph([v for v,l in six.iteritems(p.get_values(d)) if l>m ]) 

 

if value_only: 

return g_mad.average_degree() 

else: 

return g_mad 

 

@doc_index("Algorithmically hard stuff") 

def independent_set_of_representatives(self, family, solver=None, verbose=0): 

r""" 

Return an independent set of representatives. 

 

Given a graph `G` and a family `F=\{F_i:i\in [1,...,k]\}` of 

subsets of ``g.vertices()``, an Independent Set of Representatives 

(ISR) is an assignation of a vertex `v_i\in F_i` to each set `F_i` 

such that `v_i != v_j` if `i<j` (they are representatives) and the 

set `\cup_{i}v_i` is an independent set in `G`. 

 

It generalizes, for example, graph coloring and graph list coloring. 

 

(See [AhaBerZiv07]_ for more information.) 

 

INPUT: 

 

- ``family`` -- A list of lists defining the family `F` 

(actually, a Family of subsets of ``G.vertices()``). 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

OUTPUT: 

 

- A list whose `i^{\mbox{th}}` element is the representative of the 

`i^{\mbox{th}}` element of the ``family`` list. If there is no ISR, 

``None`` is returned. 

 

EXAMPLES: 

 

For a bipartite graph missing one edge, the solution is as expected:: 

 

sage: g = graphs.CompleteBipartiteGraph(3,3) 

sage: g.delete_edge(1,4) 

sage: g.independent_set_of_representatives([[0,1,2],[3,4,5]]) 

[1, 4] 

 

The Petersen Graph is 3-colorable, which can be expressed as an 

independent set of representatives problem : take 3 disjoint copies 

of the Petersen Graph, each one representing one color. Then take 

as a partition of the set of vertices the family defined by the three 

copies of each vertex. The ISR of such a family 

defines a 3-coloring:: 

 

sage: g = 3 * graphs.PetersenGraph() 

sage: n = g.order()/3 

sage: f = [[i,i+n,i+2*n] for i in range(n)] 

sage: isr = g.independent_set_of_representatives(f) 

sage: c = [floor(i/n) for i in isr] 

sage: color_classes = [[],[],[]] 

sage: for v,i in enumerate(c): 

....: color_classes[i].append(v) 

sage: for classs in color_classes: 

....: g.subgraph(classs).size() == 0 

True 

True 

True 

 

REFERENCE: 

 

.. [AhaBerZiv07] \R. Aharoni and E. Berger and R. Ziv 

Independent systems of representatives in weighted graphs 

Combinatorica vol 27, num 3, p253--267 

2007 

 

""" 

 

from sage.numerical.mip import MixedIntegerLinearProgram 

p=MixedIntegerLinearProgram(solver=solver) 

 

# Boolean variable indicating whether the vertex 

# is the representative of some set 

vertex_taken=p.new_variable(binary=True) 

 

# Boolean variable in two dimension whose first 

# element is a vertex and whose second element 

# is one of the sets given as arguments. 

# When true, indicated that the vertex is the representant 

# of the corresponding set 

 

classss=p.new_variable(binary = True) 

 

# Associates to the vertices the classes 

# to which they belong 

 

lists=dict([(v,[]) for v in self.vertex_iterator()]) 

for i,f in enumerate(family): 

[lists[v].append(i) for v in f] 

 

# a classss has exactly one representant 

p.add_constraint(p.sum(classss[v,i] for v in f), max=1, min=1) 

 

# A vertex represents at most one classss (vertex_taken is binary), and 

# vertex_taken[v]==1 if v is the representative of some classss 

 

[p.add_constraint(p.sum(classss[v,i] for i in lists[v]) - vertex_taken[v], max=0) for v in self.vertex_iterator()] 

 

# Two adjacent vertices can not both be representants of a set 

 

for (u,v) in self.edges(labels=None): 

p.add_constraint(vertex_taken[u]+vertex_taken[v],max=1) 

 

p.set_objective(None) 

 

try: 

p.solve(log=verbose) 

except Exception: 

return None 

 

classss=p.get_values(classss) 

 

repr=[] 

for i,f in enumerate(family): 

for v in f: 

if classss[v,i]==1: 

repr.append(v) 

break 

 

return repr 

 

@doc_index("Algorithmically hard stuff") 

def minor(self, H, solver=None, verbose=0): 

r""" 

Return the vertices of a minor isomorphic to `H` in the current graph. 

 

We say that a graph `G` has a `H`-minor (or that it has 

a graph isomorphic to `H` as a minor), if for all `h\in H`, 

there exist disjoint sets `S_h \subseteq V(G)` such that 

once the vertices of each `S_h` have been merged to create 

a new graph `G'`, this new graph contains `H` as a subgraph. 

 

For more information, see the 

`Wikipedia article on graph minor <http://en.wikipedia.org/wiki/Minor_%28graph_theory%29>`_. 

 

INPUT: 

 

- ``H`` -- The minor to find for in the current graph. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

OUTPUT: 

 

A dictionary associating to each vertex of `H` the set of vertices 

in the current graph representing it. 

 

ALGORITHM: 

 

Mixed Integer Linear Programming 

 

COMPLEXITY: 

 

Theoretically, when `H` is fixed, testing for the existence of 

a `H`-minor is polynomial. The known algorithms are highly 

exponential in `H`, though. 

 

.. NOTE:: 

 

This function can be expected to be *very* slow, especially 

where the minor does not exist. 

 

EXAMPLES: 

 

Trying to find a minor isomorphic to `K_4` in 

the `4\times 4` grid:: 

 

sage: g = graphs.GridGraph([4,4]) 

sage: h = graphs.CompleteGraph(4) 

sage: L = g.minor(h) 

sage: gg = g.subgraph(flatten(L.values(), max_level = 1)) 

sage: _ = [gg.merge_vertices(l) for l in L.values() if len(l)>1] 

sage: gg.is_isomorphic(h) 

True 

 

We can also try to prove this way that the Petersen graph 

is not planar, as it has a `K_5` minor:: 

 

sage: g = graphs.PetersenGraph() 

sage: K5_minor = g.minor(graphs.CompleteGraph(5)) # long time 

 

And even a `K_{3,3}` minor:: 

 

sage: K33_minor = g.minor(graphs.CompleteBipartiteGraph(3,3)) # long time 

 

(It is much faster to use the linear-time test of 

planarity in this situation, though.) 

 

As there is no cycle in a tree, looking for a `K_3` minor is useless. 

This function will raise an exception in this case:: 

 

sage: g = graphs.RandomGNP(20,.5) 

sage: g = g.subgraph(edges = g.min_spanning_tree()) 

sage: g.is_tree() 

True 

sage: L = g.minor(graphs.CompleteGraph(3)) 

Traceback (most recent call last): 

... 

ValueError: This graph has no minor isomorphic to H ! 

""" 

self._scream_if_not_simple() 

H._scream_if_not_simple() 

from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException 

p = MixedIntegerLinearProgram(solver=solver) 

 

# sorts an edge 

S = lambda x_y: x_y if x_y[0] < x_y[1] else (x_y[1], x_y[0]) 

 

# rs = Representative set of a vertex 

# for h in H, v in G is such that rs[h,v] == 1 if and only if v 

# is a representant of h in self 

rs = p.new_variable(binary = True) 

 

for v in self: 

p.add_constraint(p.sum(rs[h,v] for h in H), max = 1) 

 

# We ensure that the set of representatives of a 

# vertex h contains a tree, and thus is connected 

 

# edges represents the edges of the tree 

edges = p.new_variable(binary = True) 

 

# there can be a edge for h between two vertices 

# only if those vertices represent h 

for u,v in self.edges(labels=None): 

for h in H: 

p.add_constraint(edges[h,S((u,v))] - rs[h,u], max = 0 ) 

p.add_constraint(edges[h,S((u,v))] - rs[h,v], max = 0 ) 

 

# The number of edges of the tree in h is exactly the cardinal 

# of its representative set minus 1 

 

for h in H: 

p.add_constraint(p.sum(edges[h,S(e)] for e in self.edges(labels=None))-p.sum(rs[h,v] for v in self), min=-1, max=-1) 

 

# a tree has no cycle 

epsilon = 1/(5*Integer(self.order())) 

r_edges = p.new_variable(nonnegative=True) 

 

for h in H: 

for u,v in self.edges(labels=None): 

p.add_constraint(r_edges[h,(u,v)] + r_edges[h,(v,u)] - edges[h,S((u,v))], min = 0) 

 

for v in self: 

p.add_constraint(p.sum(r_edges[h,(u,v)] for u in self.neighbors(v)), max = 1-epsilon) 

 

# Once the representative sets are described, we must ensure 

# there are arcs corresponding to those of H between them 

h_edges = p.new_variable(nonnegative=True) 

 

for h1, h2 in H.edges(labels=None): 

 

for v1, v2 in self.edges(labels=None): 

 

p.add_constraint(h_edges[(h1,h2),S((v1,v2))] - rs[h2,v2], max = 0) 

p.add_constraint(h_edges[(h1,h2),S((v1,v2))] - rs[h1,v1], max = 0) 

 

p.add_constraint(h_edges[(h2,h1),S((v1,v2))] - rs[h1,v2], max = 0) 

p.add_constraint(h_edges[(h2,h1),S((v1,v2))] - rs[h2,v1], max = 0) 

 

p.add_constraint(p.sum(h_edges[(h1,h2),S(e)] + h_edges[(h2,h1),S(e)] for e in self.edges(labels=None) ), min = 1) 

 

p.set_objective(None) 

 

try: 

p.solve(log=verbose) 

except MIPSolverException: 

raise ValueError("This graph has no minor isomorphic to H !") 

 

rs = p.get_values(rs) 

 

rs_dict = {} 

for h in H: 

rs_dict[h] = [v for v in self if rs[h,v]==1] 

 

return rs_dict 

 

### Convexity 

 

@doc_index("Algorithmically hard stuff") 

def convexity_properties(self): 

r""" 

Return a ``ConvexityProperties`` object corresponding to ``self``. 

 

This object contains the methods related to convexity in graphs (convex 

hull, hull number) and caches useful information so that it becomes 

comparatively cheaper to compute the convex hull of many different sets 

of the same graph. 

 

.. SEEALSO:: 

 

In order to know what can be done through this object, please refer 

to module :mod:`sage.graphs.convexity_properties`. 

 

.. NOTE:: 

 

If you want to compute many convex hulls, keep this object in memory 

! When it is created, it builds a table of useful information to 

compute convex hulls. As a result :: 

 

sage: g = graphs.PetersenGraph() 

sage: g.convexity_properties().hull([1, 3]) 

[1, 2, 3] 

sage: g.convexity_properties().hull([3, 7]) 

[2, 3, 7] 

 

Is a terrible waste of computations, while :: 

 

sage: g = graphs.PetersenGraph() 

sage: CP = g.convexity_properties() 

sage: CP.hull([1, 3]) 

[1, 2, 3] 

sage: CP.hull([3, 7]) 

[2, 3, 7] 

 

Makes perfect sense. 

""" 

from sage.graphs.convexity_properties import ConvexityProperties 

return ConvexityProperties(self) 

 

# Centrality 

@doc_index("Distances") 

def centrality_degree(self, v=None): 

r""" 

Return the degree centrality of a vertex. 

 

The degree centrality of a vertex `v` is its degree, divided by 

`|V(G)|-1`. For more information, see the :wikipedia:`Centrality`. 

 

INPUT: 

 

- ``v`` - a vertex. Set to ``None`` (default) to get a dictionary 

associating each vertex with its centrality degree. 

 

.. SEEALSO:: 

 

- :meth:`~sage.graphs.generic_graph.GenericGraph.centrality_closeness` 

- :meth:`~sage.graphs.generic_graph.GenericGraph.centrality_betweenness` 

 

EXAMPLES:: 

 

sage: (graphs.ChvatalGraph()).centrality_degree() 

{0: 4/11, 1: 4/11, 2: 4/11, 3: 4/11, 4: 4/11, 5: 4/11, 

6: 4/11, 7: 4/11, 8: 4/11, 9: 4/11, 10: 4/11, 11: 4/11} 

sage: D = graphs.DiamondGraph() 

sage: D.centrality_degree() 

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

sage: D.centrality_degree(v=1) 

1 

 

TESTS:: 

 

sage: Graph(1).centrality_degree() 

Traceback (most recent call last): 

... 

ValueError: The centrality degree is not defined on graphs with only one vertex 

""" 

from sage.rings.integer import Integer 

n_minus_one = Integer(self.order()-1) 

if n_minus_one == 0: 

raise ValueError("The centrality degree is not defined " 

"on graphs with only one vertex") 

if v is None: 

return {v:self.degree(v)/n_minus_one for v in self} 

else: 

return self.degree(v)/n_minus_one 

 

### Constructors 

 

@doc_index("Basic methods") 

def to_directed(self, implementation='c_graph', data_structure=None, 

sparse=None): 

""" 

Return a directed version of the graph. 

 

A single edge becomes two edges, one in each direction. 

 

INPUT: 

 

- ``data_structure`` -- one of ``"sparse"``, ``"static_sparse"``, or 

``"dense"``. See the documentation of :class:`Graph` or 

:class:`DiGraph`. 

 

- ``sparse`` (boolean) -- ``sparse=True`` is an alias for 

``data_structure="sparse"``, and ``sparse=False`` is an alias for 

``data_structure="dense"``. 

 

EXAMPLES:: 

 

sage: graphs.PetersenGraph().to_directed() 

Petersen graph: Digraph on 10 vertices 

 

TESTS: 

 

Immutable graphs yield immutable graphs:: 

 

sage: Graph([[1, 2]], immutable=True).to_directed()._backend 

<sage.graphs.base.static_sparse_backend.StaticSparseBackend object at ...> 

 

:trac:`17005`:: 

 

sage: Graph([[1,2]], immutable=True).to_directed() 

Digraph on 2 vertices 

 

:trac:`22424`:: 

 

sage: G1=graphs.RandomGNP(5,0.5) 

sage: gp1 = G1.graphplot(save_pos=True) 

sage: G2=G1.to_directed() 

sage: G2.delete_vertex(0) 

sage: G2.add_vertex(5) 

sage: gp2 = G2.graphplot() 

sage: gp1 = G1.graphplot() 

""" 

if sparse is not None: 

if data_structure is not None: 

raise ValueError("The 'sparse' argument is an alias for " 

"'data_structure'. Please do not define both.") 

data_structure = "sparse" if sparse else "dense" 

 

if data_structure is None: 

from sage.graphs.base.dense_graph import DenseGraphBackend 

from sage.graphs.base.sparse_graph import SparseGraphBackend 

if isinstance(self._backend, DenseGraphBackend): 

data_structure = "dense" 

elif isinstance(self._backend, SparseGraphBackend): 

data_structure = "sparse" 

else: 

data_structure = "static_sparse" 

from sage.graphs.all import DiGraph 

D = DiGraph(name = self.name(), 

pos = self.get_pos(), 

multiedges = self.allows_multiple_edges(), 

loops = self.allows_loops(), 

implementation = implementation, 

data_structure = (data_structure if data_structure!="static_sparse" 

else "sparse")) # we need a mutable copy 

 

D.add_vertices(self.vertex_iterator()) 

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

D.add_edge(u,v,l) 

D.add_edge(v,u,l) 

if hasattr(self, '_embedding'): 

D._embedding = copy(self._embedding) 

D._weighted = self._weighted 

 

if data_structure == "static_sparse": 

D = D.copy(data_structure=data_structure) 

 

return D 

 

@doc_index("Basic methods") 

def to_undirected(self): 

""" 

Since the graph is already undirected, simply returns a copy of 

itself. 

 

EXAMPLES:: 

 

sage: graphs.PetersenGraph().to_undirected() 

Petersen graph: Graph on 10 vertices 

""" 

return self.copy() 

 

@doc_index("Basic methods") 

def join(self, other, labels="pairs", immutable=None): 

""" 

Return the join of ``self`` and ``other``. 

 

INPUT: 

 

- ``labels`` - (defaults to 'pairs') If set to 'pairs', each 

element ``v`` in the first graph will be named ``(0,v)`` and 

each element ``u`` in ``other`` will be named ``(1,u)`` in 

the result. If set to 'integers', the elements of the result 

will be relabeled with consecutive integers. 

 

- ``immutable`` (boolean) -- whether to create a mutable/immutable 

join. ``immutable=None`` (default) means that the graphs and their 

join will behave the same way. 

 

.. SEEALSO:: 

 

* :meth:`~sage.graphs.generic_graph.GenericGraph.union` 

 

* :meth:`~sage.graphs.generic_graph.GenericGraph.disjoint_union` 

 

EXAMPLES:: 

 

sage: G = graphs.CycleGraph(3) 

sage: H = Graph(2) 

sage: J = G.join(H); J 

Cycle graph join : Graph on 5 vertices 

sage: J.vertices() 

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

sage: J = G.join(H, labels='integers'); J 

Cycle graph join : Graph on 5 vertices 

sage: J.vertices() 

[0, 1, 2, 3, 4] 

sage: J.edges() 

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

 

:: 

 

sage: G = Graph(3) 

sage: G.name("Graph on 3 vertices") 

sage: H = Graph(2) 

sage: H.name("Graph on 2 vertices") 

sage: J = G.join(H); J 

Graph on 3 vertices join Graph on 2 vertices: Graph on 5 vertices 

sage: J.vertices() 

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

sage: J = G.join(H, labels='integers'); J 

Graph on 3 vertices join Graph on 2 vertices: Graph on 5 vertices 

sage: J.edges() 

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

""" 

G = self.disjoint_union(other, labels=labels, immutable=False) 

if labels=="integers": 

G.add_edges((u,v) for u in range(self.order()) 

for v in range(self.order(), self.order()+other.order())) 

else: 

G.add_edges(((0,u), (1,v)) for u in self.vertices() 

for v in other.vertices()) 

 

G.name('%s join %s'%(self.name(), other.name())) 

 

if immutable is None: 

immutable = self.is_immutable() and other.is_immutable() 

if immutable: 

G = G.copy(immutable=True) 

 

return G 

 

@doc_index("Leftovers") 

def seidel_adjacency_matrix(self, vertices=None): 

r""" 

Return the Seidel adjacency matrix of ``self``. 

 

Returns `J-I-2A`, for `A` the (ordinary) :meth:`adjacency 

matrix 

<sage.graphs.generic_graph.GenericGraph.adjacency_matrix>` of 

``self``, `I` the identity matrix, and `J` the all-1 matrix. 

It is closely related to :meth:`twograph`. 

 

The matrix returned is over the integers. If a different ring is 

desired, use either :meth:`sage.matrix.matrix0.Matrix.change_ring` 

method or :class:`matrix <sage.matrix.constructor.MatrixFactory>` function. 

 

INPUT: 

 

- ``vertices`` (list) -- the ordering of the vertices defining 

how they should appear in the matrix. By default, the 

ordering given by 

:meth:`~sage.graphs.generic_graph.GenericGraph.vertices` is 

used. 

 

EXAMPLES:: 

 

sage: G = graphs.CycleGraph(5) 

sage: G = G.disjoint_union(graphs.CompleteGraph(1)) 

sage: G.seidel_adjacency_matrix().minpoly() 

x^2 - 5 

""" 

 

return -self.adjacency_matrix(sparse=False, vertices=vertices)+ \ 

self.complement().adjacency_matrix(sparse=False, \ 

vertices=vertices) 

 

@doc_index("Leftovers") 

def seidel_switching(self, s, inplace=True): 

r""" 

Return the Seidel switching of ``self`` w.r.t. subset of vertices ``s``. 

 

Returns the graph obtained by Seidel switching of ``self`` 

with respect to the subset of vertices ``s``. This is the graph 

given by Seidel adjacency matrix `DSD`, for `S` the Seidel 

adjacency matrix of ``self``, and `D` the diagonal matrix with -1s 

at positions corresponding to ``s``, and 1s elsewhere. 

 

INPUT: 

 

- ``s`` -- a list of vertices of ``self`` 

 

- ``inplace`` (boolean) -- whether to do the modification inplace, or to 

return a copy of the graph after switching. 

 

EXAMPLES:: 

 

sage: G = graphs.CycleGraph(5) 

sage: G = G.disjoint_union(graphs.CompleteGraph(1)) 

sage: G.seidel_switching([(0,1),(1,0),(0,0)]) 

sage: G.seidel_adjacency_matrix().minpoly() 

x^2 - 5 

sage: G.is_connected() 

True 

 

TESTS:: 

 

sage: H = G.seidel_switching([1,4,5],inplace=False) 

sage: G.seidel_switching([1,4,5]) 

sage: G == H 

True 

""" 

from itertools import product 

G = self if inplace else copy(self) 

boundary = self.edge_boundary(s) 

G.add_edges(product(s, set(self).difference(s))) 

G.delete_edges(boundary) 

if not inplace: 

return G 

 

@doc_index("Leftovers") 

def twograph(self): 

r""" 

Return the two-graph of ``self`` 

 

Returns the :class:`two-graph <sage.combinat.designs.twographs.TwoGraph>` 

with the triples 

`T=\{t \in \binom {V}{3} : \left| \binom {t}{2} \cap E \right| \text{odd} \}` 

where `V` and `E` are vertices and edges of ``self``, respectively. 

 

EXAMPLES:: 

 

sage: p=graphs.PetersenGraph() 

sage: p.twograph() 

Incidence structure with 10 points and 60 blocks 

sage: p=graphs.chang_graphs() 

sage: T8 = graphs.CompleteGraph(8).line_graph() 

sage: C = T8.seidel_switching([(0,1,None),(2,3,None),(4,5,None),(6,7,None)],inplace=False) 

sage: T8.twograph()==C.twograph() 

True 

sage: T8.is_isomorphic(C) 

False 

 

TESTS:: 

 

sage: from sage.combinat.designs.twographs import TwoGraph 

sage: p=graphs.PetersenGraph().twograph() 

sage: TwoGraph(p, check=True) 

Incidence structure with 10 points and 60 blocks 

 

.. SEEALSO:: 

 

- :meth:`~sage.combinat.designs.twographs.TwoGraph.descendant` 

-- computes the descendant graph of the two-graph of self at a vertex 

 

- :func:`~sage.combinat.designs.twographs.twograph_descendant` 

-- ditto, but much faster. 

""" 

from sage.combinat.designs.twographs import TwoGraph 

G = self.relabel(inplace=False) 

T = [] 

 

# Triangles 

for x,y,z in G.subgraph_search_iterator(Graph({1:[2,3],2:[3]})): 

if x < y and y < z: 

T.append([x,y,z]) 

 

# Triples with just one edge 

for x,y,z in G.subgraph_search_iterator(Graph({1:[2],3:[]}),induced=True): 

if x < y: 

T.append([x,y,z]) 

 

T = TwoGraph(T) 

T.relabel({i:v for i,v in enumerate(self.vertices())}) 

 

return T 

 

### Visualization 

 

@doc_index("Basic methods") 

def write_to_eps(self, filename, **options): 

r""" 

Write a plot of the graph to ``filename`` in ``eps`` format. 

 

INPUT: 

 

- ``filename`` -- a string 

- ``**options`` -- same layout options as :meth:`.layout` 

 

EXAMPLES:: 

 

sage: P = graphs.PetersenGraph() 

sage: P.write_to_eps(tmp_filename(ext='.eps')) 

 

It is relatively simple to include this file in a LaTeX 

document. ``\usepackage{graphics}`` must appear in the 

preamble, and ``\includegraphics{filename}`` will include 

the file. To compile the document to ``pdf`` with ``pdflatex`` or ``xelatex`` 

the file needs first to be converted to ``pdf``, for example 

with ``ps2pdf filename.eps filename.pdf``. 

""" 

from sage.graphs.print_graphs import print_graph_eps 

pos = self.layout(**options) 

[xmin, xmax, ymin, ymax] = self._layout_bounding_box(pos) 

for v in pos: 

pos[v] = (1.8*(pos[v][0] - xmin)/(xmax - xmin) - 0.9, 1.8*(pos[v][1] - ymin)/(ymax - ymin) - 0.9) 

if filename[-4:] != '.eps': 

filename += '.eps' 

f = open(filename, 'w') 

f.write( print_graph_eps(self.vertices(), self.edge_iterator(), pos) ) 

f.close() 

 

@doc_index("Algorithmically hard stuff") 

def topological_minor(self, H, vertices = False, paths = False, solver=None, verbose=0): 

r""" 

Return a topological `H`-minor from ``self`` if one exists. 

 

We say that a graph `G` has a topological `H`-minor (or that 

it has a graph isomorphic to `H` as a topological minor), if 

`G` contains a subdivision of a graph isomorphic to `H` (i.e. 

obtained from `H` through arbitrary subdivision of its edges) 

as a subgraph. 

 

For more information, see the :wikipedia:`Minor_(graph_theory)`. 

 

INPUT: 

 

- ``H`` -- The topological minor to find in the current graph. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbose`` -- integer (default: ``0``). Sets the level of 

verbosity. Set to 0 by default, which means quiet. 

 

OUTPUT: 

 

The topological `H`-minor found is returned as a subgraph `M` 

of ``self``, such that the vertex `v` of `M` that represents a 

vertex `h\in H` has ``h`` as a label (see 

:meth:`get_vertex <sage.graphs.generic_graph.GenericGraph.get_vertex>` 

and 

:meth:`set_vertex <sage.graphs.generic_graph.GenericGraph.set_vertex>`), 

and such that every edge of `M` has as a label the edge of `H` 

it (partially) represents. 

 

If no topological minor is found, this method returns 

``False``. 

 

ALGORITHM: 

 

Mixed Integer Linear Programming. 

 

COMPLEXITY: 

 

Theoretically, when `H` is fixed, testing for the existence of 

a topological `H`-minor is polynomial. The known algorithms 

are highly exponential in `H`, though. 

 

.. NOTE:: 

 

This function can be expected to be *very* slow, especially where 

the topological minor does not exist. 

 

(CPLEX seems to be *much* more efficient than GLPK on this kind of 

problem) 

 

EXAMPLES: 

 

Petersen's graph has a topological `K_4`-minor:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.topological_minor(graphs.CompleteGraph(4)) 

Subgraph of (Petersen graph): Graph on ... 

 

And a topological `K_{3,3}`-minor:: 

 

sage: g.topological_minor(graphs.CompleteBipartiteGraph(3,3)) 

Subgraph of (Petersen graph): Graph on ... 

 

And of course, a tree has no topological `C_3`-minor:: 

 

sage: g = graphs.RandomGNP(15,.3) 

sage: g = g.subgraph(edges = g.min_spanning_tree()) 

sage: g.topological_minor(graphs.CycleGraph(3)) 

False 

""" 

self._scream_if_not_simple() 

H._scream_if_not_simple() 

# Useful alias ... 

G = self 

 

from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException 

p = MixedIntegerLinearProgram(solver=solver) 

 

# This is an existence problem 

p.set_objective(None) 

 

####################### 

# Vertex representant # 

####################### 

# 

# v_repr[h,g] = 1 if vertex h from H is represented by vertex 

# g from G, 0 otherwise 

 

v_repr = p.new_variable(binary = True) 

 

# Exactly one representant per vertex of H 

for h in H: 

p.add_constraint( p.sum( v_repr[h,g] for g in G), min = 1, max = 1) 

 

# A vertex of G can only represent one vertex of H 

for g in G: 

p.add_constraint( p.sum( v_repr[h,g] for h in H), max = 1) 

 

################### 

# Is representent # 

################### 

# 

# is_repr[v] = 1 if v represents some vertex of H 

 

is_repr = p.new_variable(binary = True) 

 

for g in G: 

for h in H: 

p.add_constraint( v_repr[h,g] - is_repr[g], max = 0) 

 

################################### 

# paths between the representents # 

################################### 

# 

# For any edge (h1,h2) in H, we have a corresponding path in G 

# between the representants of h1 and h2. Which means there is 

# a flow of intensity 1 from one to the other. 

# We are then writing a flow problem for each edge of H. 

# 

# The variable flow[(h1,h2),(g1,g2)] indicates the amount of 

# flow on the edge (g1,g2) representing the edge (h1,h2). 

 

flow = p.new_variable(binary = True) 

 

# This lambda function returns the balance of flow 

# corresponding to commodity C at vertex v v 

 

flow_in = lambda C, v : p.sum( flow[C,(v,u)] for u in G.neighbors(v) ) 

flow_out = lambda C, v : p.sum( flow[C,(u,v)] for u in G.neighbors(v) ) 

 

flow_balance = lambda C, v : flow_in(C,v) - flow_out(C,v) 

 

for h1,h2 in H.edges(labels = False): 

 

for v in G: 

 

# The flow balance depends on whether the vertex v is 

# a representant of h1 or h2 in G, or a representant 

# of none 

 

p.add_constraint( flow_balance((h1,h2),v) == v_repr[h1,v] - v_repr[h2,v] ) 

 

############################# 

# Internal vertex of a path # 

############################# 

# 

# is_internal[C][g] = 1 if a vertex v from G is located on the 

# path representing the edge (=commodity) C 

 

is_internal = p.new_variable(binary = True) 

 

# When is a vertex internal for a commodity ? 

for C in H.edges(labels = False): 

for g in G: 

p.add_constraint( flow_in(C,g) + flow_out(C,g) - is_internal[C,g], max = 1) 

 

############################ 

# Two paths do not cross ! # 

############################ 

 

# A vertex can only be internal for one commodity, and zero if 

# the vertex is a representent 

 

for g in G: 

p.add_constraint( p.sum( is_internal[C,g] for C in H.edges(labels = False)) 

+ is_repr[g], max = 1 ) 

 

# (The following inequalities are not necessary, but they seem 

# to be of help (the solvers find the answer quicker when they 

# are added) 

 

# The flow on one edge can go in only one direction. Besides, 

# it can belong to at most one commodity and has a maximum 

# intensity of 1. 

 

for g1,g2 in G.edges(labels = None): 

 

p.add_constraint( p.sum( flow[C,(g1,g2)] for C in H.edges(labels = False) ) 

+ p.sum( flow[C,(g2,g1)] for C in H.edges(labels = False) ), 

max = 1) 

 

 

# Now we can solve the problem itself ! 

 

try: 

p.solve(log = verbose) 

 

except MIPSolverException: 

return False 

 

 

minor = G.subgraph(immutable=False) 

 

is_repr = p.get_values(is_repr) 

v_repr = p.get_values(v_repr) 

flow = p.get_values(flow) 

 

for u,v in minor.edges(labels = False): 

used = False 

for C in H.edges(labels = False): 

 

if flow[C,(u,v)] + flow[C,(v,u)] > .5: 

used = True 

minor.set_edge_label(u,v,C) 

break 

if not used: 

minor.delete_edge(u,v) 

 

minor.delete_vertices( [v for v in minor 

if minor.degree(v) == 0 ] ) 

 

for g in minor: 

if is_repr[g] > .5: 

for h in H: 

if v_repr[h,v] > .5: 

minor.set_vertex(g,h) 

break 

 

return minor 

 

### Cliques 

 

@doc_index("Clique-related methods") 

def cliques_maximal(self, algorithm = "native"): 

""" 

Return the list of all maximal cliques. 

 

Each clique is represented by a list of vertices. A clique 

is an induced complete subgraph, and a maximal clique is one 

not contained in a larger one. 

 

INPUT: 

 

- ``algorithm`` -- can be set to ``"native"`` (default) to use Sage's 

own implementation, or to ``"NetworkX"`` to use NetworkX' 

implementation of the Bron and Kerbosch Algorithm [BroKer1973]_. 

 

 

.. NOTE:: 

 

This method sorts its output before returning it. If you prefer to 

save the extra time, you can call 

:class:`sage.graphs.independent_sets.IndependentSets` directly. 

 

.. NOTE:: 

 

Sage's implementation of the enumeration of *maximal* independent 

sets is not much faster than NetworkX' (expect a 2x speedup), which 

is surprising as it is written in Cython. This being said, the 

algorithm from NetworkX appears to be sligthly different from this 

one, and that would be a good thing to explore if one wants to 

improve the implementation. 

 

ALGORITHM: 

 

This function is based on NetworkX's implementation of the Bron and 

Kerbosch Algorithm [BroKer1973]_. 

 

REFERENCE: 

 

.. [BroKer1973] Coen Bron and Joep Kerbosch. (1973). Algorithm 457: 

Finding All Cliques of an Undirected Graph. Commun. ACM. v 

16. n 9. pages 575-577. ACM Press. [Online] Available: 

http://www.ram.org/computing/rambin/rambin.html 

 

EXAMPLES:: 

 

sage: graphs.ChvatalGraph().cliques_maximal() 

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

[2, 6], [2, 8], [3, 4], [3, 7], [3, 9], [4, 5], [4, 8], [5, 10], 

[5, 11], [6, 10], [6, 11], [7, 8], [7, 11], [8, 10], [9, 10], [9, 11]] 

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

sage: G.show(figsize=[2,2]) 

sage: G.cliques_maximal() 

[[0, 1, 2], [0, 1, 3]] 

sage: C=graphs.PetersenGraph() 

sage: C.cliques_maximal() 

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

[3, 8], [4, 9], [5, 7], [5, 8], [6, 8], [6, 9], [7, 9]] 

sage: C = Graph('DJ{') 

sage: C.cliques_maximal() 

[[0, 4], [1, 2, 3, 4]] 

 

Comparing the two implementations:: 

 

sage: g = graphs.RandomGNP(20,.7) 

sage: s1 = Set(map(Set, g.cliques_maximal(algorithm="NetworkX"))) 

sage: s2 = Set(map(Set, g.cliques_maximal(algorithm="native"))) 

sage: s1 == s2 

True 

""" 

if algorithm == "native": 

from sage.graphs.independent_sets import IndependentSets 

return sorted(IndependentSets(self, maximal = True, complement = True)) 

elif algorithm == "NetworkX": 

import networkx 

return sorted(networkx.find_cliques(self.networkx_graph(copy=False))) 

else: 

raise ValueError("Algorithm must be equal to 'native' or to 'NetworkX'.") 

 

@doc_index("Clique-related methods") 

def clique_maximum(self, algorithm="Cliquer"): 

""" 

Return the vertex set of a maximal order complete subgraph. 

 

INPUT: 

 

- ``algorithm`` -- the algorithm to be used : 

 

- If ``algorithm = "Cliquer"`` (default) - This wraps the C program 

Cliquer [NisOst2003]_. 

 

- If ``algorithm = "MILP"``, the problem is solved through a Mixed 

Integer Linear Program. 

 

(see :class:`~sage.numerical.mip.MixedIntegerLinearProgram`) 

 

- If ``algorithm = "mcqd"`` - Uses the MCQD solver 

(`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD 

package must be installed. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use to_undirected 

to convert a digraph to an undirected graph. 

 

ALGORITHM: 

 

This function is based on Cliquer [NisOst2003]_. 

 

EXAMPLES: 

 

Using Cliquer (default):: 

 

sage: C=graphs.PetersenGraph() 

sage: C.clique_maximum() 

[7, 9] 

sage: C = Graph('DJ{') 

sage: C.clique_maximum() 

[1, 2, 3, 4] 

 

Through a Linear Program:: 

 

sage: len(C.clique_maximum(algorithm = "MILP")) 

4 

 

TESTS: 

 

Wrong algorithm:: 

 

sage: C.clique_maximum(algorithm = "BFS") 

Traceback (most recent call last): 

... 

NotImplementedError: Only 'MILP', 'Cliquer' and 'mcqd' are supported. 

 

""" 

self._scream_if_not_simple(allow_multiple_edges=True) 

if algorithm=="Cliquer": 

from sage.graphs.cliquer import max_clique 

return max_clique(self) 

elif algorithm == "MILP": 

return self.complement().independent_set(algorithm = algorithm) 

elif algorithm == "mcqd": 

try: 

from sage.graphs.mcqd import mcqd 

except ImportError: 

from sage.misc.package import PackageNotFoundError 

raise PackageNotFoundError("mcqd") 

return mcqd(self) 

else: 

raise NotImplementedError("Only 'MILP', 'Cliquer' and 'mcqd' are supported.") 

 

@doc_index("Clique-related methods") 

def clique_number(self, algorithm="Cliquer", cliques=None): 

r""" 

Return the order of the largest clique of the graph 

 

This is also called as the clique number. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use ``to_undirected`` 

to convert a digraph to an undirected graph. 

 

INPUT: 

 

- ``algorithm`` -- the algorithm to be used : 

 

- If ``algorithm = "Cliquer"`` - This wraps the C program Cliquer 

[NisOst2003]_. 

 

- If ``algorithm = "networkx"`` - This function is based on 

NetworkX's implementation of the Bron and Kerbosch Algorithm 

[BroKer1973]_. 

 

- If ``algorithm = "MILP"``, the problem is solved through a Mixed 

Integer Linear Program. 

 

(see :class:`~sage.numerical.mip.MixedIntegerLinearProgram`) 

 

- If ``algorithm = "mcqd"`` - Uses the MCQD solver 

(`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD 

package must be installed. 

 

- ``cliques`` - an optional list of cliques that can be input if 

already computed. Ignored unless ``algorithm=="networkx"``. 

 

ALGORITHM: 

 

This function is based on Cliquer [NisOst2003]_ and [BroKer1973]_. 

 

EXAMPLES:: 

 

sage: C = Graph('DJ{') 

sage: C.clique_number() 

4 

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

sage: G.show(figsize=[2,2]) 

sage: G.clique_number() 

3 

 

By definition the clique number of a complete graph is its order:: 

 

sage: all(graphs.CompleteGraph(i).clique_number() == i for i in range(1,15)) 

True 

 

A non-empty graph without edges has a clique number of 1:: 

 

sage: all((i*graphs.CompleteGraph(1)).clique_number() == 1 for i in range(1,15)) 

True 

 

A complete multipartite graph with k parts has clique number k:: 

 

sage: all((i*graphs.CompleteMultipartiteGraph(i*[5])).clique_number() == i for i in range(1,6)) 

True 

 

TESTS:: 

 

sage: g = graphs.PetersenGraph() 

sage: g.clique_number(algorithm="MILP") 

2 

sage: for i in range(10): # optional - mcqd 

....: g = graphs.RandomGNP(15,.5) # optional - mcqd 

....: if g.clique_number() != g.clique_number(algorithm="mcqd"): # optional - mcqd 

....: print("This is dead wrong !") # optional - mcqd 

""" 

self._scream_if_not_simple(allow_loops=False) 

if algorithm=="Cliquer": 

from sage.graphs.cliquer import clique_number 

return clique_number(self) 

elif algorithm=="networkx": 

import networkx 

return networkx.graph_clique_number(self.networkx_graph(copy=False),cliques) 

elif algorithm == "MILP": 

return len(self.complement().independent_set(algorithm = algorithm)) 

elif algorithm == "mcqd": 

try: 

from sage.graphs.mcqd import mcqd 

except ImportError: 

from sage.misc.package import PackageNotFoundError 

raise PackageNotFoundError("mcqd") 

return len(mcqd(self)) 

else: 

raise NotImplementedError("Only 'networkx' 'MILP' 'Cliquer' and 'mcqd' are supported.") 

 

@doc_index("Clique-related methods") 

def cliques_number_of(self, vertices=None, cliques=None): 

""" 

Return a dictionary of the number of maximal cliques containing each 

vertex, keyed by vertex. 

 

This returns a single value if only one input vertex. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use to_undirected 

to convert a digraph to an undirected graph. 

 

INPUT: 

 

- ``vertices`` - the vertices to inspect (default is 

entire graph) 

 

- ``cliques`` - list of cliques (if already 

computed) 

 

 

EXAMPLES:: 

 

sage: C = Graph('DJ{') 

sage: C.cliques_number_of() 

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

sage: E = C.cliques_maximal() 

sage: E 

[[0, 4], [1, 2, 3, 4]] 

sage: C.cliques_number_of(cliques=E) 

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

sage: F = graphs.Grid2dGraph(2,3) 

sage: X = F.cliques_number_of() 

sage: for v in sorted(X): 

....: print("{} {}".format(v, X[v])) 

(0, 0) 2 

(0, 1) 3 

(0, 2) 2 

(1, 0) 2 

(1, 1) 3 

(1, 2) 2 

sage: F.cliques_number_of(vertices=[(0, 1), (1, 2)]) 

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

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

sage: G.show(figsize=[2,2]) 

sage: G.cliques_number_of() 

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

""" 

import networkx 

return networkx.number_of_cliques(self.networkx_graph(copy=False), vertices, cliques) 

 

@doc_index("Clique-related methods") 

def cliques_get_max_clique_graph(self, name=''): 

""" 

Return the clique graph. 

 

Vertices of the result are the maximal cliques of the graph, and 

edges of the result are between maximal cliques with common members 

in the original graph. 

 

For more information, see the :wikipedia:`Clique_graph`. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use to_undirected 

to convert a digraph to an undirected graph. 

 

INPUT: 

 

- ``name`` - The name of the new graph. 

 

EXAMPLES:: 

 

sage: (graphs.ChvatalGraph()).cliques_get_max_clique_graph() 

Graph on 24 vertices 

sage: ((graphs.ChvatalGraph()).cliques_get_max_clique_graph()).show(figsize=[2,2], vertex_size=20, vertex_labels=False) 

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

sage: G.show(figsize=[2,2]) 

sage: G.cliques_get_max_clique_graph() 

Graph on 2 vertices 

sage: (G.cliques_get_max_clique_graph()).show(figsize=[2,2]) 

""" 

import networkx 

return Graph(networkx.make_max_clique_graph(self.networkx_graph(copy=False), name=name, create_using=networkx.MultiGraph())) 

 

@doc_index("Clique-related methods") 

def cliques_get_clique_bipartite(self, **kwds): 

""" 

Return a bipartite graph constructed such that maximal cliques are the 

right vertices and the left vertices are retained from the given 

graph. Right and left vertices are connected if the bottom vertex 

belongs to the clique represented by a top vertex. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use to_undirected 

to convert a digraph to an undirected graph. 

 

EXAMPLES:: 

 

sage: (graphs.ChvatalGraph()).cliques_get_clique_bipartite() 

Bipartite graph on 36 vertices 

sage: ((graphs.ChvatalGraph()).cliques_get_clique_bipartite()).show(figsize=[2,2], vertex_size=20, vertex_labels=False) 

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

sage: G.show(figsize=[2,2]) 

sage: G.cliques_get_clique_bipartite() 

Bipartite graph on 6 vertices 

sage: (G.cliques_get_clique_bipartite()).show(figsize=[2,2]) 

""" 

from .bipartite_graph import BipartiteGraph 

import networkx 

return BipartiteGraph(networkx.make_clique_bipartite(self.networkx_graph(copy=False), **kwds)) 

 

@doc_index("Algorithmically hard stuff") 

def independent_set(self, algorithm = "Cliquer", value_only = False, reduction_rules = True, solver = None, verbosity = 0): 

r""" 

Return a maximum independent set. 

 

An independent set of a graph is a set of pairwise non-adjacent 

vertices. A maximum independent set is an independent set of maximum 

cardinality. It induces an empty subgraph. 

 

Equivalently, an independent set is defined as the complement of a 

vertex cover. 

 

For more information, see the 

:wikipedia:`Independent_set_(graph_theory)` and the 

:wikipedia:`Vertex_cover`. 

 

INPUT: 

 

- ``algorithm`` -- the algorithm to be used 

 

* If ``algorithm = "Cliquer"`` (default), the problem is solved 

using Cliquer [NisOst2003]_. 

 

(see the :mod:`Cliquer modules <sage.graphs.cliquer>`) 

 

* If ``algorithm = "MILP"``, the problem is solved through a Mixed 

Integer Linear Program. 

 

(see :class:`~sage.numerical.mip.MixedIntegerLinearProgram`) 

 

* If ``algorithm = "mcqd"`` - Uses the MCQD solver 

(`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD 

package must be installed. 

 

- ``value_only`` -- boolean (default: ``False``). If set to ``True``, 

only the size of a maximum independent set is returned. Otherwise, 

a maximum independent set is returned as a list of vertices. 

 

- ``reduction_rules`` -- (default: ``True``) Specify if the reductions 

rules from kernelization must be applied as pre-processing or not. 

See [ACFLSS04]_ for more details. Note that depending on the 

instance, it might be faster to disable reduction rules. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`~sage.numerical.mip.MixedIntegerLinearProgram.solve` 

of the class 

:class:`~sage.numerical.mip.MixedIntegerLinearProgram`. 

 

- ``verbosity`` -- non-negative integer (default: ``0``). Set the level 

of verbosity you want from the linear program solver. Since the 

problem of computing an independent set is `NP`-complete, its solving 

may take some time depending on the graph. A value of 0 means that 

there will be no message printed by the solver. This option is only 

useful if ``algorithm="MILP"``. 

 

.. NOTE:: 

 

While Cliquer/MCAD are usually (and by far) the most efficient 

implementations, the MILP formulation sometimes proves faster on 

very "symmetrical" graphs. 

 

EXAMPLES: 

 

Using Cliquer:: 

 

sage: C = graphs.PetersenGraph() 

sage: C.independent_set() 

[0, 3, 6, 7] 

 

As a linear program:: 

 

sage: C = graphs.PetersenGraph() 

sage: len(C.independent_set(algorithm = "MILP")) 

4 

 

.. PLOT:: 

 

g = graphs.PetersenGraph() 

sphinx_plot(g.plot(partition=[g.independent_set()])) 

""" 

my_cover = self.vertex_cover(algorithm=algorithm, value_only=value_only, reduction_rules=reduction_rules, solver=solver, verbosity=verbosity) 

if value_only: 

return self.order() - my_cover 

else: 

return [u for u in self.vertices() if not u in my_cover] 

 

 

@doc_index("Algorithmically hard stuff") 

def vertex_cover(self, algorithm = "Cliquer", value_only = False, 

reduction_rules = True, solver = None, verbosity = 0): 

r""" 

Return a minimum vertex cover of self represented by a set of vertices. 

 

A minimum vertex cover of a graph is a set `S` of vertices such that 

each edge is incident to at least one element of `S`, and such that `S` 

is of minimum cardinality. For more information, see 

:wikipedia:`Vertex_cover`. 

 

Equivalently, a vertex cover is defined as the complement of an 

independent set. 

 

As an optimization problem, it can be expressed as follows: 

 

.. MATH:: 

 

\mbox{Minimize : }&\sum_{v\in G} b_v\\ 

\mbox{Such that : }&\forall (u,v) \in G.edges(), b_u+b_v\geq 1\\ 

&\forall x\in G, b_x\mbox{ is a binary variable} 

 

INPUT: 

 

- ``algorithm`` -- string (default: ``"Cliquer"``). Indicating 

which algorithm to use. It can be one of those values. 

 

- ``"Cliquer"`` will compute a minimum vertex cover 

using the Cliquer package. 

 

- ``"MILP"`` will compute a minimum vertex cover through a mixed 

integer linear program. 

 

- If ``algorithm = "mcqd"`` - Uses the MCQD solver 

(`<http://www.sicmm.org/~konc/maxclique/>`_). Note that the MCQD 

package must be installed. 

 

- ``value_only`` -- boolean (default: ``False``). If set to ``True``, 

only the size of a minimum vertex cover is returned. Otherwise, 

a minimum vertex cover is returned as a list of vertices. 

 

- ``reduction_rules`` -- (default: ``True``) Specify if the reductions 

rules from kernelization must be applied as pre-processing or not. 

See [ACFLSS04]_ for more details. Note that depending on the 

instance, it might be faster to disable reduction rules. 

 

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

solver to be used. If set to ``None``, the default one is used. For 

more information on LP solvers and which default solver is used, see 

the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class 

:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

- ``verbosity`` -- non-negative integer (default: ``0``). Set the level 

of verbosity you want from the linear program solver. Since the 

problem of computing a vertex cover is `NP`-complete, its solving may 

take some time depending on the graph. A value of 0 means that there 

will be no message printed by the solver. This option is only useful 

if ``algorithm="MILP"``. 

 

EXAMPLES: 

 

On the Pappus graph:: 

 

sage: g = graphs.PappusGraph() 

sage: g.vertex_cover(value_only=True) 

9 

 

.. PLOT:: 

 

g = graphs.PappusGraph() 

sphinx_plot(g.plot(partition=[g.vertex_cover()])) 

 

TESTS: 

 

The two algorithms should return the same result:: 

 

sage: g = graphs.RandomGNP(10,.5) 

sage: vc1 = g.vertex_cover(algorithm="MILP") 

sage: vc2 = g.vertex_cover(algorithm="Cliquer") 

sage: len(vc1) == len(vc2) 

True 

 

The cardinality of the vertex cover is unchanged when reduction rules are used. First for trees:: 

 

sage: for i in range(20): 

....: g = graphs.RandomTree(20) 

....: vc1_set = g.vertex_cover() 

....: vc1 = len(vc1_set) 

....: vc2 = g.vertex_cover(value_only = True, reduction_rules = False) 

....: if vc1 != vc2: 

....: print("Error :", vc1, vc2) 

....: print("With reduction rules :", vc1) 

....: print("Without reduction rules :", vc2) 

....: break 

....: g.delete_vertices(vc1_set) 

....: if g.size() != 0: 

....: print("This thing is not a vertex cover !") 

 

Then for random GNP graphs:: 

 

sage: for i in range(20): 

....: g = graphs.RandomGNP(50,4/50) 

....: vc1_set = g.vertex_cover() 

....: vc1 = len(vc1_set) 

....: vc2 = g.vertex_cover(value_only = True, reduction_rules = False) 

....: if vc1 != vc2: 

....: print("Error :", vc1, vc2) 

....: print("With reduction rules :", vc1) 

....: print("Without reduction rules :", vc2) 

....: break 

....: g.delete_vertices(vc1_set) 

....: if g.size() != 0: 

....: print("This thing is not a vertex cover !") 

 

Testing mcqd:: 

 

sage: graphs.PetersenGraph().vertex_cover(algorithm="mcqd",value_only=True) # optional - mcqd 

6 

 

Given a wrong algorithm:: 

 

sage: graphs.PetersenGraph().vertex_cover(algorithm = "guess") 

Traceback (most recent call last): 

... 

ValueError: the algorithm must be "Cliquer", "MILP" or "mcqd" 

 

Ticket :trac:`24287` is fixed:: 

 

sage: G = Graph([(0,1)]*5 + [(1,2)]*2, multiedges=True) 

sage: G.vertex_cover(reduction_rules=True, algorithm='MILP') 

[1] 

sage: G.vertex_cover(reduction_rules=False) 

[1] 

""" 

self._scream_if_not_simple(allow_multiple_edges=True) 

g = self 

 

ppset = [] 

folded_vertices = [] 

 

################### 

# Reduction rules # 

################### 

 

if reduction_rules: 

# We apply simple reduction rules allowing to identify vertices that 

# belongs to an optimal vertex cover 

 

# We first take a copy of the graph without multiple edges, if any. 

g = copy(self) 

g.allow_multiple_edges(False) 

 

degree_at_most_two = {u for u in g if g.degree(u) <= 2} 

 

while degree_at_most_two: 

 

u = degree_at_most_two.pop() 

du = g.degree(u) 

 

if du == 0: 

# RULE 1: isolated vertices are not part of the cover. We 

# simply remove them from the graph. The degree of such 

# vertices may have been reduced to 0 while applying other 

# reduction rules 

g.delete_vertex(u) 

 

elif du == 1: 

# RULE 2: If a vertex u has degree 1, we select its neighbor 

# v and remove both u and v from g. 

v = next(g.neighbor_iterator(u)) 

ppset.append(v) 

g.delete_vertex(u) 

 

for w in g.neighbors(v): 

if g.degree(w) <= 3: 

# The degree of w will be at most two after the 

# deletion of v 

degree_at_most_two.add(w) 

 

g.delete_vertex(v) 

degree_at_most_two.discard(v) 

 

elif du == 2: 

v,w = g.neighbors(u) 

 

if g.has_edge(v, w): 

# RULE 3: If the neighbors v and w of a degree 2 vertex 

# u are incident, then we select both v and w and remove 

# u, v, and w from g. 

ppset.append(v) 

ppset.append(w) 

g.delete_vertex(u) 

neigh = set(g.neighbors(v) + g.neighbors(w)).difference([v, w]) 

g.delete_vertex(v) 

g.delete_vertex(w) 

 

for z in neigh: 

if g.degree(z) <= 2: 

degree_at_most_two.add(z) 

 

else: 

# RULE 4, folded vertices: If the neighbors v and w of a 

# degree 2 vertex u are not incident, then we contract 

# edges (u, v), (u, w). Then, if the solution contains u, 

# we replace it with v and w. Otherwise, we let u in the 

# solution. 

neigh = set(g.neighbors(v) + g.neighbors(w)).difference([u, v, w]) 

g.delete_vertex(v) 

g.delete_vertex(w) 

for z in neigh: 

g.add_edge(u,z) 

 

folded_vertices.append((u, v, w)) 

 

if g.degree(u) <= 2: 

degree_at_most_two.add(u) 

 

degree_at_most_two.discard(v) 

degree_at_most_two.discard(w) 

 

 

# RULE 5: 

# TODO: add extra reduction rules 

 

 

################## 

# Main Algorithm # 

################## 

 

if g.order() == 0: 

# Reduction rules were sufficients to get the solution 

size_cover_g = 0 

cover_g = [] 

 

elif algorithm == "Cliquer" or algorithm == "mcqd": 

if g.has_multiple_edges() and not reduction_rules: 

g = copy(g) 

g.allow_multiple_edges(False) 

 

independent = g.complement().clique_maximum(algorithm=algorithm) 

if value_only: 

size_cover_g = g.order() - len(independent) 

else: 

cover_g = [u for u in g if not u in independent] 

 

elif algorithm == "MILP": 

 

from sage.numerical.mip import MixedIntegerLinearProgram 

p = MixedIntegerLinearProgram(maximization=False, solver=solver) 

b = p.new_variable(binary=True) 

 

# minimizes the number of vertices in the set 

p.set_objective(p.sum(b[v] for v in g)) 

 

# an edge contains at least one vertex of the minimum vertex cover 

for (u,v) in g.edges(labels=None): 

p.add_constraint(b[u] + b[v], min=1) 

 

if value_only: 

size_cover_g = p.solve(objective_only=True, log=verbosity) 

else: 

p.solve(log=verbosity) 

b = p.get_values(b) 

cover_g = [v for v in g if b[v] == 1] 

else: 

raise ValueError('the algorithm must be "Cliquer", "MILP" or "mcqd"') 

 

######################### 

# Returning the results # 

######################### 

 

# We finally reconstruct the solution according the reduction rules 

if value_only: 

return len(ppset) + len(folded_vertices) + size_cover_g 

else: 

# RULES 2 and 3: 

cover_g.extend(ppset) 

# RULE 4: 

folded_vertices.reverse() 

for u,v,w in folded_vertices: 

if u in cover_g: 

cover_g.remove(u) 

cover_g.append(v) 

cover_g.append(w) 

else: 

cover_g.append(u) 

cover_g.sort() 

return cover_g 

 

@doc_index("Clique-related methods") 

def cliques_vertex_clique_number(self, algorithm="cliquer", vertices=None, 

cliques=None): 

""" 

Return a dictionary of sizes of the largest maximal cliques containing 

each vertex, keyed by vertex. 

 

Returns a single value if only one input vertex. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use to_undirected 

to convert a digraph to an undirected graph. 

 

INPUT: 

 

- ``algorithm`` - either ``cliquer`` or ``networkx`` 

 

- ``cliquer`` - This wraps the C program Cliquer [NisOst2003]_. 

 

- ``networkx`` - This function is based on NetworkX's implementation 

of the Bron and Kerbosch Algorithm [BroKer1973]_. 

 

- ``vertices`` - the vertices to inspect (default is entire graph). 

Ignored unless ``algorithm=='networkx'``. 

 

- ``cliques`` - list of cliques (if already computed). Ignored unless 

``algorithm=='networkx'``. 

 

EXAMPLES:: 

 

sage: C = Graph('DJ{') 

sage: C.cliques_vertex_clique_number() 

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

sage: E = C.cliques_maximal() 

sage: E 

[[0, 4], [1, 2, 3, 4]] 

sage: C.cliques_vertex_clique_number(cliques=E,algorithm="networkx") 

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

sage: F = graphs.Grid2dGraph(2,3) 

sage: X = F.cliques_vertex_clique_number(algorithm="networkx") 

sage: for v in sorted(X): 

....: print("{} {}".format(v, X[v])) 

(0, 0) 2 

(0, 1) 2 

(0, 2) 2 

(1, 0) 2 

(1, 1) 2 

(1, 2) 2 

sage: F.cliques_vertex_clique_number(vertices=[(0, 1), (1, 2)]) 

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

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

sage: G.show(figsize=[2,2]) 

sage: G.cliques_vertex_clique_number() 

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

""" 

if algorithm=="cliquer": 

from sage.graphs.cliquer import clique_number 

if vertices is None: 

vertices=self 

value={} 

for v in vertices: 

value[v] = 1+clique_number(self.subgraph(self.neighbors(v))) 

self.subgraph(self.neighbors(v)).plot() 

return value 

elif algorithm=="networkx": 

import networkx 

return networkx.node_clique_number(self.networkx_graph(copy=False),vertices, cliques) 

else: 

raise NotImplementedError("Only 'networkx' and 'cliquer' are supported.") 

 

@doc_index("Clique-related methods") 

def cliques_containing_vertex(self, vertices=None, cliques=None): 

""" 

Return the cliques containing each vertex, represented as a dictionary 

of lists of lists, keyed by vertex. 

 

Returns a single list if only one input vertex. 

 

.. NOTE:: 

 

Currently only implemented for undirected graphs. Use to_undirected 

to convert a digraph to an undirected graph. 

 

INPUT: 

 

- ``vertices`` - the vertices to inspect (default is 

entire graph) 

 

- ``cliques`` - list of cliques (if already 

computed) 

 

EXAMPLES:: 

 

sage: C = Graph('DJ{') 

sage: C.cliques_containing_vertex() 

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

sage: E = C.cliques_maximal() 

sage: E 

[[0, 4], [1, 2, 3, 4]] 

sage: C.cliques_containing_vertex(cliques=E) 

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

sage: F = graphs.Grid2dGraph(2,3) 

sage: X = F.cliques_containing_vertex() 

sage: for v in sorted(X): 

....: print("{} {}".format(v, X[v])) 

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

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

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

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

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

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

sage: F.cliques_containing_vertex(vertices=[(0, 1), (1, 2)]) 

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

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

sage: G.show(figsize=[2,2]) 

sage: G.cliques_containing_vertex() 

{0: [[0, 1, 2], [0, 1, 3]], 1: [[0, 1, 2], [0, 1, 3]], 2: [[0, 1, 2]], 3: [[0, 1, 3]]} 

 

""" 

import networkx 

return networkx.cliques_containing_node(self.networkx_graph(copy=False),vertices, cliques) 

 

@doc_index("Clique-related methods") 

def clique_complex(self): 

""" 

Return the clique complex of self. 

 

This is the largest simplicial complex on 

the vertices of self whose 1-skeleton is self. 

 

This is only makes sense for undirected simple graphs. 

 

EXAMPLES:: 

 

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

sage: g.clique_complex() 

Simplicial complex with vertex set (0, 1, 2, 4) and facets {(4,), (0, 1, 2)} 

 

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

sage: x = h.clique_complex() 

sage: x 

Simplicial complex with vertex set (0, 1, 2, 3, 4) and facets {(0, 1, 4), (0, 1, 2, 3)} 

sage: i = x.graph() 

sage: i==h 

True 

sage: x==i.clique_complex() 

True 

 

""" 

if self.is_directed() or self.has_loops() or self.has_multiple_edges(): 

raise ValueError("Self must be an undirected simple graph to have a clique complex.") 

import sage.homology.simplicial_complex 

C = sage.homology.simplicial_complex.SimplicialComplex(self.cliques_maximal(), maximality_check=True) 

C._graph = self 

return C 

 

@doc_index("Clique-related methods") 

def clique_polynomial(self, t = None): 

""" 

Return the clique polynomial of self. 

 

This is the polynomial where the coefficient of `t^n` is the number of 

cliques in the graph with `n` vertices. The constant term of the 

clique polynomial is always taken to be one. 

 

EXAMPLES:: 

 

sage: g = Graph() 

sage: g.clique_polynomial() 

1 

sage: g = Graph({0:[1]}) 

sage: g.clique_polynomial() 

t^2 + 2*t + 1 

sage: g = graphs.CycleGraph(4) 

sage: g.clique_polynomial() 

4*t^2 + 4*t + 1 

 

""" 

if t is None: 

R = PolynomialRing(ZZ, 't') 

t = R.gen() 

number_of = [0]*(self.order() + 1) 

for x in IndependentSets(self, complement = True): 

number_of[len(x)] += 1 

return sum(coeff*t**i for i,coeff in enumerate(number_of) if coeff) 

 

### Miscellaneous 

 

@doc_index("Leftovers") 

def cores(self, k = None, with_labels=False): 

""" 

Return the core number for each vertex in an ordered list. 

 

(for homomorphisms cores, see the :meth:`Graph.has_homomorphism_to` 

method) 

 

**DEFINITIONS** 

 

* *K-cores* in graph theory were introduced by Seidman in 1983 and by 

Bollobas in 1984 as a method of (destructively) simplifying graph 

topology to aid in analysis and visualization. They have been more 

recently defined as the following by Batagelj et al: 

 

*Given a graph `G` with vertices set `V` and edges set `E`, the 

`k`-core of `G` is the graph obtained from `G` by recursively removing 

the vertices with degree less than `k`, for as long as there are any.* 

 

This operation can be useful to filter or to study some properties of 

the graphs. For instance, when you compute the 2-core of graph G, you 

are cutting all the vertices which are in a tree part of graph. (A 

tree is a graph with no loops). [WPkcore]_ 

 

[PSW1996]_ defines a `k`-core of `G` as the largest subgraph (it is 

unique) of `G` with minimum degree at least `k`. 

 

* Core number of a vertex 

 

The core number of a vertex `v` is the largest integer `k` such that 

`v` belongs to the `k`-core of `G`. 

 

* Degeneracy 

 

The *degeneracy* of a graph `G`, usually denoted `\delta^*(G)`, is the 

smallest integer `k` such that the graph `G` can be reduced to the 

empty graph by iteratively removing vertices of degree `\leq 

k`. Equivalently, `\delta^*(G)=k` if `k` is the smallest integer such 

that the `k`-core of `G` is empty. 

 

**IMPLEMENTATION** 

 

This implementation is based on the NetworkX implementation of 

the algorithm described in [BZ]_. 

 

**INPUT** 

 

- ``k`` (integer) 

 

* If ``k = None`` (default), returns the core number for each vertex. 

 

* If ``k`` is an integer, returns a pair ``(ordering, core)``, where 

``core`` is the list of vertices in the `k`-core of ``self``, and 

``ordering`` is an elimination order for the other vertices such 

that each vertex is of degree strictly less than `k` when it is to 

be eliminated from the graph. 

 

- ``with_labels`` (boolean) 

 

* When set to ``False``, and ``k = None``, the method returns a list 

whose `i` th element is the core number of the `i` th vertex. When 

set to ``True``, the method returns a dictionary whose keys are 

vertices, and whose values are the corresponding core numbers. 

 

By default, ``with_labels = False``. 

 

.. SEEALSO:: 

 

* Graph cores is also a notion related to graph homomorphisms. For 

this second meaning, see :meth:`Graph.has_homomorphism_to`. 

 

REFERENCE: 

 

.. [WPkcore] K-core. Wikipedia. (2007). [Online] Available: 

:wikipedia:`K-core` 

 

.. [PSW1996] Boris Pittel, Joel Spencer and Nicholas Wormald. Sudden 

Emergence of a Giant k-Core in a Random 

Graph. (1996). J. Combinatorial Theory. Ser B 67. pages 

111-151. [Online] Available: 

http://cs.nyu.edu/cs/faculty/spencer/papers/k-core.pdf 

 

.. [BZ] Vladimir Batagelj and Matjaz Zaversnik. An `O(m)` 

Algorithm for Cores Decomposition of 

Networks. :arxiv:`cs/0310049v1`. 

 

EXAMPLES:: 

 

sage: (graphs.FruchtGraph()).cores() 

[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] 

sage: (graphs.FruchtGraph()).cores(with_labels=True) 

{0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3, 7: 3, 8: 3, 9: 3, 10: 3, 11: 3} 

sage: a = random_matrix(ZZ,20,x=2,sparse=True, density=.1) 

sage: b = Graph(20) 

sage: b.add_edges(a.nonzero_positions(), loops=False) 

sage: cores = b.cores(with_labels=True); cores 

{0: 3, 1: 3, 2: 3, 3: 3, 4: 2, 5: 2, 6: 3, 7: 1, 8: 3, 9: 3, 10: 3, 11: 3, 12: 3, 13: 3, 14: 2, 15: 3, 16: 3, 17: 3, 18: 3, 19: 3} 

sage: [v for v,c in cores.items() if c>=2] # the vertices in the 2-core 

[0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 

 

Checking the 2-core of a random lobster is indeed the empty set:: 

 

sage: g = graphs.RandomLobster(20,.5,.5) 

sage: ordering, core = g.cores(2) 

sage: len(core) == 0 

True 

""" 

self._scream_if_not_simple() 

# compute the degrees of each vertex 

degrees=self.degree(labels=True) 

 

# sort vertices by degree. Store in a list and keep track of 

# where a specific degree starts (effectively, the list is 

# sorted by bins). 

verts= sorted( degrees.keys(), key=lambda x: degrees[x]) 

bin_boundaries=[0] 

curr_degree=0 

for i,v in enumerate(verts): 

if degrees[v]>curr_degree: 

bin_boundaries.extend([i]*(degrees[v]-curr_degree)) 

curr_degree=degrees[v] 

vert_pos = dict((v,pos) for pos,v in enumerate(verts)) 

# Set up initial guesses for core and lists of neighbors. 

core= degrees 

nbrs=dict((v,set(self.neighbors(v))) for v in self) 

# form vertex core building up from smallest 

for v in verts: 

 

# If all the vertices have a degree larger than k, we can 

# return our answer if k is not None 

if k is not None and core[v] >= k: 

return verts[:vert_pos[v]], verts[vert_pos[v]:] 

 

for u in nbrs[v]: 

if core[u] > core[v]: 

nbrs[u].remove(v) 

 

# cleverly move u to the end of the next smallest 

# bin (i.e., subtract one from the degree of u). 

# We do this by swapping u with the first vertex 

# in the bin that contains u, then incrementing 

# the bin boundary for the bin that contains u. 

pos=vert_pos[u] 

bin_start=bin_boundaries[core[u]] 

vert_pos[u]=bin_start 

vert_pos[verts[bin_start]]=pos 

verts[bin_start],verts[pos]=verts[pos],verts[bin_start] 

bin_boundaries[core[u]]+=1 

core[u] -= 1 

 

if k is not None: 

return verts, [] 

 

if with_labels: 

return core 

else: 

return core.values() 

 

@doc_index("Leftovers") 

def modular_decomposition(self): 

r""" 

Return the modular decomposition of the current graph. 

 

Crash course on modular decomposition: 

 

A module `M` of a graph `G` is a proper subset of its vertices 

such that for all `u \in V(G)-M, v,w\in M` the relation `u 

\sim v \Leftrightarrow u \sim w` holds, where `\sim` denotes 

the adjacency relation in `G`. Equivalently, `M \subset V(G)` 

is a module if all its vertices have the same adjacency 

relations with each vertex outside of the module (vertex by 

vertex). 

 

Hence, for a set like a module, it is very easy to encode the 

information of the adjacencies between the vertices inside and 

outside the module -- we can actually add a new vertex `v_M` 

to our graph representing our module `M`, and let `v_M` be 

adjacent to `u\in V(G)-M` if and only if some `v\in M` (and 

hence all the vertices contained in the module) is adjacent to 

`u`. We can now independently (and recursively) study the 

structure of our module `M` and the new graph `G-M+\{v_M\}`, 

without any loss of information. 

 

Here are two very simple modules : 

 

* A connected component `C` (or the union of some --but 

not all-- of them) of a disconnected graph `G`, for 

instance, is a module, as no vertex of `C` has a 

neighbor outside of it. 

 

* An anticomponent `C` (or the union of some --but not 

all-- of them) of an non-anticonnected graph `G`, for 

the same reason (it is just the complement of the 

previous graph !). 

 

These modules being of special interest, the disjoint union of 

graphs is called a Parallel composition, and the complement of 

a disjoint union is called a Parallel composition. A graph 

whose only modules are singletons is called Prime. 

 

For more information on modular decomposition, in particular 

for an explanation of the terms "Parallel," "Prime" and 

"Serie," see the `Wikipedia article on modular decomposition 

<http://en.wikipedia.org/wiki/Modular_decomposition>`_. 

 

You may also be interested in the survey from Michel Habib and 

Christophe Paul entitled "A survey on Algorithmic aspects of 

modular decomposition" [HabPau10]_. 

 

OUTPUT: 

 

A pair of two values (recursively encoding the decomposition) : 

 

* The type of the current module : 

 

* ``"PARALLEL"`` 

* ``"PRIME"`` 

* ``"SERIES"`` 

 

* The list of submodules (as list of pairs ``(type, list)``, 

recursively...) or the vertex's name if the module is a 

singleton. 

 

EXAMPLES: 

 

The Bull Graph is prime:: 

 

sage: graphs.BullGraph().modular_decomposition() 

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

 

The Petersen Graph too:: 

 

sage: graphs.PetersenGraph().modular_decomposition() 

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

 

This a clique on 5 vertices with 2 pendant edges, though, has a more 

interesting decomposition :: 

 

sage: g = graphs.CompleteGraph(5) 

sage: g.add_edge(0,5) 

sage: g.add_edge(0,6) 

sage: g.modular_decomposition() 

(SERIES, [(PARALLEL, [(SERIES, [4, 3, 2, 1]), 5, 6]), 0]) 

 

ALGORITHM: 

 

This function uses python implementation of algorithm published by 

Marc Tedder, Derek Corneil, Michel Habib and Christophe Paul 

[TedCorHabPaul08] 

 

.. SEEALSO:: 

 

- :meth:`is_prime` -- Tests whether a graph is prime. 

 

REFERENCE: 

 

.. [HabPau10] Michel Habib and Christophe Paul 

A survey of the algorithmic aspects of modular decomposition 

Computer Science Review 

vol 4, number 1, pages 41--59, 2010 

http://www.lirmm.fr/~paul/md-survey.pdf 

 

.. [TedCorHabPaul08] Marc Tedder, Derek Corneil, Michel Habib and 

Christophe Paul 

:arxiv:`0710.3901` 

 

TESTS: 

 

empty graph is OK:: 

 

sage: graphs.EmptyGraph().modular_decomposition() 

() 

 

vertices may be arbitrary --- check that :trac:`24898` is fixed:: 

 

sage: Graph({(1,2):[(2,3)],(2,3):[(1,2)]}).modular_decomposition() 

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

""" 

from sage.graphs.modular_decomposition import modular_decomposition, NodeType 

 

self._scream_if_not_simple() 

 

if self.order() == 0: 

return tuple() 

 

if self.order() == 1: 

return (NodeType.PRIME, self.vertices()) 

 

D = modular_decomposition(self) 

 

relabel = lambda x : (x.node_type, [relabel(_) for _ in x.children]) if x.node_type != NodeType.NORMAL else x.children[0] 

 

return relabel(D) 

 

@doc_index("Graph properties") 

def is_polyhedral(self): 

""" 

Test whether the graph is the graph of the polyhedron. 

 

By a theorem of Steinitz (Satz 43, p. 77 of [St1922]_), 

graphs of three-dimensional polyhedra are exactly 

the simple 3-vertex-connected planar graphs. 

 

EXAMPLES:: 

 

sage: C = graphs.CubeGraph(3) 

sage: C.is_polyhedral() 

True 

sage: K33=graphs.CompleteBipartiteGraph(3, 3) 

sage: K33.is_polyhedral() 

False 

sage: graphs.CycleGraph(17).is_polyhedral() 

False 

sage: [i for i in range(9) if graphs.CompleteGraph(i).is_polyhedral()] 

[4] 

 

 

.. SEEALSO:: 

 

* :meth:`~sage.graphs.generic_graph.GenericGraph.vertex_connectivity` 

* :meth:`~sage.graphs.generic_graph.GenericGraph.is_planar` 

* :meth:`is_circumscribable` 

* :meth:`is_inscribable` 

* :wikipedia:`Polyhedral_graph` 

 

TESTS:: 

 

sage: G = Graph([[1, 2, 3, 4], [[1, 2], [1,1]]], loops=True) 

sage: G.is_polyhedral() 

False 

 

sage: G = Graph([[1, 2, 3], [[1, 2], [3, 1], [1, 2], [2, 3]]], multiedges=True) 

sage: G.is_polyhedral() 

False 

 

""" 

return (not self.has_loops() 

and not self.has_multiple_edges() 

and self.vertex_connectivity(k=3) 

and self.is_planar()) 

 

@doc_index("Graph properties") 

def is_circumscribable(self): 

""" 

Test whether the graph is the graph of a circumscribed polyhedron. 

 

A polyhedron is circumscribed if all of its facets are tangent to a 

sphere. By a theorem of Rivin ([HRS1993]_), this can be checked by 

solving a linear program that assigns weights between 0 and 1/2 on each 

edge of the polyhedron, so that the weights on any face add to exactly 

one and the weights on any non-facial cycle add to more than one. 

If and only if this can be done, the polyhedron can be circumscribed. 

 

EXAMPLES:: 

 

sage: C = graphs.CubeGraph(3) 

sage: C.is_circumscribable() 

True 

 

sage: O = graphs.OctahedralGraph() 

sage: O.is_circumscribable() 

True 

 

sage: TT = polytopes.truncated_tetrahedron().graph() 

sage: TT.is_circumscribable() 

False 

 

 

Stellating in a face of the octahedral graph is not circumscribable:: 

 

sage: f = set(flatten(choice(O.faces()))) 

sage: O.add_edges([[6, i] for i in f]) 

sage: O.is_circumscribable() 

False 

 

 

.. SEEALSO:: 

 

* :meth:`is_polyhedral` 

* :meth:`is_inscribable` 

 

TESTS:: 

 

sage: G = graphs.CompleteGraph(5) 

sage: G.is_circumscribable() 

Traceback (most recent call last): 

... 

NotImplementedError: this method only works for polyhedral graphs 

 

.. TODO:: 

 

Allow the use of other, inexact but faster solvers. 

""" 

if not self.is_polyhedral(): 

raise NotImplementedError('this method only works for polyhedral graphs') 

 

from sage.numerical.mip import MixedIntegerLinearProgram 

# For a description of the algorithm see paper by Rivin and: 

# https://www.ics.uci.edu/~eppstein/junkyard/uninscribable/ 

# In order to simulate strict inequalities in the following LP, we 

# introduce a variable c[0] and maximize it. If it is positive, then 

# the LP has a solution, such that all inequalities are strict 

# after removing the auxiliary variable c[0]. 

M = MixedIntegerLinearProgram(maximization=True, solver="ppl") 

e = M.new_variable(nonnegative=True) 

c = M.new_variable() 

M.set_min(c[0], -1) 

M.set_max(c[0], 1) 

M.set_objective(c[0]) 

 

for u, v in self.edge_iterator(labels=0): 

if u > v: 

u, v = v, u 

M.set_max(e[u, v], ZZ(1)/ZZ(2)) 

M.add_constraint(e[u, v] - c[0], min=0) 

M.add_constraint(e[u, v] + c[0], max=ZZ(1)/ZZ(2)) 

 

# The faces are completely determined by the graph structure: 

# for polyhedral graph, there is only one way to choose the faces. 

# We add an equality constraint for each face. 

efaces = self.faces() 

vfaces = set(frozenset([_[0] for _ in face]) for face in efaces) 

for edges in efaces: 

M.add_constraint(M.sum(e[tuple(sorted(_))] for _ in edges) == 1) 

 

# In order to generate all simple cycles of G, which are not faces, 

# we use the "all_simple_cycles" method of directed graphs, generating 

# each cycle twice (in both directions). The set below make sure only 

# one direction gives rise to an (in)equality 

D = self.to_directed() 

inequality_constraints = set() 

for cycle in D.all_simple_cycles(): 

if len(cycle) > 3: 

scycle = frozenset(cycle) 

if scycle not in vfaces: 

edges = (tuple(sorted([cycle[i], cycle[i+1]])) for i in range(len(cycle)-1)) 

inequality_constraints.add(frozenset(edges)) 

 

for ieq in inequality_constraints: 

M.add_constraint(M.sum(e[_] for _ in ieq) - c[0] >= 1) 

 

from sage.numerical.mip import MIPSolverException 

try: 

solution = M.solve() 

except MIPSolverException as e: 

if str(e) == "PPL : There is no feasible solution": 

return False 

return solution > 0 

 

@doc_index("Graph properties") 

def is_inscribable(self): 

""" 

Test whether the graph is the graph of an inscribed polyhedron. 

 

A polyhedron is inscribed if all of its vertices are on a sphere. 

This is dual to the notion of circumscribed polyhedron: A Polyhedron is 

inscribed if and only if its polar dual is circumscribed and hence a 

graph is inscribable if and only if its planar dual is circumscribable. 

 

EXAMPLES:: 

 

sage: H = graphs.HerschelGraph() 

sage: H.is_inscribable() # long time (> 1 sec) 

False 

sage: H.planar_dual().is_inscribable() # long time (> 1 sec) 

True 

 

sage: C = graphs.CubeGraph(3) 

sage: C.is_inscribable() 

True 

 

Cutting off a vertex from the cube yields an uninscribable graph:: 

 

sage: C = graphs.CubeGraph(3) 

sage: v = next(C.vertex_iterator()) 

sage: triangle = [_ + v for _ in C.neighbors(v)] 

sage: C.add_edges(Combinations(triangle, 2)) 

sage: C.add_edges(zip(triangle, C.neighbors(v))) 

sage: C.delete_vertex(v) 

sage: C.is_inscribable() 

False 

 

Breaking a face of the cube yields an uninscribable graph:: 

 

sage: C = graphs.CubeGraph(3) 

sage: face = choice(C.faces()) 

sage: C.add_edge([face[0][0], face[2][0]]) 

sage: C.is_inscribable() 

False 

 

 

.. SEEALSO:: 

 

* :meth:`is_polyhedral` 

* :meth:`is_circumscribable` 

 

TESTS:: 

 

sage: G = graphs.CompleteBipartiteGraph(3,3) 

sage: G.is_inscribable() 

Traceback (most recent call last): 

... 

NotImplementedError: this method only works for polyhedral graphs 

""" 

if not self.is_polyhedral(): 

raise NotImplementedError('this method only works for polyhedral graphs') 

return self.planar_dual().is_circumscribable() 

 

@doc_index("Graph properties") 

def is_prime(self): 

r""" 

Test whether the current graph is prime. 

 

A graph is prime if all its modules are trivial (i.e. empty, all of the 

graph or singletons) -- see :meth:`modular_decomposition`. 

 

EXAMPLES: 

 

The Petersen Graph and the Bull Graph are both prime:: 

 

sage: graphs.PetersenGraph().is_prime() 

True 

sage: graphs.BullGraph().is_prime() 

True 

 

Though quite obviously, the disjoint union of them is not:: 

 

sage: (graphs.PetersenGraph() + graphs.BullGraph()).is_prime() 

False 

 

TESTS:: 

 

sage: graphs.EmptyGraph().is_prime() 

True 

""" 

from sage.graphs.modular_decomposition import NodeType 

 

if self.order() <= 1: 

return True 

 

D = self.modular_decomposition() 

 

return D[0] == NodeType.PRIME and len(D[1]) == self.order() 

 

def _gomory_hu_tree(self, vertices, algorithm=None): 

r""" 

Return a Gomory-Hu tree associated to self. 

 

This function is the private counterpart of ``gomory_hu_tree()``, 

with the difference that it has an optional argument 

needed for recursive computations, which the user is not 

interested in defining himself. 

 

See the documentation of ``gomory_hu_tree()`` for more information. 

 

INPUT: 

 

- ``vertices`` - a set of "real" vertices, as opposed to the 

fakes one introduced during the computations. This variable is 

useful for the algorithm and for recursion purposes. 

 

- ``algorithm`` -- select the algorithm used by the :meth:`edge_cut` 

method. Refer to its documentation for allowed values and default 

behaviour. 

 

EXAMPLES: 

 

This function is actually tested in ``gomory_hu_tree()``, this 

example is only present to have a doctest coverage of 100%. 

 

sage: g = graphs.PetersenGraph() 

sage: t = g._gomory_hu_tree(frozenset(g.vertices())) 

""" 

self._scream_if_not_simple() 

 

# Small case, not really a problem ;-) 

if len(vertices) == 1: 

g = Graph() 

g.add_vertices(vertices) 

return g 

 

# Take any two vertices (u,v) 

it = iter(vertices) 

u,v = next(it),next(it) 

 

# Compute a uv min-edge-cut. 

# 

# The graph is split into U,V with u \in U and v\in V. 

flow,edges,[U,V] = self.edge_cut(u, v, use_edge_labels=True, vertices=True, algorithm=algorithm) 

 

# One graph for each part of the previous one 

gU,gV = self.subgraph(U, immutable=False), self.subgraph(V, immutable=False) 

 

# A fake vertex fU (resp. fV) to represent U (resp. V) 

fU = frozenset(U) 

fV = frozenset(V) 

 

# Each edge (uu,vv) with uu \in U and vv\in V yields: 

# - an edge (uu,fV) in gU 

# - an edge (vv,fU) in gV 

# 

# If the same edge is added several times their capacities add up. 

 

from sage.rings.real_mpfr import RR 

for uu,vv,capacity in edges: 

capacity = capacity if capacity in RR else 1 

 

# Assume uu is in gU 

if uu in V: 

uu,vv = vv,uu 

 

# Create the new edges if necessary 

if not gU.has_edge(uu, fV): 

gU.add_edge(uu, fV, 0) 

if not gV.has_edge(vv, fU): 

gV.add_edge(vv, fU, 0) 

 

# update the capacities 

gU.set_edge_label(uu, fV, gU.edge_label(uu, fV) + capacity) 

gV.set_edge_label(vv, fU, gV.edge_label(vv, fU) + capacity) 

 

# Recursion on each side 

gU_tree = gU._gomory_hu_tree(vertices & frozenset(gU), algorithm=algorithm) 

gV_tree = gV._gomory_hu_tree(vertices & frozenset(gV), algorithm=algorithm) 

 

# Union of the two partial trees 

g = gU_tree.union(gV_tree) 

 

# An edge to connect them, with the appropriate label 

g.add_edge(u, v, flow) 

 

return g 

 

@doc_index("Connectivity, orientations, trees") 

def gomory_hu_tree(self, algorithm=None): 

r""" 

Return a Gomory-Hu tree of self. 

 

Given a tree `T` with labeled edges representing capacities, it is very 

easy to determine the maximum flow between any pair of vertices : 

it is the minimal label on the edges of the unique path between them. 

 

Given a graph `G`, a Gomory-Hu tree `T` of `G` is a tree 

with the same set of vertices, and such that the maximum flow 

between any two vertices is the same in `G` as in `T`. See the 

`Wikipedia article on Gomory-Hu tree <http://en.wikipedia.org/wiki/Gomory%E2%80%93Hu_tree>`_. 

Note that, in general, a graph admits more than one Gomory-Hu tree. 

 

See also 15.4 (Gomory-Hu trees) from [SchrijverCombOpt]_. 

 

INPUT: 

 

- ``algorithm`` -- select the algorithm used by the :meth:`edge_cut` 

method. Refer to its documentation for allowed values and default 

behaviour. 

 

OUTPUT: 

 

A graph with labeled edges 

 

EXAMPLES: 

 

Taking the Petersen graph:: 

 

sage: g = graphs.PetersenGraph() 

sage: t = g.gomory_hu_tree() 

 

Obviously, this graph is a tree:: 

 

sage: t.is_tree() 

True 

 

Note that if the original graph is not connected, then the 

Gomory-Hu tree is in fact a forest:: 

 

sage: (2*g).gomory_hu_tree().is_forest() 

True 

sage: (2*g).gomory_hu_tree().is_connected() 

False 

 

On the other hand, such a tree has lost nothing of the initial 

graph connectedness:: 

 

sage: all([ t.flow(u,v) == g.flow(u,v) for u,v in Subsets( g.vertices(), 2 ) ]) 

True 

 

Just to make sure, we can check that the same is true for two vertices 

in a random graph:: 

 

sage: g = graphs.RandomGNP(20,.3) 

sage: t = g.gomory_hu_tree() 

sage: g.flow(0,1) == t.flow(0,1) 

True 

 

And also the min cut:: 

 

sage: g.edge_connectivity() == min(t.edge_labels()) 

True 

 

TESTS: 

 

:trac:`16475`:: 

 

sage: G = graphs.PetersenGraph() 

sage: for u,v in G.edge_iterator(labels=False): 

....: G.set_edge_label(u, v, 1) 

sage: for u, v in [(0, 1), (0, 4), (0, 5), (1, 2), (1, 6), (3, 4), (5, 7), (5, 8)]: 

....: G.set_edge_label(u, v, 2) 

sage: T = G.gomory_hu_tree() 

sage: from itertools import combinations 

sage: for u,v in combinations(G,2): 

....: assert T.flow(u,v,use_edge_labels=True) == G.flow(u,v,use_edge_labels=True) 

 

sage: graphs.EmptyGraph().gomory_hu_tree() 

Graph on 0 vertices 

""" 

if self.order() == 0: 

return Graph() 

if not self.is_connected(): 

g = Graph() 

for cc in self.connected_components_subgraphs(): 

g = g.union(cc._gomory_hu_tree(frozenset(cc.vertices()), algorithm=algorithm)) 

else: 

g = self._gomory_hu_tree(frozenset(self.vertices()), algorithm=algorithm) 

 

if self.get_pos() is not None: 

g.set_pos(dict(self.get_pos())) 

return g 

 

@doc_index("Leftovers") 

def two_factor_petersen(self): 

r""" 

Return a decomposition of the graph into 2-factors. 

 

Petersen's 2-factor decomposition theorem asserts that any 

`2r`-regular graph `G` can be decomposed into 2-factors. 

Equivalently, it means that the edges of any `2r`-regular 

graphs can be partitionned in `r` sets `C_1,\dots,C_r` such 

that for all `i`, the set `C_i` is a disjoint union of cycles 

( a 2-regular graph ). 

 

As any graph of maximal degree `\Delta` can be completed into 

a regular graph of degree `2\lceil\frac\Delta 2\rceil`, this 

result also means that the edges of any graph of degree `\Delta` 

can be partitionned in `r=2\lceil\frac\Delta 2\rceil` sets 

`C_1,\dots,C_r` such that for all `i`, the set `C_i` is a 

graph of maximal degree `2` ( a disjoint union of paths 

and cycles ). 

 

EXAMPLES: 

 

The Complete Graph on `7` vertices is a `6`-regular graph, so it can 

be edge-partitionned into `2`-regular graphs:: 

 

sage: g = graphs.CompleteGraph(7) 

sage: classes = g.two_factor_petersen() 

sage: for c in classes: 

....: gg = Graph() 

....: gg.add_edges(c) 

....: print(max(gg.degree())<=2) 

True 

True 

True 

sage: Set(set(classes[0]) | set(classes[1]) | set(classes[2])).cardinality() == g.size() 

True 

 

:: 

 

sage: g = graphs.CirculantGraph(24, [7, 11]) 

sage: cl = g.two_factor_petersen() 

sage: g.plot(edge_colors={'black':cl[0], 'red':cl[1]}) 

Graphics object consisting of 73 graphics primitives 

 

""" 

self._scream_if_not_simple() 

d = self.eulerian_orientation() 

 

# This new graph is bipartite, and built the following way : 

# 

# To each vertex v of the digraph are associated two vertices, 

# a sink (-1,v) and a source (1,v) 

# Any edge (u,v) in the digraph is then added as ((-1,u),(1,v)) 

 

from sage.graphs.graph import Graph 

g = Graph() 

g.add_edges([((-1,u),(1,v)) for (u,v) in d.edge_iterator(labels=None)]) 

 

# This new bipartite graph is now edge_colored 

from sage.graphs.graph_coloring import edge_coloring 

classes = edge_coloring(g) 

 

# The edges in the classes are of the form ((-1,u),(1,v)) 

# and have to be translated back to (u,v) 

classes_b = [] 

for c in classes: 

classes_b.append([(u,v) for ((uu,u),(vv,v)) in c]) 

 

return classes_b 

 

@doc_index("Leftovers") 

def kirchhoff_symanzik_polynomial(self, name='t'): 

""" 

Return the Kirchhoff-Symanzik polynomial of a graph. 

 

This is a polynomial in variables `t_e` (each of them representing an 

edge of the graph `G`) defined as a sum over all spanning trees: 

 

.. MATH:: 

 

\Psi_G(t) = \sum_{\substack{T\subseteq V \\ \text{a spanning tree}}} \prod_{e \\not\in E(T)} t_e 

 

This is also called the first Symanzik polynomial or the Kirchhoff 

polynomial. 

 

INPUT: 

 

- ``name``: name of the variables (default: ``'t'``) 

 

OUTPUT: 

 

- a polynomial with integer coefficients 

 

ALGORITHM: 

 

This is computed here using a determinant, as explained in Section 

3.1 of [Marcolli2009]_. 

 

As an intermediate step, one computes a cycle basis `\mathcal C` of 

`G` and a rectangular `|\mathcal C| \\times |E(G)|` matrix with 

entries in `\{-1,0,1\}`, which describes which edge belong to which 

cycle of `\mathcal C` and their respective orientations. 

 

More precisely, after fixing an arbitrary orientation for each edge 

`e\in E(G)` and each cycle `C\in\mathcal C`, one gets a sign for 

every incident pair (edge, cycle) which is `1` if the orientation 

coincide and `-1` otherwise. 

 

EXAMPLES: 

 

For the cycle of length 5:: 

 

sage: G = graphs.CycleGraph(5) 

sage: G.kirchhoff_symanzik_polynomial() 

t0 + t1 + t2 + t3 + t4 

 

One can use another letter for variables:: 

 

sage: G.kirchhoff_symanzik_polynomial(name='u') 

u0 + u1 + u2 + u3 + u4 

 

For the 'coffee bean' graph:: 

 

sage: G = Graph([(0,1,'a'),(0,1,'b'),(0,1,'c')],multiedges=True) 

sage: G.kirchhoff_symanzik_polynomial() 

t0*t1 + t0*t2 + t1*t2 

 

For the 'parachute' graph:: 

 

sage: G = Graph([(0,2,'a'),(0,2,'b'),(0,1,'c'),(1,2,'d')], multiedges=True) 

sage: G.kirchhoff_symanzik_polynomial() 

t0*t1 + t0*t2 + t1*t2 + t1*t3 + t2*t3 

 

For the complete graph with 4 vertices:: 

 

sage: G = graphs.CompleteGraph(4) 

sage: G.kirchhoff_symanzik_polynomial() 

t0*t1*t3 + t0*t2*t3 + t1*t2*t3 + t0*t1*t4 + t0*t2*t4 + t1*t2*t4 

+ t1*t3*t4 + t2*t3*t4 + t0*t1*t5 + t0*t2*t5 + t1*t2*t5 + t0*t3*t5 

+ t2*t3*t5 + t0*t4*t5 + t1*t4*t5 + t3*t4*t5 

 

REFERENCES: 

 

.. [Marcolli2009] Matilde Marcolli, Feynman Motives, Chapter 3, 

Feynman integrals and algebraic varieties, 

http://www.its.caltech.edu/~matilde/LectureN3.pdf 

 

.. [Brown2011] Francis Brown, Multiple zeta values and periods: From 

moduli spaces to Feynman integrals, in Contemporary Mathematics vol 

539 

""" 

from sage.matrix.constructor import matrix 

from sage.rings.integer_ring import ZZ 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

edges = self.edges() 

cycles = self.cycle_basis(output='edge') 

 

edge2int = {e: j for j, e in enumerate(edges)} 

circuit_mtrx = matrix(ZZ, self.size(), len(cycles)) 

for i, cycle in enumerate(cycles): 

for edge in cycle: 

if edge in edges: 

circuit_mtrx[edge2int[edge], i] = +1 

else: 

circuit_mtrx[edge2int[(edge[1], edge[0], edge[2])], i] = -1 

 

D = matrix.diagonal(PolynomialRing(ZZ, name, self.size()).gens()) 

return (circuit_mtrx.transpose() * D * circuit_mtrx).determinant() 

 

@doc_index("Leftovers") 

def magnitude_function(self): 

""" 

Return the magnitude function of the graph as a rational function. 

 

This is defined as the sum of all coefficients in the inverse 

of the matrix `Z` whose coefficient `Z_{i,j}` indexed by a 

pair of vertices `(i,j)` is `q^d(i,j)` where `d` is the distance 

function in the graph. 

 

By convention, if the distance from `i` to `j` is infinite 

(for two vertices not path connected) then `Z_{i,j}=0`. 

 

The value of the magnitude function at `q=0` is the 

cardinality of the graph. The magnitude function of a disjoint 

union is the sum of the magnitudes functions of the connected 

components. The magnitude function of a Cartesian product is 

the product of the magnitudes functions of the factors. 

 

EXAMPLES:: 

 

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

sage: g.magnitude_function() 

2 

 

sage: g = graphs.CycleGraph(4) 

sage: g.magnitude_function() 

4/(q^2 + 2*q + 1) 

 

sage: g = graphs.CycleGraph(5) 

sage: m = g.magnitude_function(); m 

5/(2*q^2 + 2*q + 1) 

 

One can expand the magnitude as a power series in `q` as follows:: 

 

sage: q = QQ[['q']].gen() 

sage: m(q) 

5 - 10*q + 10*q^2 - 20*q^4 + 40*q^5 - 40*q^6 + ... 

 

One can also use the substitution `q = exp(-t)` to obtain 

the magnitude function as a function of `t`:: 

 

sage: g = graphs.CycleGraph(6) 

sage: m = g.magnitude_function() 

sage: t = var('t') 

sage: m(exp(-t)) 

6/(2*e^(-t) + 2*e^(-2*t) + e^(-3*t) + 1) 

 

TESTS:: 

 

sage: g = Graph() 

sage: g.magnitude_function() 

0 

 

sage: g = Graph({1:[]}) 

sage: g.magnitude_function() 

1 

 

sage: g = graphs.PathGraph(4) 

sage: g.magnitude_function() 

(-2*q + 4)/(q + 1) 

 

REFERENCES: 

 

.. [Lein] Tom Leinster, *The magnitude of metric spaces*. 

Doc. Math. 18 (2013), 857-905. 

""" 

from sage.matrix.constructor import matrix 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

from sage.graphs.distances_all_pairs import distances_all_pairs 

 

ring = PolynomialRing(ZZ, 'q') 

q = ring.gen() 

N = self.order() 

if not N: 

return ring.zero() 

dist = distances_all_pairs(self) 

vertices = list(self) 

Z = matrix(ring, N, N, ring.zero()) 

for i in range(N): 

Z[i, i] = ring.one() 

for i in range(N): 

for j in range(i): 

dij = dist[vertices[i]][vertices[j]] 

if dij in ZZ: 

Z[i, j] = Z[j, i] = q ** dij 

else: 

Z[i, j] = Z[j, i] = ring.zero() 

return sum(sum(u) for u in ~Z) 

 

@doc_index("Leftovers") 

def ihara_zeta_function_inverse(self): 

""" 

Compute the inverse of the Ihara zeta function of the graph. 

 

This is a polynomial in one variable with integer coefficients. The 

Ihara zeta function itself is the inverse of this polynomial. 

 

See :wikipedia:`Ihara zeta function`. 

 

ALGORITHM: 

 

This is computed here as the (reversed) characteristic 

polynomial of a square matrix of size twice the number of edges, 

related to the adjacency matrix of the line graph, see for example 

Proposition 9 in [ScottStorm]_ and Def. 4.1 in [Terras]_. 

 

The graph is first replaced by its 2-core, as this does not change 

the Ihara zeta function. 

 

EXAMPLES:: 

 

sage: G = graphs.CompleteGraph(4) 

sage: factor(G.ihara_zeta_function_inverse()) 

(2*t - 1) * (t + 1)^2 * (t - 1)^3 * (2*t^2 + t + 1)^3 

 

sage: G = graphs.CompleteGraph(5) 

sage: factor(G.ihara_zeta_function_inverse()) 

(-1) * (3*t - 1) * (t + 1)^5 * (t - 1)^6 * (3*t^2 + t + 1)^4 

 

sage: G = graphs.PetersenGraph() 

sage: factor(G.ihara_zeta_function_inverse()) 

(-1) * (2*t - 1) * (t + 1)^5 * (t - 1)^6 * (2*t^2 + 2*t + 1)^4 

* (2*t^2 - t + 1)^5 

 

sage: G = graphs.RandomTree(10) 

sage: G.ihara_zeta_function_inverse() 

1 

 

REFERENCES: 

 

.. [HST] Matthew D. Horton, H. M. Stark, and Audrey A. Terras, 

What are zeta functions of graphs and what are they good for? 

in Quantum graphs and their applications, 173-189, 

Contemp. Math., Vol. 415 

 

.. [Terras] Audrey Terras, Zeta functions of graphs: a stroll through 

the garden, Cambridge Studies in Advanced Mathematics, Vol. 128 

 

.. [ScottStorm] Geoffrey Scott and Christopher Storm, The coefficients 

of the Ihara zeta function, Involve (http://msp.org/involve/2008/1-2/involve-v1-n2-p08-p.pdf) 

""" 

from sage.matrix.constructor import matrix 

 

H = self.subgraph(vertices=self.cores(k=2)[1]) 

E = H.edges() 

m = len(E) 

# compute (Hashimoto) edge matrix T 

T = matrix(ZZ, 2 * m, 2 * m, 0) 

for i in range(m): 

for j in range(m): 

if i != j: 

if E[i][1] == E[j][0]: # same orientation 

T[2 * i, 2 * j] = 1 

T[2 * j + 1, 2 * i + 1] = 1 

elif E[i][1] == E[j][1]: # opposite orientation (towards) 

T[2 * i, 2 * j + 1] = 1 

T[2 * j, 2 * i + 1] = 1 

elif E[i][0] == E[j][0]: # opposite orientation (away) 

T[2 * i + 1, 2 * j] = 1 

T[2 * j + 1, 2 * i] = 1 

return T.charpoly('t').reverse() 

 

@doc_index("Leftovers") 

def perfect_matchings(self, labels=False): 

""" 

Return an iterator over all perfect matchings of the graph. 

 

ALGORITHM: 

 

Choose a vertex `v`, then recurse through all edges incident to `v`, 

removing one edge at a time whenever an edge is added to a matching. 

 

INPUT: 

 

- ``labels`` -- boolean (default: ``False``); when ``True``, the 

edges in each perfect matching are triples (containing the label 

as the third element), otherwise the edges are pairs 

 

.. SEEALSO:: 

 

:meth:`matching` 

 

EXAMPLES:: 

 

sage: G=graphs.GridGraph([2,3]) 

sage: list(G.perfect_matchings()) 

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

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

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

 

sage: G = graphs.CompleteGraph(4) 

sage: list(G.perfect_matchings(labels=True)) 

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

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

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

 

sage: G = Graph([[1,-1,'a'], [2,-2, 'b'], [1,-2,'x'], [2,-1,'y']]) 

sage: list(G.perfect_matchings(labels=True)) 

[[(-2, 1, 'x'), (-1, 2, 'y')], [(-2, 2, 'b'), (-1, 1, 'a')]] 

 

sage: G = graphs.CompleteGraph(8) 

sage: mpc = G.matching_polynomial().coefficients(sparse=False)[0] 

sage: len(list(G.perfect_matchings())) == mpc 

True 

 

sage: G = graphs.PetersenGraph().copy(immutable=True) 

sage: list(G.perfect_matchings()) 

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

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

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

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

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

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

 

sage: list(Graph().perfect_matchings()) 

[[]] 

 

sage: G = graphs.CompleteGraph(5) 

sage: list(G.perfect_matchings()) 

[] 

""" 

if not self: 

yield [] 

return 

# if every connected component has an even number of vertices 

if all(len(cc) % 2 == 0 for cc in self.connected_components()): 

v = next(self.vertex_iterator()) 

for e in self.edges_incident(v, labels=labels): 

Gp = self.copy(immutable=False) 

Gp.delete_vertices([e[0], e[1]]) 

for mat in Gp.perfect_matchings(labels): 

yield [e] + mat 

 

@doc_index("Leftovers") 

def has_perfect_matching(self, algorithm="Edmonds", solver=None, verbose=0): 

r""" 

Return whether this graph has a perfect matching. 

 

INPUT: 

 

- ``algorithm`` -- string (default: ``"Edmonds"``) 

 

- ``"Edmonds"`` uses Edmonds' algorithm as implemented in NetworkX to 

find a matching of maximal cardinality, then check whether this 

cardinality is half the number of vertices of the graph. 

 

- ``"LP_matching"`` uses a Linear Program to find a matching of 

maximal cardinality, then check whether this cardinality is half the 

number of vertices of the graph. 

 

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

problem: put a binary variable ``b[e]`` on each edge ``e``, and for 

each vertex ``v``, require that the sum of the values of the edges 

incident to ``v`` is 1. 

 

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

solver to be used; if set to ``None``, the default one is used 

 

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

set to 0 by default, which means quiet (only useful when 

``algorithm == "LP_matching"`` or ``algorithm == "LP"``) 

 

For more information on LP solvers and which default solver is 

used, see the method 

:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>` 

of the class :class:`MixedIntegerLinearProgram 

<sage.numerical.mip.MixedIntegerLinearProgram>`. 

 

OUTPUT: 

 

A boolean. 

 

EXAMPLES:: 

 

sage: graphs.PetersenGraph().has_perfect_matching() 

True 

sage: graphs.WheelGraph(6).has_perfect_matching() 

True 

sage: graphs.WheelGraph(5).has_perfect_matching() 

False 

sage: graphs.PetersenGraph().has_perfect_matching(algorithm="LP_matching") 

True 

sage: graphs.WheelGraph(6).has_perfect_matching(algorithm="LP_matching") 

True 

sage: graphs.WheelGraph(5).has_perfect_matching(algorithm="LP_matching") 

False 

sage: graphs.PetersenGraph().has_perfect_matching(algorithm="LP_matching") 

True 

sage: graphs.WheelGraph(6).has_perfect_matching(algorithm="LP_matching") 

True 

sage: graphs.WheelGraph(5).has_perfect_matching(algorithm="LP_matching") 

False 

 

TESTS:: 

 

sage: G = graphs.EmptyGraph() 

sage: all(G.has_perfect_matching(algorithm=algo) for algo in ['Edmonds', 'LP_matching', 'LP']) 

True 

 

Be careful with isolated vertices:: 

 

sage: G = graphs.PetersenGraph() 

sage: G.add_vertex(11) 

sage: any(G.has_perfect_matching(algorithm=algo) for algo in ['Edmonds', 'LP_matching', 'LP']) 

False 

""" 

if self.order() % 2: 

return False 

if algorithm == "Edmonds": 

return len(self) == 2*self.matching(value_only=True, 

use_edge_labels=False, 

algorithm="Edmonds") 

elif algorithm == "LP_matching": 

return len(self) == 2*self.matching(value_only=True, 

use_edge_labels=False, 

algorithm="LP", 

solver=solver, 

verbose=verbose) 

elif algorithm == "LP": 

from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException 

p = MixedIntegerLinearProgram(solver=solver) 

b = p.new_variable(binary = True) 

for v in self: 

edges = self.edges_incident(v, labels=False) 

if not edges: 

return False 

p.add_constraint(p.sum(b[e] for e in edges) == 1) 

try: 

p.solve(log=verbose) 

return True 

except MIPSolverException: 

return False 

else: 

raise ValueError('algorithm must be set to "Edmonds", "LP_matching" or "LP"') 

 

# Aliases to functions defined in other modules 

from sage.graphs.weakly_chordal import is_long_hole_free, is_long_antihole_free, is_weakly_chordal 

from sage.graphs.asteroidal_triples import is_asteroidal_triple_free 

from sage.graphs.chrompoly import chromatic_polynomial 

from sage.graphs.graph_decompositions.rankwidth import rank_decomposition 

from sage.graphs.graph_decompositions.vertex_separation import pathwidth 

from sage.graphs.matchpoly import matching_polynomial 

from sage.graphs.cliquer import all_max_clique as cliques_maximum 

from sage.graphs.spanning_tree import random_spanning_tree 

from sage.graphs.graph_decompositions.graph_products import is_cartesian_product 

from sage.graphs.distances_all_pairs import is_distance_regular 

from sage.graphs.base.static_dense_graph import is_strongly_regular 

from sage.graphs.line_graph import is_line_graph 

from sage.graphs.tutte_polynomial import tutte_polynomial 

from sage.graphs.lovasz_theta import lovasz_theta 

from sage.graphs.partial_cube import is_partial_cube 

from sage.graphs.orientations import strong_orientations_iterator 

 

 

_additional_categories = { 

"is_long_hole_free" : "Graph properties", 

"is_long_antihole_free" : "Graph properties", 

"is_weakly_chordal" : "Graph properties", 

"is_asteroidal_triple_free" : "Graph properties", 

"chromatic_polynomial" : "Algorithmically hard stuff", 

"rank_decomposition" : "Algorithmically hard stuff", 

"pathwidth" : "Algorithmically hard stuff", 

"matching_polynomial" : "Algorithmically hard stuff", 

"all_max_cliques" : "Clique-related methods", 

"cliques_maximum" : "Clique-related methods", 

"random_spanning_tree" : "Connectivity, orientations, trees", 

"is_cartesian_product" : "Graph properties", 

"is_distance_regular" : "Graph properties", 

"is_strongly_regular" : "Graph properties", 

"is_line_graph" : "Graph properties", 

"is_partial_cube" : "Graph properties", 

"tutte_polynomial" : "Algorithmically hard stuff", 

"lovasz_theta" : "Leftovers", 

"strong_orientations_iterator" : "Connectivity, orientations, trees" 

} 

 

__doc__ = __doc__.replace("{INDEX_OF_METHODS}",gen_thematic_rest_table_index(Graph,_additional_categories))