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

# cython: binding=True 

r""" 

Vertex separation 

  

This module implements several algorithms to compute the vertex separation of a 

digraph and the corresponding ordering of the vertices. It also implements tests 

functions for evaluation the width of a linear ordering. 

  

Given an ordering 

`v_1,\cdots, v_n` of the vertices of `V(G)`, its *cost* is defined as: 

  

.. MATH:: 

  

c(v_1, ..., v_n) = \max_{1\leq i \leq n} c'(\{v_1, ..., v_i\}) 

  

Where 

  

.. MATH:: 

  

c'(S) = |N^+_G(S)\backslash S| 

  

The *vertex separation* of a digraph `G` is equal to the minimum cost of an 

ordering of its vertices. 

  

**Vertex separation and pathwidth** 

  

The vertex separation is defined on a digraph, but one can obtain from a graph 

`G` a digraph `D` with the same vertex set, and in which each edge `uv` of `G` 

is replaced by two edges `uv` and `vu` in `D`. The vertex separation of `D` is 

equal to the pathwidth of `G`, and the corresponding ordering of the vertices of 

`D`, also called a *layout*, encodes an optimal path-decomposition of `G`. 

This is a result of Kinnersley [Kin92]_ and Bodlaender [Bod98]_. 

  

  

**This module contains the following methods** 

  

.. csv-table:: 

:class: contentstable 

:widths: 30, 70 

:delim: | 

  

:meth:`pathwidth` | Computes the pathwidth of ``self`` (and provides a decomposition) 

:meth:`path_decomposition` | Returns the pathwidth of the given graph and the ordering of the vertices resulting in a corresponding path decomposition 

:meth:`vertex_separation` | Returns an optimal ordering of the vertices and its cost for vertex-separation 

:meth:`vertex_separation_exp` | Computes the vertex separation of `G` using an exponential time and space algorithm 

:meth:`vertex_separation_MILP` | Computes the vertex separation of `G` and the optimal ordering of its vertices using an MILP formulation 

:meth:`vertex_separation_BAB` | Computes the vertex separation of `G` and the optimal ordering of its vertices using a branch and bound algorithm 

:meth:`lower_bound` | Returns a lower bound on the vertex separation of `G` 

:meth:`is_valid_ordering` | Test if the linear vertex ordering `L` is valid for (di)graph `G` 

:meth:`width_of_path_decomposition` | Returns the width of the path decomposition induced by the linear ordering `L` of the vertices of `G` 

:meth:`linear_ordering_to_path_decomposition`| Return the path decomposition encoded in the ordering `L` 

  

  

Exponential algorithm for vertex separation 

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

  

In order to find an optimal ordering of the vertices for the vertex separation, 

this algorithm tries to save time by computing the function `c'(S)` **at most 

once** once for each of the sets `S\subseteq V(G)`. These values are stored in 

an array of size `2^n` where reading the value of `c'(S)` or updating it can be 

done in constant (and small) time. 

  

Assuming that we can compute the cost of a set `S` and remember it, finding an 

optimal ordering is an easy task. Indeed, we can think of the sequence `v_1, 

..., v_n` of vertices as a sequence of *sets* `\{v_1\}, \{v_1,v_2\}, ..., 

\{v_1,...,v_n\}`, whose cost is precisely `\max c'(\{v_1\}), c'(\{v_1,v_2\}), 

... , c'(\{v_1,...,v_n\})`. Hence, when considering the digraph on the `2^n` 

sets `S\subseteq V(G)` where there is an arc from `S` to `S'` if `S'=S\cap 

\{v\}` for some `v` (that is, if the sets `S` and `S'` can be consecutive in a 

sequence), an ordering of the vertices of `G` corresponds to a *path* from 

`\emptyset` to `\{v_1,...,v_n\}`. In this setting, checking whether there exists 

a ordering of cost less than `k` can be achieved by checking whether there 

exists a directed path `\emptyset` to `\{v_1,...,v_n\}` using only sets of cost 

less than `k`. This is just a depth-first-search, for each `k`. 

  

**Lazy evaluation of** `c'` 

  

In the previous algorithm, most of the time is actually spent on the computation 

of `c'(S)` for each set `S\subseteq V(G)` -- i.e. `2^n` computations of 

neighborhoods. This can be seen as a huge waste of time when noticing that it is 

useless to know that the value `c'(S)` for a set `S` is less than `k` if all the 

paths leading to `S` have a cost greater than `k`. For this reason, the value of 

`c'(S)` is computed lazily during the depth-first search. Explanation : 

  

When the depth-first search discovers a set of size less than `k`, the costs of 

its out-neighbors (the potential sets that could follow it in the optimal 

ordering) are evaluated. When an out-neighbor is found that has a cost smaller 

than `k`, the depth-first search continues with this set, which is explored with 

the hope that it could lead to a path toward `\{v_1,...,v_n\}`. On the other 

hand, if an out-neighbour has a cost larger than `k` it is useless to attempt to 

build a cheap sequence going though this set, and the exploration stops 

there. This way, a large number of sets will never be evaluated and *a lot* of 

computational time is saved this way. 

  

Besides, some improvement is also made by "improving" the values found by 

`c'`. Indeed, `c'(S)` is a lower bound on the cost of a sequence containing the 

set `S`, but if all out-neighbors of `S` have a cost of `c'(S) + 5` then one 

knows that having `S` in a sequence means a total cost of at least `c'(S) + 

5`. For this reason, for each set `S` we store the value of `c'(S)`, and replace 

it by `\max (c'(S), \min_{\text{next}})` (where `\min_{\text{next}}` is the 

minimum of the costs of the out-neighbors of `S`) once the costs of these 

out-neighbors have been evaluated by the algorithm. 

  

.. NOTE:: 

  

Because of its current implementation, this algorithm only works on graphs 

on less than 32 vertices. This can be changed to 64 if necessary, but 32 

vertices already require 4GB of memory. Running it on 64 bits is not 

expected to be doable by the computers of the next decade `:-D` 

  

**Lower bound on the vertex separation** 

  

One can obtain a lower bound on the vertex separation of a graph in exponential 

time but *small* memory by computing once the cost of each set `S`. Indeed, the 

cost of a sequence `v_1, ..., v_n` corresponding to sets `\{v_1\}, \{v_1,v_2\}, 

..., \{v_1,...,v_n\}` is 

  

.. MATH:: 

  

\max c'(\{v_1\}),c'(\{v_1,v_2\}),...,c'(\{v_1,...,v_n\})\geq\max c'_1,...,c'_n 

  

where `c_i` is the minimum cost of a set `S` on `i` vertices. Evaluating the 

`c_i` can take time (and in particular more than the previous exact algorithm), 

but it does not need much memory to run. 

  

  

MILP formulation for the vertex separation 

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

  

We describe below a mixed integer linear program (MILP) for determining an 

optimal layout for the vertex separation of `G`, which is an improved version of 

the formulation proposed in [SP10]_. It aims at building a sequence `S_t` of 

sets such that an ordering `v_1, ..., v_n` of the vertices correspond to 

`S_0=\{v_1\}, S_2=\{v_1,v_2\}, ..., S_{n-1}=\{v_1,...,v_n\}`. 

  

**Variables:** 

  

  

- `y_v^t` -- Variable set to 1 if `v\in S_t`, and 0 otherwise. The order of 

`v` in the layout is the smallest `t` such that `y_v^t==1`. 

  

- `u_v^t` -- Variable set to 1 if `v\not \in S_t` and `v` has an in-neighbor in 

`S_t`. It is set to 0 otherwise. 

  

- `x_v^t` -- Variable set to 1 if either `v\in S_t` or if `v` has an in-neighbor 

in `S_t`. It is set to 0 otherwise. 

  

- `z` -- Objective value to minimize. It is equal to the maximum over all step 

`t` of the number of vertices such that `u_v^t==1`. 

  

**MILP formulation:** 

  

.. MATH:: 

:nowrap: 

  

\begin{alignat}{2} 

\text{Minimize:} 

&z&\\ 

\text{Such that:} 

x_v^t &\leq x_v^{t+1}& \forall v\in V,\ 0\leq t\leq n-2\\ 

y_v^t &\leq y_v^{t+1}& \forall v\in V,\ 0\leq t\leq n-2\\ 

y_v^t &\leq x_w^t& \forall v\in V,\ \forall w\in N^+(v),\ 0\leq t\leq n-1\\ 

\sum_{v \in V} y_v^{t} &= t+1& 0\leq t\leq n-1\\ 

x_v^t-y_v^t&\leq u_v^t & \forall v \in V,\ 0\leq t\leq n-1\\ 

\sum_{v \in V} u_v^t &\leq z& 0\leq t\leq n-1\\ 

0 \leq x_v^t &\leq 1& \forall v\in V,\ 0\leq t\leq n-1\\ 

0 \leq u_v^t &\leq 1& \forall v\in V,\ 0\leq t\leq n-1\\ 

y_v^t &\in \{0,1\}& \forall v\in V,\ 0\leq t\leq n-1\\ 

0 \leq z &\leq n& 

\end{alignat} 

  

The vertex separation of `G` is given by the value of `z`, and the order of 

vertex `v` in the optimal layout is given by the smallest `t` for which 

`y_v^t==1`. 

  

  

Branch and Bound algorithm for the vertex separation 

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

  

We describe below the principle of a branch and bound algorithm (BAB) for 

determining an optimal ordering for the vertex separation of `G`, as proposed in 

[CMN14]_. 

  

**Greedy steps:** 

  

Let us denote `{\cal L}(S)` the set of all possible orderings of the vertices in 

`S`, and let `{\cal L}_P(S)\subseteq {\cal L}(S)` be the orderings starting with 

a prefix `P`. Let also `c(L)` be the cost of the ordering `L\in{\cal L}(V)` as 

defined above. 

  

Given a digraph `D=(V,A)`, a set `S\subset V`, and a prefix `P`, it has been 

proved in [CMN14]_ that `\min_{L\in{\cal L}_P(V)} c(L) = \min_{L\in{\cal 

L}_{P+v}(V)} c(L)` holds in two (non exhaustive) cases: 

  

.. MATH:: 

  

\text{or} \begin{cases} 

N^+(v)\subseteq S\cup N^+(S)\\ 

v\in N^+(S)\text{ and }N^+(v)\setminus(S\cup N^+(S)) = \{w\} 

\end{cases} 

  

In other words, if we find a vertex `v` satisfying the above conditions, the best 

possible ordering with prefix `P` has the same cost as the best possible 

ordering with prefix `P+v`. So we can greedily extend the prefix with vertices 

satisfying the conditions which results in a significant reduction of the search 

space. 

  

  

**The algorithm:** 

  

Given the current prefix `P` and the current upper bound `UB` (either an input 

upper bound or the cost of the best solution found so far), apply the following 

steps: 

  

- Extend the prefix `P` into a prefix `P'` using the greedy steps as described 

above. 

  

- Sort the vertices `v\in V\setminus P'` by increasing values of `|N^+(P+v)|`, 

and prune the vertices with a value larger or equal to `UB`. Let `\Delta` be 

the resulting sorted list. 

  

- Repeat with prefix `P'+v` for all `v\in\Delta` and keep the best found 

solution. 

  

If a lower bound is passed to the algorithm, it will stop as soon as a solution 

with cost equal to that lower bound is found. 

  

  

**Storing prefixes:** 

  

If for a prefix `P` we have `c(P)<\min_{L\in{\cal L}_P(V)} c(L)=C`, then for any 

permutation `P'` of `P` we have `\min_{L\in{\cal L}_{P'}(V)} c(L)\geq C`. 

  

Thus, given such a prefix `P` there is no need to explore any of the orderings 

starting with one of its permutations. To do so, we store `P` (as a set of 

vertices) to cut branches later. See [CMN14]_ for more details. 

  

Since the number of stored sets can get very large, one can control the maximum 

length and the maximum number of stored prefixes. 

  

  

REFERENCES 

---------- 

  

.. [Bod98] *A partial k-arboretum of graphs with bounded treewidth*, Hans 

L. Bodlaender, Theoretical Computer Science 209(1-2):1-45, 1998. 

  

.. [Kin92] *The vertex separation number of a graph equals its path-width*, 

Nancy G. Kinnersley, Information Processing Letters 42(6):345-350, 1992. 

  

.. [SP10] *Lightpath Reconfiguration in WDM networks*, Fernando Solano and 

Michal Pioro, IEEE/OSA Journal of Optical Communication and Networking 

2(12):1010-1021, 2010. 

  

.. [CMN14] *Experimental Evaluation of a Branch and Bound Algorithm for 

computing Pathwidth*, David Coudert, Dorian Mazauric, and Nicolas Nisse. In 

Symposium on Experimental Algorithms (SEA), volume 8504 of LNCS, Copenhagen, 

Denmark, pages 46-58, June 2014, 

http://hal.inria.fr/hal-00943549/document 

  

Authors 

------- 

  

- Nathann Cohen (2011-10): Initial version and exact exponential algorithm 

  

- David Coudert (2012-04): MILP formulation and tests functions 

  

- David Coudert (2015-01): BAB formulation and tests functions 

  

  

Methods 

------- 

""" 

  

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

# Copyright (C) 2011 Nathann Cohen <nathann.cohen@gmail.com> 

# 

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

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

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

# (at your option) any later version. 

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

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

  

from __future__ import absolute_import, print_function 

  

from libc.string cimport memset 

from cysignals.memory cimport check_malloc, sig_malloc, sig_free 

from cysignals.signals cimport sig_check, sig_on, sig_off 

  

from sage.graphs.graph_decompositions.fast_digraph cimport FastDigraph, compute_out_neighborhood_cardinality, popcount32 

from libc.stdint cimport uint8_t, int8_t 

include "sage/data_structures/binary_matrix.pxi" 

from sage.graphs.base.static_dense_graph cimport dense_graph_init 

  

  

############### 

# Lower Bound # 

############### 

  

def lower_bound(G): 

r""" 

Returns a lower bound on the vertex separation of `G` 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph 

  

OUTPUT: 

  

A lower bound on the vertex separation of `D` (see the module's 

documentation). 

  

.. NOTE:: 

  

This method runs in exponential time but has no memory constraint. 

  

  

EXAMPLES: 

  

On a circuit:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import lower_bound 

sage: g = digraphs.Circuit(6) 

sage: lower_bound(g) 

1 

  

TESTS: 

  

Given anything else than a Graph or a DiGraph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import lower_bound 

sage: lower_bound(range(2)) 

Traceback (most recent call last): 

... 

ValueError: The parameter must be a Graph or a DiGraph. 

  

Given a too large graph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import lower_bound 

sage: lower_bound(graphs.PathGraph(50)) 

Traceback (most recent call last): 

... 

ValueError: The (di)graph can have at most 31 vertices. 

  

""" 

from sage.graphs.graph import Graph 

from sage.graphs.digraph import DiGraph 

if not isinstance(G, Graph) and not isinstance(G, DiGraph): 

raise ValueError("The parameter must be a Graph or a DiGraph.") 

  

if G.order() >= 32: 

raise ValueError("The (di)graph can have at most 31 vertices.") 

  

cdef FastDigraph FD = FastDigraph(G) 

cdef int * g = FD.graph 

cdef int n = FD.n 

  

# minimums[i] is means to store the value of c'_{i+1} 

minimums = <uint8_t *>check_malloc(n) 

cdef unsigned int i 

  

# They are initialized to n 

for 0<= i< n: 

minimums[i] = n 

  

cdef uint8_t tmp, tmp_count 

  

# We go through all sets 

for 1<= i< <unsigned int> (1<<n): 

tmp_count = <uint8_t> popcount32(i) 

tmp = <uint8_t> compute_out_neighborhood_cardinality(FD, i) 

  

# And update the costs 

minimums[tmp_count-1] = minimum(minimums[tmp_count-1], tmp) 

  

# We compute the maximum of all those values 

for 1<= i< n: 

minimums[0] = maximum(minimums[0], minimums[i]) 

  

cdef int min = minimums[0] 

  

sig_free(minimums) 

  

return min 

  

################################################################### 

# Method for turning an ordering to a path decomposition and back # 

################################################################### 

  

def linear_ordering_to_path_decomposition(G, L): 

""" 

Return the path decomposition encoded in the ordering L 

  

INPUT: 

  

- ``G`` -- a Graph 

  

- ``L`` -- a linear ordering for G 

  

OUTPUT: 

  

A path graph whose vertices are the bags of the path decomposition. 

  

EXAMPLES: 

  

The bags of an optimal path decomposition of a path-graph have two vertices each:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation 

sage: from sage.graphs.graph_decompositions.vertex_separation import linear_ordering_to_path_decomposition 

sage: g = graphs.PathGraph(5) 

sage: pw, L = vertex_separation(g, algorithm = "BAB"); pw 

1 

sage: h = linear_ordering_to_path_decomposition(g, L) 

sage: h.vertices() 

[{0, 1}, {3, 4}, {2, 3}, {1, 2}] 

sage: h.edges(labels=None) 

[({0, 1}, {1, 2}), ({2, 3}, {3, 4}), ({1, 2}, {2, 3})] 

  

Giving a non-optimal linear ordering:: 

  

sage: g = graphs.PathGraph(5) 

sage: L = [1, 4, 0, 2, 3] 

sage: from sage.graphs.graph_decompositions.vertex_separation import width_of_path_decomposition 

sage: width_of_path_decomposition(g, L) 

3 

sage: h = linear_ordering_to_path_decomposition(g, L) 

sage: h.vertices() 

[{0, 2, 3, 4}, {0, 1, 2}] 

 

The bags of the path decomposition of a cycle have three vertices each:: 

  

sage: g = graphs.CycleGraph(6) 

sage: pw, L = vertex_separation(g, algorithm = "BAB"); pw 

2 

sage: h = linear_ordering_to_path_decomposition(g, L) 

sage: h.vertices() 

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

sage: h.edges(labels=None) 

[({1, 2, 5}, {2, 4, 5}), ({0, 1, 5}, {1, 2, 5}), ({2, 4, 5}, {2, 3, 4})] 

  

  

TESTS:: 

  

sage: linear_ordering_to_path_decomposition(Graph(), []) 

Graph on 0 vertices 

sage: linear_ordering_to_path_decomposition(DiGraph(), []) 

Traceback (most recent call last): 

... 

ValueError: the first parameter must be a Graph 

sage: g = graphs.CycleGraph(6) 

sage: linear_ordering_to_path_decomposition(g, list(range(7))) 

Traceback (most recent call last): 

... 

ValueError: the input linear vertex ordering L is not valid for G 

""" 

from sage.graphs.graph import Graph 

if not isinstance(G, Graph): 

raise ValueError("the first parameter must be a Graph") 

if not G: 

return Graph() 

if not is_valid_ordering(G, L): 

raise ValueError("the input linear vertex ordering L is not valid for G") 

  

cdef set seen = set() # already treated vertices 

cdef set covered = set() # vertices in the neighborhood of seen but not in seen 

cdef list bags = list() # The bags of the path decomposition 

  

# We build the bags of the path-decomposition, and avoid adding useless bags 

for u in L: 

seen.add(u) 

covered.update(G.neighbors(u)) 

covered.difference_update(seen) 

new_bag = covered.union([u]) 

if bags: 

if new_bag.issubset(bags[-1]): 

continue 

if new_bag.issuperset(bags[-1]): 

bags.pop() 

  

bags.append(new_bag) 

  

# We now build a graph whose vertices are bags 

from sage.sets.set import Set 

H = Graph() 

H.add_path([Set(bag) for bag in bags]) 

return H 

  

  

  

################################################################## 

# Front end methods for path decomposition and vertex separation # 

################################################################## 

  

def pathwidth(self, k=None, certificate=False, algorithm="BAB", verbose=False, 

max_prefix_length=20, max_prefix_number=10**6): 

""" 

Computes the pathwidth of ``self`` (and provides a decomposition) 

  

INPUT: 

  

- ``k`` (integer) -- the width to be considered. When ``k`` is an integer, 

the method checks that the graph has pathwidth `\leq k`. If ``k`` is 

``None`` (default), the method computes the optimal pathwidth. 

  

- ``certificate`` -- whether to return the path-decomposition itself. 

  

- ``algorithm`` -- (default: ``"BAB"``) Specify the algorithm to use among 

  

- ``"BAB"`` -- Use a branch-and-bound algorithm. This algorithm has no 

size restriction but could take a very long time on large graphs. It can 

also be used to test is the input graph has pathwidth `\leq k`, in which 

cas it will return the first found solution with width `\leq k` is 

``certificate==True``. 

  

- ``exponential`` -- Use an exponential time and space algorithm. This 

algorithm only works of graphs on less than 32 vertices. 

  

- ``MILP`` -- Use a mixed integer linear programming formulation. This 

algorithm has no size restriction but could take a very long time. 

  

- ``verbose`` (boolean) -- whether to display information on the 

computations. 

  

- ``max_prefix_length`` -- (default: 20) limits the length of the stored 

prefixes to prevent storing too many prefixes. This parameter is used only 

when ``algorithm=="BAB"``. 

  

- ``max_prefix_number`` -- (default: 10**6) upper bound on the number of 

stored prefixes used to prevent using too much memory. This parameter is 

used only when ``algorithm=="BAB"``. 

  

OUTPUT: 

  

Return the pathwidth of ``self``. When ``k`` is specified, it returns 

``False`` when no path-decomposition of width `\leq k` exists or ``True`` 

otherwise. When ``certificate=True``, the path-decomposition is also 

returned. 

  

.. SEEALSO:: 

  

* :meth:`Graph.treewidth` -- computes the treewidth of a graph 

* :meth:`~sage.graphs.graph_decompositions.vertex_separation.vertex_separation` 

-- computes the vertex separation of a (di)graph 

  

EXAMPLES: 

  

The pathwidth of a cycle is equal to 2:: 

  

sage: g = graphs.CycleGraph(6) 

sage: g.pathwidth() 

2 

sage: pw, decomp = g.pathwidth(certificate=True) 

sage: decomp.vertices() 

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

  

The pathwidth of a Petersen graph is 5:: 

  

sage: g = graphs.PetersenGraph() 

sage: g.pathwidth() 

5 

sage: g.pathwidth(k=2) 

False 

sage: g.pathwidth(k=6) 

True 

sage: g.pathwidth(k=6, certificate=True) 

(True, Graph on 5 vertices) 

  

TESTS: 

  

Given anything else than a Graph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import pathwidth 

sage: pathwidth(DiGraph()) 

Traceback (most recent call last): 

... 

ValueError: the parameter must be a Graph 

  

Given a wrong algorithm:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import pathwidth 

sage: pathwidth(Graph(), algorithm="SuperFast") 

Traceback (most recent call last): 

... 

ValueError: Algorithm "SuperFast" has not been implemented yet. Please contribute. 

""" 

from sage.graphs.graph import Graph 

if not isinstance(self, Graph): 

raise ValueError("the parameter must be a Graph") 

  

pw, L = vertex_separation(self, algorithm=algorithm, verbose=verbose, 

cut_off=k, upper_bound=None if k is None else (k+1), 

max_prefix_length=max_prefix_length, 

max_prefix_number=max_prefix_number) 

  

if k is None: 

return (pw, linear_ordering_to_path_decomposition(self, L)) if certificate else pw 

if pw < 0: 

# no solution found 

return (False, Graph()) if certificate else False 

return (pw <= k, linear_ordering_to_path_decomposition(self, L)) if certificate else pw <= k 

  

  

def path_decomposition(G, algorithm = "BAB", cut_off=None, upper_bound=None, verbose = False, 

max_prefix_length=20, max_prefix_number=10**6): 

r""" 

Returns the pathwidth of the given graph and the ordering of the vertices 

resulting in a corresponding path decomposition. 

  

INPUT: 

  

- ``G`` -- a Graph 

  

- ``algorithm`` -- (default: ``"BAB"``) Specify the algorithm to use among 

  

- ``"BAB"`` -- Use a branch-and-bound algorithm. This algorithm has no 

size restriction but could take a very long time on large graphs. It can 

also be used to test is the input (di)graph has vertex separation at 

most ``upper_bound`` or to return the first found solution with vertex 

separation less or equal to a ``cut_off`` value. 

  

- ``exponential`` -- Use an exponential time and space algorithm. This 

algorithm only works of graphs on less than 32 vertices. 

  

- ``MILP`` -- Use a mixed integer linear programming formulation. This 

algorithm has no size restriction but could take a very long time. 

  

- ``upper_bound`` -- (default: ``None``) This is parameter is used by the 

``"BAB"`` algorithm. If specified, the algorithm searches for a solution 

with ``width < upper_bound``. It helps cutting branches. However, if the 

given upper bound is too low, the algorithm may not be able to find a 

solution. 

  

- ``cut_off`` -- (default: None) This is parameter is used by the ``"BAB"`` 

algorithm. This bound allows us to stop the search as soon as a solution 

with width at most ``cut_off`` is found, if any. If this bound cannot be 

reached, the best solution found is returned, unless a too low 

``upper_bound`` is given. 

  

- ``verbose`` (boolean) -- whether to display information on the 

computations. 

  

- ``max_prefix_length`` -- (default: 20) limits the length of the stored 

prefixes to prevent storing too many prefixes. This parameter is used only 

when ``algorithm=="BAB"``. 

  

- ``max_prefix_number`` -- (default: 10**6) upper bound on the number of 

stored prefixes used to prevent using too much memory. This parameter is 

used only when ``algorithm=="BAB"``. 

  

OUTPUT: 

  

A pair ``(cost, ordering)`` representing the optimal ordering of the 

vertices and its cost. 

  

.. SEEALSO:: 

  

* :meth:`Graph.treewidth` -- computes the treewidth of a graph 

  

EXAMPLES: 

  

The pathwidth of a cycle is equal to 2:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import path_decomposition 

sage: g = graphs.CycleGraph(6) 

sage: pw, L = path_decomposition(g, algorithm = "BAB"); pw 

2 

sage: pw, L = path_decomposition(g, algorithm = "exponential"); pw 

2 

sage: pw, L = path_decomposition(g, algorithm = "MILP"); pw 

2 

  

TESTS: 

  

Given anything else than a Graph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import path_decomposition 

sage: path_decomposition(DiGraph()) 

Traceback (most recent call last): 

... 

ValueError: The parameter must be a Graph. 

  

Given a wrong algorithm:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import path_decomposition 

sage: path_decomposition(Graph(), algorithm="SuperFast") 

Traceback (most recent call last): 

... 

ValueError: Algorithm "SuperFast" has not been implemented yet. Please contribute. 

  

""" 

from sage.graphs.graph import Graph 

if not isinstance(G, Graph): 

raise ValueError("The parameter must be a Graph.") 

  

return vertex_separation(G, algorithm=algorithm, cut_off=cut_off, upper_bound=upper_bound, 

verbose=verbose, max_prefix_length=max_prefix_length, 

max_prefix_number=max_prefix_number) 

  

  

def vertex_separation(G, algorithm = "BAB", cut_off=None, upper_bound=None, verbose = False, 

max_prefix_length=20, max_prefix_number=10**6): 

r""" 

Returns an optimal ordering of the vertices and its cost for 

vertex-separation. 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph 

  

- ``algorithm`` -- (default: ``"BAB"``) Specify the algorithm to use among 

  

- ``"BAB"`` -- Use a branch-and-bound algorithm. This algorithm has no 

size restriction but could take a very long time on large graphs. It can 

also be used to test is the input (di)graph has vertex separation at 

most ``upper_bound`` or to return the first found solution with vertex 

separation less or equal to a ``cut_off`` value. 

  

- ``exponential`` -- Use an exponential time and space algorithm. This 

algorithm only works of graphs on less than 32 vertices. 

  

- ``MILP`` -- Use a mixed integer linear programming formulation. This 

algorithm has no size restriction but could take a very long time. 

  

- ``upper_bound`` -- (default: ``None``) This is parameter is used by the 

``"BAB"`` algorithm. If specified, the algorithm searches for a solution 

with ``width < upper_bound``. It helps cutting branches. However, if the 

given upper bound is too low, the algorithm may not be able to find a 

solution. 

  

- ``cut_off`` -- (default: None) This is parameter is used by the ``"BAB"`` 

algorithm. This bound allows us to stop the search as soon as a solution 

with width at most ``cut_off`` is found, if any. If this bound cannot be 

reached, the best solution found is returned, unless a too low 

``upper_bound`` is given. 

  

- ``verbose`` (boolean) -- whether to display information on the 

computations. 

  

- ``max_prefix_length`` -- (default: 20) limits the length of the stored 

prefixes to prevent storing too many prefixes. This parameter is used only 

when ``algorithm=="BAB"``. 

  

- ``max_prefix_number`` -- (default: 10**6) upper bound on the number of 

stored prefixes used to prevent using too much memory. This parameter is 

used only when ``algorithm=="BAB"``. 

  

OUTPUT: 

  

A pair ``(cost, ordering)`` representing the optimal ordering of the 

vertices and its cost. 

  

EXAMPLES: 

  

Comparison of methods:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation 

sage: G = digraphs.DeBruijn(2,3) 

sage: vs,L = vertex_separation(G, algorithm="BAB"); vs 

2 

sage: vs,L = vertex_separation(G, algorithm="exponential"); vs 

2 

sage: vs,L = vertex_separation(G, algorithm="MILP"); vs 

2 

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

sage: vs,L = vertex_separation(G, algorithm="BAB"); vs 

3 

sage: vs,L = vertex_separation(G, algorithm="exponential"); vs 

3 

sage: vs,L = vertex_separation(G, algorithm="MILP"); vs 

3 

  

Digraphs with multiple strongly connected components:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation 

sage: D = digraphs.Path(8) 

sage: print(vertex_separation(D)) 

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

sage: D = DiGraph( random_DAG(30) ) 

sage: vs,L = vertex_separation(D); vs 

0 

sage: K4 = DiGraph( graphs.CompleteGraph(4) ) 

sage: D = K4+K4 

sage: D.add_edge(0, 4) 

sage: print(vertex_separation(D)) 

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

sage: D = K4+K4+K4 

sage: D.add_edge(0, 4) 

sage: D.add_edge(0, 8) 

sage: print(vertex_separation(D)) 

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

  

TESTS: 

  

Given a wrong algorithm:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation 

sage: vertex_separation(Graph(), algorithm="SuperFast") 

Traceback (most recent call last): 

... 

ValueError: Algorithm "SuperFast" has not been implemented yet. Please contribute. 

  

Given anything else than a Graph or a DiGraph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation 

sage: vertex_separation(range(4)) 

Traceback (most recent call last): 

... 

ValueError: The parameter must be a Graph or a DiGraph. 

""" 

from sage.graphs.graph import Graph 

from sage.graphs.digraph import DiGraph 

  

CC = [] 

if isinstance(G, Graph): 

if not G.is_connected(): 

# We decompose the graph into connected components. 

CC = G.connected_components() 

  

elif isinstance(G, DiGraph): 

if not G.is_strongly_connected(): 

# We decompose the digraph into strongly connected components and 

# arrange them in the inverse order of the topological sort of the 

# digraph of the strongly connected components. 

scc_digraph = G.strongly_connected_components_digraph() 

CC = scc_digraph.topological_sort()[::-1] 

  

else: 

raise ValueError('The parameter must be a Graph or a DiGraph.') 

  

  

if CC: 

# The graph has several (strongly) connected components. We solve the 

# problem on each of them and order partial solutions in the same order 

# than in list CC. The vertex separation is the maximum over all these 

# subgraphs. 

vs, L = 0, [] 

for V in CC: 

  

if len(V)==1: 

# We can directly add this vertex to the solution 

L.extend(V) 

  

else: 

# We build the (strongly) connected subgraph and do a recursive 

# call to get its vertex separation and corresponding ordering 

H = G.subgraph(V) 

vsH,LH = vertex_separation(H, algorithm = algorithm, 

cut_off = cut_off, 

upper_bound = upper_bound, 

verbose = verbose, 

max_prefix_length = max_prefix_length, 

max_prefix_number = max_prefix_number) 

  

if vsH==-1: 

# We have not been able to find a solution. This case 

# happens when a too low upper bound is given. 

return -1, [] 

  

# We update the vertex separation and ordering 

vs = max(vs, vsH) 

L.extend(LH) 

  

# We also update the cut_off parameter that could speed up 

# resolution for other components (used when algorithm=="BAB") 

cut_off = max(cut_off, vs) 

  

return vs, L 

  

  

# We have a (strongly) connected graph and we call the desired algorithm 

if algorithm == "exponential": 

return vertex_separation_exp(G, verbose = verbose) 

  

elif algorithm == "MILP": 

return vertex_separation_MILP(G, verbosity = (1 if verbose else 0)) 

  

elif algorithm == "BAB": 

return vertex_separation_BAB(G, cut_off=cut_off, upper_bound=upper_bound, verbose=verbose, 

max_prefix_length=max_prefix_length, max_prefix_number = max_prefix_number) 

  

else: 

raise ValueError('Algorithm "{}" has not been implemented yet. Please contribute.'.format(algorithm)) 

  

  

################################ 

# Exact exponential algorithms # 

################################ 

  

def vertex_separation_exp(G, verbose = False): 

r""" 

Returns an optimal ordering of the vertices and its cost for 

vertex-separation. 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph. 

  

- ``verbose`` (boolean) -- whether to display information on the 

computations. 

  

OUTPUT: 

  

A pair ``(cost, ordering)`` representing the optimal ordering of the 

vertices and its cost. 

  

.. NOTE:: 

  

Because of its current implementation, this algorithm only works on 

graphs on less than 32 vertices. This can be changed to 54 if necessary, 

but 32 vertices already require 4GB of memory. 

  

EXAMPLES: 

  

The vertex separation of a circuit is equal to 1:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation_exp 

sage: g = digraphs.Circuit(6) 

sage: vertex_separation_exp(g) 

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

  

TESTS: 

  

Given anything else than a Graph or a DiGraph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation_exp 

sage: vertex_separation_exp(range(3)) 

Traceback (most recent call last): 

... 

ValueError: The parameter must be a Graph or a DiGraph. 

  

Graphs with non-integer vertices:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation_exp 

sage: D=digraphs.DeBruijn(2,3) 

sage: vertex_separation_exp(D) 

(2, ['000', '001', '100', '010', '101', '011', '110', '111']) 

  

Given a too large graph:: 

  

sage: from sage.graphs.graph_decompositions.vertex_separation import vertex_separation_exp 

sage: vertex_separation_exp(graphs.PathGraph(50)) 

Traceback (most recent call last): 

... 

ValueError: The graph should have at most 31 vertices ! 

""" 

from sage.graphs.graph import Graph 

from sage.graphs.digraph import DiGraph 

if not isinstance(G, Graph) and not isinstance(G, DiGraph): 

raise ValueError("The parameter must be a Graph or a DiGraph.") 

  

if G.order() >= 32: 

raise ValueError("The graph should have at most 31 vertices !") 

  

cdef FastDigraph g = FastDigraph(G) 

  

if verbose: 

print("Memory allocation") 

g.print_adjacency_matrix() 

  

cdef unsigned int mem = 1 << g.n 

cdef uint8_t * neighborhoods = <uint8_t *>check_malloc(mem) 

  

memset(neighborhoods, <uint8_t> -1, mem) 

  

cdef int i,j , k 

for k in xrange(g.n): 

if verbose: 

print("Looking for a strategy of cost", str(k)) 

  

sig_check() 

if exists(g, neighborhoods, 0, k) <= k: 

break 

  

if verbose: 

print("... Found !") 

print("Now computing the ordering") 

  

cdef list order = find_order(g, neighborhoods, k) 

  

sig_free(neighborhoods) 

  

return k, list( g.int_to_vertices[i] for i in order ) 

  

############################################################################## 

# Actual algorithm, breadh-first search and updates of the costs of the sets # 

############################################################################## 

  

# Check whether an ordering with the given cost exists, and updates data in the 

# neighborhoods array at the same time. See the module's documentation 

  

cdef inline int exists(FastDigraph g, uint8_t * neighborhoods, int current, int cost): 

  

# If this is true, it means the set has not been evaluated yet 

if neighborhoods[current] == <uint8_t>-1: 

neighborhoods[current] = compute_out_neighborhood_cardinality(g, current) 

  

# If the cost of this set is too high, there is no point in going further. 

# Same thing if the current set is the whole vertex set. 

if neighborhoods[current] > cost or (current == (1<<g.n)-1): 

return neighborhoods[current] 

  

# Minimum of the costs of the outneighbors 

cdef int mini = g.n 

  

cdef int i 

cdef int next_set 

  

  

for i in xrange(g.n): 

if (current >> i)&1: 

continue 

  

# For each of the out-neighbors next_set of current 

next_set = current | 1<<i 

  

# Check whether there exists a cheap path toward {1..n}, and updated the 

# cost. 

mini = minimum(mini, exists(g, neighborhoods, next_set, cost)) 

  

# We have found a path ! 

if mini <= cost: 

return mini 

  

# Updating the cost of the current set with the minimum of the cost of its 

# outneighbors. 

neighborhoods[current] = mini 

  

return neighborhoods[current] 

  

# Returns the ordering once we are sure it exists 

cdef list find_order(FastDigraph g, uint8_t * neighborhoods, int cost): 

cdef list ordering = [] 

cdef int current = 0 

cdef int n = g.n 

cdef int i 

  

while n: 

# We look for n vertices 

  

for i in xrange(g.n): 

if (current >> i)&1: 

continue 

  

# Find the next set with small cost (we know it exists) 

next_set = current | 1<<i 

if neighborhoods[next_set] <= cost: 

ordering.append(i) 

current = next_set 

break 

  

# One less to find 

n -= 1 

  

return ordering 

  

# Min/Max functions 

  

cdef inline int minimum(int a, int b): 

if a<b: 

return a 

else: 

return b 

  

cdef inline int maximum(int a, int b): 

if a>b: 

return a 

else: 

return b 

  

  

################################################################# 

# Function for testing the validity of a linear vertex ordering # 

################################################################# 

  

def is_valid_ordering(G, L): 

r""" 

Test if the linear vertex ordering `L` is valid for (di)graph `G`. 

  

A linear ordering `L` of the vertices of a (di)graph `G` is valid if all 

vertices of `G` are in `L`, and if `L` contains no other vertex and no 

duplicated vertices. 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph. 

  

- ``L`` -- an ordered list of the vertices of ``G``. 

  

  

OUTPUT: 

  

Returns ``True`` if `L` is a valid vertex ordering for `G`, and ``False`` 

otherwise. 

  

  

EXAMPLES: 

  

Path decomposition of a cycle:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = graphs.CycleGraph(6) 

sage: L = [u for u in G.vertices()] 

sage: vertex_separation.is_valid_ordering(G, L) 

True 

sage: vertex_separation.is_valid_ordering(G, [1,2]) 

False 

  

TESTS: 

  

Giving anything else than a Graph or a DiGraph:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: vertex_separation.is_valid_ordering(2, []) 

Traceback (most recent call last): 

... 

ValueError: The input parameter must be a Graph or a DiGraph. 

  

Giving anything else than a list:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = graphs.CycleGraph(6) 

sage: vertex_separation.is_valid_ordering(G, {}) 

Traceback (most recent call last): 

... 

ValueError: The second parameter must be of type 'list'. 

""" 

from sage.graphs.graph import Graph 

from sage.graphs.digraph import DiGraph 

if not isinstance(G, Graph) and not isinstance(G, DiGraph): 

raise ValueError("The input parameter must be a Graph or a DiGraph.") 

if not isinstance(L, list): 

raise ValueError("The second parameter must be of type 'list'.") 

  

return set(L) == set(G.vertices()) 

  

  

#################################################################### 

# Measurement functions of the widths of some graph decompositions # 

#################################################################### 

  

def width_of_path_decomposition(G, L): 

r""" 

Returns the width of the path decomposition induced by the linear ordering 

`L` of the vertices of `G`. 

  

If `G` is an instance of :mod:`Graph <sage.graphs.graph>`, this function 

returns the width `pw_L(G)` of the path decomposition induced by the linear 

ordering `L` of the vertices of `G`. If `G` is a :mod:`DiGraph 

<sage.graphs.digraph>`, it returns instead the width `vs_L(G)` of the 

directed path decomposition induced by the linear ordering `L` of the 

vertices of `G`, where 

  

.. MATH:: 

  

vs_L(G) & = \max_{0\leq i< |V|-1} | N^+(L[:i])\setminus L[:i] |\\ 

pw_L(G) & = \max_{0\leq i< |V|-1} | N(L[:i])\setminus L[:i] |\\ 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph 

  

- ``L`` -- a linear ordering of the vertices of ``G`` 

  

EXAMPLES: 

  

Path decomposition of a cycle:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = graphs.CycleGraph(6) 

sage: L = [u for u in G.vertices()] 

sage: vertex_separation.width_of_path_decomposition(G, L) 

2 

  

Directed path decomposition of a circuit:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = digraphs.Circuit(6) 

sage: L = [u for u in G.vertices()] 

sage: vertex_separation.width_of_path_decomposition(G, L) 

1 

  

TESTS: 

  

Path decomposition of a BalancedTree:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = graphs.BalancedTree(3,2) 

sage: pw, L = vertex_separation.path_decomposition(G) 

sage: pw == vertex_separation.width_of_path_decomposition(G, L) 

True 

sage: L.reverse() 

sage: pw == vertex_separation.width_of_path_decomposition(G, L) 

False 

  

Directed path decomposition of a circuit:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = digraphs.Circuit(8) 

sage: vs, L = vertex_separation.vertex_separation(G) 

sage: vs == vertex_separation.width_of_path_decomposition(G, L) 

True 

sage: L = [0,4,6,3,1,5,2,7] 

sage: vs == vertex_separation.width_of_path_decomposition(G, L) 

False 

  

Giving a wrong linear ordering:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = Graph() 

sage: vertex_separation.width_of_path_decomposition(G, ['a','b']) 

Traceback (most recent call last): 

... 

ValueError: The input linear vertex ordering L is not valid for G. 

""" 

if not is_valid_ordering(G, L): 

raise ValueError("The input linear vertex ordering L is not valid for G.") 

  

neighbors = G.neighbors_out if G.is_directed() else G.neighbors 

  

vsL = 0 

S = set() 

neighbors_of_S_in_V_minus_S = set() 

  

for u in L: 

  

# We remove u from the neighbors of S 

neighbors_of_S_in_V_minus_S.discard(u) 

  

# We add vertex u to the set S 

S.add(u) 

  

# We add the (out-)neighbors of u to the neighbors of S 

for v in neighbors(u): 

if (not v in S): 

neighbors_of_S_in_V_minus_S.add(v) 

  

# We update the cost of the vertex separation 

vsL = max( vsL, len(neighbors_of_S_in_V_minus_S) ) 

  

return vsL 

  

  

########################################## 

# MILP formulation for vertex separation # 

########################################## 

  

def vertex_separation_MILP(G, integrality = False, solver = None, verbosity = 0): 

r""" 

Computes the vertex separation of `G` and the optimal ordering of its 

vertices using an MILP formulation. 

  

This function uses a mixed integer linear program (MILP) for determining an 

optimal layout for the vertex separation of `G`. This MILP is an improved 

version of the formulation proposed in [SP10]_. See the :mod:`module's 

documentation <sage.graphs.graph_decompositions.vertex_separation>` for more 

details on this MILP formulation. 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph 

  

- ``integrality`` -- (default: ``False``) Specify if variables `x_v^t` and 

`u_v^t` must be integral or if they can be relaxed. This has no impact on 

the validity of the solution, but it is sometimes faster to solve the 

problem using binary variables only. 

  

- ``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 pair ``(cost, ordering)`` representing the optimal ordering of the 

vertices and its cost. 

  

EXAMPLES: 

  

Vertex separation of a De Bruijn digraph:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = digraphs.DeBruijn(2,3) 

sage: vs, L = vertex_separation.vertex_separation_MILP(G); vs 

2 

sage: vs == vertex_separation.width_of_path_decomposition(G, L) 

True 

sage: vse, Le = vertex_separation.vertex_separation(G); vse 

2 

  

The vertex separation of a circuit is 1:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: G = digraphs.Circuit(6) 

sage: vs, L = vertex_separation.vertex_separation_MILP(G); vs 

1 

  

TESTS: 

  

Comparison with exponential algorithm:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: for i in range(10): 

....: G = digraphs.RandomDirectedGNP(10, 0.2) 

....: ve, le = vertex_separation.vertex_separation(G) 

....: vm, lm = vertex_separation.vertex_separation_MILP(G) 

....: if ve != vm: 

....: print("The solution is not optimal!") 

  

Comparison with different values of the integrality parameter:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: for i in range(10): # long time (11s on sage.math, 2012) 

....: G = digraphs.RandomDirectedGNP(10, 0.2) 

....: va, la = vertex_separation.vertex_separation_MILP(G, integrality=False) 

....: vb, lb = vertex_separation.vertex_separation_MILP(G, integrality=True) 

....: if va != vb: 

....: print("The integrality parameter changes the result!") 

  

Giving anything else than a Graph or a DiGraph:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation 

sage: vertex_separation.vertex_separation_MILP([]) 

Traceback (most recent call last): 

... 

ValueError: The first input parameter must be a Graph or a DiGraph. 

""" 

from sage.graphs.graph import Graph 

from sage.graphs.digraph import DiGraph 

if not isinstance(G, Graph) and not isinstance(G, DiGraph): 

raise ValueError("The first input parameter must be a Graph or a DiGraph.") 

  

from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException 

p = MixedIntegerLinearProgram( maximization = False, solver = solver ) 

  

# Declaration of variables. 

x = p.new_variable(binary=integrality, nonnegative=True) 

u = p.new_variable(binary=integrality, nonnegative=True) 

y = p.new_variable(binary=True) 

z = p.new_variable(integer=True, nonnegative=True) 

  

N = G.num_verts() 

V = G.vertices() 

neighbors_out = G.neighbors_out if G.is_directed() else G.neighbors 

  

# (2) x[v,t] <= x[v,t+1] for all v in V, and for t:=0..N-2 

# (3) y[v,t] <= y[v,t+1] for all v in V, and for t:=0..N-2 

for v in V: 

for t in xrange(N - 1): 

p.add_constraint( x[v,t] - x[v,t+1] <= 0 ) 

p.add_constraint( y[v,t] - y[v,t+1] <= 0 ) 

  

# (4) y[v,t] <= x[w,t] for all v in V, for all w in N^+(v), and for all t:=0..N-1 

for v in V: 

for w in neighbors_out(v): 

for t in xrange(N): 

p.add_constraint( y[v,t] - x[w,t] <= 0 ) 

  

# (5) sum_{v in V} y[v,t] == t+1 for t:=0..N-1 

for t in xrange(N): 

p.add_constraint( p.sum([ y[v,t] for v in V ]) == t+1 ) 

  

# (6) u[v,t] >= x[v,t]-y[v,t] for all v in V, and for all t:=0..N-1 

for v in V: 

for t in xrange(N): 

p.add_constraint( x[v,t] - y[v,t] - u[v,t] <= 0 ) 

  

# (7) z >= sum_{v in V} u[v,t] for all t:=0..N-1 

for t in xrange(N): 

p.add_constraint( p.sum([ u[v,t] for v in V ]) - z['z'] <= 0 ) 

  

# (8)(9) 0 <= x[v,t] and u[v,t] <= 1 

if not integrality: 

for v in V: 

for t in xrange(N): 

p.add_constraint( 0 <= x[v,t] <= 1 ) 

p.add_constraint( 0 <= u[v,t] <= 1 ) 

  

# (10) y[v,t] in {0,1} 

p.set_binary( y ) 

  

# (11) 0 <= z <= |V| 

p.add_constraint( z['z'] <= N ) 

  

# (1) Minimize z 

p.set_objective( z['z'] ) 

  

try: 

obj = p.solve( log=verbosity ) 

except MIPSolverException: 

if integrality: 

raise ValueError("Unbounded or unexpected error") 

else: 

raise ValueError("Unbounded or unexpected error. Try with 'integrality = True'.") 

  

taby = p.get_values( y ) 

tabz = p.get_values( z ) 

# since exactly one vertex is processed per step, we can reconstruct the sequence 

seq = [] 

for t in xrange(N): 

for v in V: 

if (taby[v,t] > 0) and (not v in seq): 

seq.append(v) 

break 

vs = int(round( tabz['z'] )) 

  

return vs, seq 

  

########################################## 

# Branch and Bound for vertex separation # 

########################################## 

  

def vertex_separation_BAB(G, 

cut_off = None, 

upper_bound = None, 

max_prefix_length = 20, 

max_prefix_number = 10**6, 

verbose = False): 

r""" 

Branch and Bound algorithm for the vertex separation. 

  

This method implements the branch and bound algorithm for the vertex 

separation of directed graphs and the pathwidth of undirected graphs 

proposed in [CMN14]_. The implementation is valid for both Graph and 

DiGraph. See the documentation of the 

:mod:`~sage.graphs.graph_decompositions.vertex_separation` module. 

  

INPUT: 

  

- ``G`` -- a Graph or a DiGraph. 

  

- ``cut_off`` -- (default: None) bound to consider in the branch and bound 

algorithm. This allows us to stop the search as soon as a solution with 

width at most ``cut_off`` is found, if any. If this bound cannot be 

reached, the best solution found is returned, unless a too low 

``upper_bound`` is given. 

  

- ``upper_bound`` -- (default: None) if specified, the algorithm searches 

for a solution with ``width < upper_bound``. It helps cutting branches. 

However, if the given upper bound is too low, the algorithm may not be 

able to find a solution. 

  

- ``max_prefix_length`` -- (default: 20) limits the length of the stored 

prefixes to prevent storing too many prefixes. 

  

- ``max_prefix_number`` -- (default: 10**6) upper bound on the number of 

stored prefixes used to prevent using too much memory. 

  

- ``verbose`` -- (default: False) display some information when set to True. 

  

OUTPUT: 

  

- ``width`` -- the computed vertex separation 

  

- ``seq`` -- an ordering of the vertices of width ``width``. 

  

  

EXAMPLES: 

  

The algorithm is valid for the vertex separation:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: D = digraphs.RandomDirectedGNP(15, .2) 

sage: vb, seqb = VS.vertex_separation_BAB(D) 

sage: vd, seqd = VS.vertex_separation_exp(D) 

sage: vb == vd 

True 

sage: vb == VS.width_of_path_decomposition(D, seqb) 

True 

  

The vertex separation of a `N\times N` grid is `N`:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

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

sage: vs, seq = VS.vertex_separation_BAB(G); vs 

4 

sage: vs == VS.width_of_path_decomposition(G, seq) 

True 

  

The vertex separation of a `N\times M` grid with `N<M` is `N`:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

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

sage: vs, seq = VS.vertex_separation_BAB(G); vs 

3 

sage: vs == VS.width_of_path_decomposition(G, seq) 

True 

  

The vertex separation of circuit of order `N\geq 2` is 1:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: D = digraphs.Circuit(10) 

sage: vs, seq = VS.vertex_separation_BAB(D); vs 

1 

sage: vs == VS.width_of_path_decomposition(D, seq) 

True 

  

The vertex separation of cycle of order `N\geq 3` is 2:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: G = graphs.CycleGraph(10) 

sage: vs, seq = VS.vertex_separation_BAB(G); vs 

2 

  

The vertex separation of ``MycielskiGraph(5)`` is 10:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: G = graphs.MycielskiGraph(5) 

sage: vs, seq = VS.vertex_separation_BAB(G); vs 

10 

  

Searching for any solution with width less or equal to ``cut_off``:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: G = graphs.MycielskiGraph(5) 

sage: vs, seq = VS.vertex_separation_BAB(G, cut_off=11); vs 

11 

sage: vs, seq = VS.vertex_separation_BAB(G, cut_off=10); vs 

10 

sage: vs, seq = VS.vertex_separation_BAB(G, cut_off=9); vs 

10 

  

Testing for the existence of a solution with width strictly less than ``upper_bound``:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: G = graphs.MycielskiGraph(5) 

sage: vs, seq = VS.vertex_separation_BAB(G, upper_bound=11); vs 

10 

sage: vs, seq = VS.vertex_separation_BAB(G, upper_bound=10); vs 

-1 

sage: vs, seq = VS.vertex_separation_BAB(G, cut_off=11, upper_bound=10); vs 

-1 

  

Changing the parameters of the prefix storage:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: G = graphs.MycielskiGraph(5) 

sage: vs, seq = VS.vertex_separation_BAB(G, max_prefix_length=0); vs 

10 

sage: vs, seq = VS.vertex_separation_BAB(G, max_prefix_number=5); vs 

10 

sage: vs, seq = VS.vertex_separation_BAB(G, max_prefix_number=0); vs 

10 

  

TESTS: 

  

Giving anything else than a Graph or a DiGraph:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: VS.vertex_separation_BAB(range(5)) 

Traceback (most recent call last): 

... 

ValueError: The input parameter must be a Graph or a DiGraph. 

  

Giving an empty Graph or DiGraph:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: VS.vertex_separation_BAB(Graph()) 

(0, []) 

sage: VS.vertex_separation_BAB(DiGraph()) 

(0, []) 

  

Giving a too low upper bound:: 

  

sage: from sage.graphs.graph_decompositions import vertex_separation as VS 

sage: VS.vertex_separation_BAB(digraphs.Circuit(3), upper_bound=0) 

Traceback (most recent call last): 

... 

ValueError: The input upper bound must be at least 1. 

""" 

from sage.graphs.graph import Graph 

from sage.graphs.digraph import DiGraph 

if not isinstance(G, DiGraph) and not isinstance(G, Graph): 

raise ValueError("The input parameter must be a Graph or a DiGraph.") 

  

cdef int n = G.order() 

if n==0: 

return 0, [] 

  

cut_off = 0 if cut_off is None else cut_off 

upper_bound = n if upper_bound is None else upper_bound 

if upper_bound < 1: 

raise ValueError("The input upper bound must be at least 1.") 

  

# ==> Allocate and initialize some data structures 

  

# We use a binary matrix to store the (di)graph. This way the neighborhoud 

# of a vertex is stored in one bitset. 

cdef binary_matrix_t H 

cdef dict vertex_to_int = dense_graph_init(H, G, translation = True) 

cdef int i 

cdef dict int_to_vertex = dict((i, v) for v,i in vertex_to_int.iteritems()) 

  

# We need 2 bitsets here + 3 per call to vertex_separation_BAB_C, so overall 

# 3*n + 2. We use another binary matrix as a pool of bitsets. 

cdef binary_matrix_t bm_pool 

binary_matrix_init(bm_pool, 3*n+2, n) 

  

cdef int * prefix = <int *>sig_malloc(n * sizeof(int)) 

cdef int * positions = <int *>sig_malloc(n * sizeof(int)) 

if prefix==NULL or positions==NULL: 

sig_free(prefix) 

sig_free(positions) 

binary_matrix_free(H) 

binary_matrix_free(bm_pool) 

raise MemoryError("Unable to allocate data strutures.") 

  

cdef list best_seq = list(range(n)) 

for i in xrange(n): 

prefix[i] = i 

positions[i] = i 

  

cdef int width = upper_bound 

cdef list order = list() 

cdef set prefix_storage = set() 

  

try: 

# ==> Call the cython method 

sig_on() 

width = vertex_separation_BAB_C(H = H, 

n = n, 

prefix = prefix, 

positions = positions, 

best_seq = best_seq, 

level = 0, 

b_prefix = bm_pool.rows[3*n], 

b_prefix_and_neighborhood = bm_pool.rows[3*n+1], 

cut_off = cut_off, 

upper_bound = upper_bound, 

current_cost = 0, 

bm_pool = bm_pool, 

prefix_storage = prefix_storage, 

max_prefix_length = max_prefix_length, 

max_prefix_number = max_prefix_number, 

verbose = verbose) 

  

sig_off() 

  

# ==> Build the final ordering 

order = [int_to_vertex[best_seq[i]] for i in xrange(n)] 

  

finally: 

if verbose: 

print('Stored prefixes: {}'.format(len(prefix_storage))) 

sig_free(prefix) 

sig_free(positions) 

binary_matrix_free(H) 

binary_matrix_free(bm_pool) 

  

return (width if width<upper_bound else -1), order 

  

cdef inline _my_invert_positions(int *prefix, int *positions, int pos_a, int pos_b): 

""" 

Permute vertices at positions ``pos_a`` and ``pos_b`` in array ``prefix``, 

and record the new positions in array ``positions``. 

""" 

if pos_a!=pos_b: 

positions[prefix[pos_a]],positions[prefix[pos_b]] = positions[prefix[pos_b]],positions[prefix[pos_a]] 

prefix[pos_a], prefix[pos_b] = prefix[pos_b], prefix[pos_a] 

  

  

cdef int vertex_separation_BAB_C(binary_matrix_t H, 

int n, 

int * prefix, 

int * positions, 

list best_seq, 

int level, 

bitset_t b_prefix, 

bitset_t b_prefix_and_neighborhood, 

int cut_off, 

int upper_bound, 

int current_cost, 

binary_matrix_t bm_pool, 

set prefix_storage, 

int max_prefix_length, 

int max_prefix_number, 

bint verbose): 

r""" 

Branch and Bound algorithm for the process number and the vertex separation. 

  

INPUT: 

  

- ``H`` -- a binary matrix storing the adjacency of the (di)graph 

  

- ``n`` -- the number of vertices of the (di)graph 

  

- ``prefix`` -- array of ``n`` integers containing a permutation of the 

vertices. The vertices forming the current prefix under consideration are 

stored in cells ``[0,level-1]``. 

  

- ``positions`` -- array of ``n`` integers associating to each vertex its 

index in array ``prefix``. 

  

- ``best_seq`` -- array of ``n`` integers storing the best ordering found so 

far. 

  

- ``level`` -- an integer specifying the length of the current prefix. 

  

- ``b_prefix`` -- a bitset of size ``n`` recording the vertices in the 

current prefix (in cells ``[0,level-1]``). 

  

- ``b_prefix_and_neighborhood`` -- a bitset of size ``n`` recording the 

vertices in the current prefix and the vertices in its neighborhood. 

  

- ``cut_off`` -- (default: None) bound to consider in the branch and bound 

algorithm. This allows us to stop the search as soon as a solution with 

width at most ``cut_off`` is found, if any. 

  

- ``upper_bound`` -- the algorithm searches for a solution with ``width < 

upper_bound``. It helps cutting branches. Each time a new solution is 

found, the upper bound is reduced. 

  

- ``bm_pool`` -- a binary matrix used with ``3*n+2`` rows of size 

``n``. Each rows is a bitset of size ``n``. This data structure is used as 

a pool of initialized bitsets. Each call of this method needs 3 bitsets 

for local operations, so it uses rows ``[3*level,3*level+2]``. 

  

- ``prefix_storage`` -- set used to store prefixes. 

  

- ``max_prefix_length`` -- maximum length of the stored prefixes to prevent 

storing too many prefixes. 

  

- ``max_prefix_number`` -- upper bound on the number of stored prefixes used 

to prevent using too much memory. 

  

- ``verbose`` -- (default: False) display some information when set to True. 

""" 

cdef int i 

  

# ==> Test termination 

  

if level==n: 

if current_cost < upper_bound: 

for i in xrange(n): 

best_seq[i] = prefix[i] 

if verbose: 

print("New upper bound: {}".format(current_cost)) 

  

return current_cost 

  

  

cdef int delta_i, j, v, select_it 

cdef list delta = list() 

cdef int loc_level = level 

  

# ==> Allocate local data structures 

  

cdef bitset_s *loc_b_prefix = bm_pool.rows[3*level] 

cdef bitset_s *loc_b_pref_and_neigh = bm_pool.rows[3*level+1] 

cdef bitset_s *b_tmp = bm_pool.rows[3*level+2] 

bitset_copy(loc_b_prefix, b_prefix) 

bitset_copy(loc_b_pref_and_neigh, b_prefix_and_neighborhood) 

  

# ==> Greedy steps 

# 

# We extend the current prefix with all vertices u such that either 

# (i) All out-neighbors of u are in the prefix or in its out-neighborhood 

# (ii) or u is an out-neighbor of the prefix and all but one of its 

# out-neighbors are in the prefix or in its out-neighborhood. 

  

select_it = 0 

i = loc_level 

while i<n: 

  

j = prefix[i] 

  

if bitset_issubset(H.rows[j], loc_b_pref_and_neigh): 

# (i) Vertex j is such that all its out-neighbors are in the prefix 

# or in its out-neighborhood (so in loc_b_pref_and_neigh). 

bitset_add(loc_b_pref_and_neigh, j) 

select_it = 1 

  

elif bitset_in(loc_b_pref_and_neigh, j) and not bitset_in(loc_b_prefix, j): 

bitset_difference(b_tmp, H.rows[j], loc_b_pref_and_neigh) 

if bitset_len(b_tmp)==1: 

# (ii) Vertex j is an out-neighbor of the prefix and all but one 

# of its out-neighbors are in the prefix or in its 

# out-neighborhood. 

v = bitset_first(b_tmp) 

bitset_add(loc_b_pref_and_neigh, v) 

select_it = 1 

  

if select_it: 

# We add j to the prefix and update neighborhoods 

_my_invert_positions(prefix, positions, i, loc_level) 

loc_level += 1 

bitset_add(loc_b_prefix, j) 

select_it = 0 

# We search for vertices that can now be selected 

i = loc_level 

else: 

i += 1 

  

# ==> Test termination 

# 

if loc_level==n: 

if current_cost < upper_bound: 

for i in xrange(n): 

best_seq[i] = prefix[i] 

if verbose: 

print("New upper bound: {}".format(current_cost)) 

  

return current_cost 

  

  

# ==> Test if the prefix is in prefix_storage 

# 

# The set S of vertices of a prefix P is in prefix_storage if the branch 

# with prefix P is such that c(P)<\min_{L\in{\cal L}_P(V)} c(L). In such 

# case, there is no need to continue exploration for the current branch. 

cdef frozenset frozen_prefix 

  

if loc_level<=max_prefix_length: 

frozen_prefix = frozenset([prefix[i] for i in xrange(loc_level)]) 

if frozen_prefix in prefix_storage: 

return upper_bound 

  

  

# ==> Sort and Prune 

# 

# We compute for each remaining vertex v a lower bound on the width of any 

# ordering with prefix prefix+v 

for i from loc_level <= i < n: 

j = prefix[i] 

bitset_union(b_tmp, loc_b_pref_and_neigh, H.rows[j]) 

bitset_difference(b_tmp, b_tmp, loc_b_prefix) 

bitset_discard(b_tmp, j) 

delta_i = bitset_len(b_tmp) 

if delta_i < upper_bound: 

delta.append( (delta_i, j) ) 

  

delta.sort() 

  

  

# ==> Recursion 

for delta_i, i in delta: 

  

delta_i = max(current_cost, delta_i) 

  

if delta_i >= upper_bound: 

break 

  

# We extend the current prefix with vertex i and explore the branch 

bitset_union(b_tmp, loc_b_pref_and_neigh, H.rows[i]) 

bitset_discard(b_tmp, i) 

_my_invert_positions(prefix, positions, positions[i], loc_level) 

bitset_add(loc_b_prefix, i) 

  

cost_i = vertex_separation_BAB_C(H = H, 

n = n, 

prefix = prefix, 

positions = positions, 

best_seq = best_seq, 

level = loc_level+1, 

b_prefix = loc_b_prefix, 

b_prefix_and_neighborhood = b_tmp, 

cut_off = cut_off, 

upper_bound = upper_bound, 

current_cost = delta_i, 

bm_pool = bm_pool, 

prefix_storage = prefix_storage, 

max_prefix_length = max_prefix_length, 

max_prefix_number = max_prefix_number, 

verbose = verbose) 

  

bitset_discard(loc_b_prefix, i) 

  

if cost_i < upper_bound: 

upper_bound = cost_i 

if upper_bound <= cut_off: 

# We are satisfied with current solution. 

break 

  

# ==> Update prefix_storage 

# 

# If the prefix P is such that c(P)<\min_{L\in{\cal L}_P(V)} c(L), no other 

# prefix P' on the same set S=V(P) of vertices can lead to a better 

# solution. 

if loc_level<=max_prefix_length and current_cost<upper_bound and len(prefix_storage)<max_prefix_number: 

prefix_storage.add(frozen_prefix) 

  

return upper_bound