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

r""" 

Fast sparse graphs 

  

For an overview of graph data structures in sage, see 

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

  

Usage Introduction 

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

  

:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

  

Sparse graphs are initialized as follows:: 

  

sage: S = SparseGraph(nverts = 10, expected_degree = 3, extra_vertices = 10) 

  

This example initializes a sparse graph with room for twenty vertices, the first 

ten of which are in the graph. In general, the first ``nverts`` are "active." 

For example, see that 9 is already in the graph:: 

  

sage: S.verts() 

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

sage: S.add_vertex(9) 

9 

sage: S.verts() 

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

  

But 10 is not, until we add it:: 

  

sage: S.add_vertex(10) 

10 

sage: S.verts() 

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

  

You can begin working with unlabeled arcs right away as follows:: 

  

sage: S.add_arc(0,1) 

sage: S.add_arc(1,2) 

sage: S.add_arc(1,0) 

sage: S.has_arc(7,3) 

False 

sage: S.has_arc(0,1) 

True 

sage: S.in_neighbors(1) 

[0] 

sage: S.out_neighbors(1) 

[0, 2] 

sage: S.del_all_arcs(0,1) 

sage: S.all_arcs(0,1) 

[] 

sage: S.all_arcs(1,2) 

[0] 

sage: S.del_vertex(7) 

sage: S.all_arcs(7,3) 

Traceback (most recent call last): 

... 

LookupError: Vertex (7) is not a vertex of the graph. 

  

Sparse graphs support multiple edges and labeled edges, but requires that the 

labels be positive integers (the case label = 0 is treated as no label). 

  

:: 

  

sage: S.add_arc_label(0,1,-1) 

Traceback (most recent call last): 

... 

ValueError: Label (-1) must be a nonnegative integer. 

sage: S.add_arc(0,1) 

sage: S.arc_label(0,1) 

0 

  

Note that ``arc_label`` only returns the first edge label found in the specified 

place, and this can be in any order (if you want all arc labels, use 

``all_arcs``):: 

  

sage: S.add_arc_label(0,1,1) 

sage: S.arc_label(0,1) 

1 

sage: S.all_arcs(0,1) 

[0, 1] 

  

Zero specifies only that there is no labeled arc:: 

  

sage: S.arc_label(1,2) 

0 

  

So do not be fooled:: 

  

sage: S.all_arcs(1,2) 

[0] 

sage: S.add_arc(1,2) 

sage: S.arc_label(1,2) 

0 

  

Instead, if you work with unlabeled edges, be sure to use the right functions:: 

  

sage: T = SparseGraph(nverts = 3, expected_degree = 2) 

sage: T.add_arc(0,1) 

sage: T.add_arc(1,2) 

sage: T.add_arc(2,0) 

sage: T.has_arc(0,1) 

True 

  

Sparse graphs are by their nature directed. As of this writing, you need to do 

operations in pairs to treat the undirected case (or use a backend or a Sage 

graph):: 

  

sage: T.has_arc(1,0) 

False 

  

Multiple unlabeled edges are also possible:: 

  

sage: for _ in range(10): S.add_arc(5,4) 

sage: S.all_arcs(5,4) 

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

  

The curious developer is encouraged to check out the ``unsafe`` functions, 

which do not check input but which run in pure C. 

  

Underlying Data Structure 

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

  

The class ``SparseGraph`` contains the following variables which are inherited 

from ``CGraph`` (for explanation, refer to the documentation there):: 

  

cdef int num_verts 

cdef int num_arcs 

cdef int *in_degrees 

cdef int *out_degrees 

cdef bitset_t active_vertices 

  

It also contains the following variables:: 

  

cdef int hash_length 

cdef int hash_mask 

cdef SparseGraphBTNode **vertices 

  

For each vertex ``u``, a hash table of length ``hash_length`` is instantiated. 

An arc ``(u, v)`` is stored at ``u * hash_length + hash(v)`` of the array 

``vertices``, where ``hash`` should be thought of as an arbitrary but fixed hash 

function which takes values in ``0 <= hash < hash_length``. Each address may 

represent different arcs, say ``(u, v1)`` and ``(u, v2)`` where 

``hash(v1) == hash(v2)``. Thus, a binary tree structure is used at this step to 

speed access to individual arcs, whose nodes (each of which represents a pair 

``(u,v)``) are instances of the following type:: 

  

cdef struct SparseGraphBTNode: 

int vertex 

int number 

SparseGraphLLNode *labels 

SparseGraphBTNode *left 

SparseGraphBTNode *right 

  

Which range of the ``vertices`` array the root of the tree is in determines 

``u``, and ``vertex`` stores ``v``. The integer ``number`` stores only the 

number of unlabeled arcs from ``u`` to ``v``. 

  

Currently, labels are stored in a simple linked list, whose nodes are instances 

of the following type:: 

  

cdef struct SparseGraphLLNode: 

int label 

int number 

SparseGraphLLNode *next 

  

The int ``label`` must be a positive integer, since 0 indicates no label, and 

negative numbers indicate errors. The int ``number`` is the number of arcs with 

the given label. 

  

TODO: Optimally, edge labels would also be represented by a binary tree, which 

would help performance in graphs with many overlapping edges. Also, a more 

efficient binary tree structure could be used, although in practice the trees 

involved will usually have very small order, unless the degree of vertices 

becomes significantly larger than the ``expected_degree`` given, because this is 

the size of each hash table. Indeed, the expected size of the binary trees is 

`\frac{\text{actual degree}}{\text{expected degree}}`. Ryan Dingman, e.g., is 

working on a general-purpose Cython-based red black tree, which would be optimal 

for both of these uses. 

""" 

  

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

# Copyright (C) 2008-9 Robert L. Miller <rlmillster@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 libc.string cimport memset 

from cysignals.memory cimport check_malloc, check_allocarray, sig_free 

  

include 'sage/data_structures/bitset.pxi' 

  

cdef enum: 

BT_REORDERING_CONSTANT = 145533211 

# Since the binary tree will often see vertices coming in already sorted, 

# we don't use the normal ordering on integers, instead multiplying by a 

# randomly chosen number and (after reducing mod the size of integers) 

# comparing the result. This isn't necessarily the most efficient way to do 

# things, but it may just be on binary trees that are never bigger than two 

# or three nodes. 

  

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

# Here we rely on the fact that C performs arithmetic on unsigned 

# ints modulo 2^wordsize. 

cdef unsigned int aa = a, bb = b # signed ints lead to badness like a>b>c>a... 

if aa*BT_REORDERING_CONSTANT > bb*BT_REORDERING_CONSTANT: 

return 1 

elif aa*BT_REORDERING_CONSTANT < bb*BT_REORDERING_CONSTANT: 

return -1 

return 0 

  

cdef class SparseGraph(CGraph): 

""" 

Compiled sparse graphs. 

  

:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

  

Sparse graphs are initialized as follows:: 

  

sage: S = SparseGraph(nverts = 10, expected_degree = 3, extra_vertices = 10) 

  

INPUT: 

  

- ``nverts`` - non-negative integer, the number of vertices. 

- ``expected_degree`` - non-negative integer (default: 16), expected upper 

bound on degree of vertices. 

- ``extra_vertices`` - non-negative integer (default: 0), how many extra 

vertices to allocate. 

- ``verts`` - optional list of vertices to add 

- ``arcs`` - optional list of arcs to add 

  

The first ``nverts`` are created as vertices of the graph, and the next 

``extra_vertices`` can be freely added without reallocation. See top level 

documentation for more details. The input ``verts`` and ``arcs`` are mainly 

for use in pickling. 

  

""" 

  

def __cinit__(self, int nverts, int expected_degree = 16, int extra_vertices = 10, verts=None, arcs=None): 

""" 

Allocation and initialization happen in one place. 

  

Memory usage is roughly 

  

O( (nverts + extra_vertices)*expected_degree + num_arcs ). 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: S = SparseGraph(nverts = 10, expected_degree = 3, extra_vertices = 10) 

  

TESTS:: 

  

sage: Graph(-1) 

Traceback (most recent call last): 

... 

ValueError: The number of vertices cannot be strictly negative! 

""" 

cdef int i = 1 

if nverts < 0: 

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

if nverts == 0 and extra_vertices == 0: 

raise RuntimeError('Sparse graphs must allocate space for vertices!') 

self.num_verts = nverts 

nverts += extra_vertices 

self.num_arcs = 0 

while i < expected_degree: 

i = i << 1 

self.hash_length = i 

self.hash_mask = i - 1 

  

# Allocating memory (initialized to zero) 

self.vertices = <SparseGraphBTNode **>check_calloc( 

nverts * self.hash_length, sizeof(SparseGraphBTNode *)) 

self.in_degrees = <int *>check_calloc(nverts, sizeof(int)) 

self.out_degrees = <int *>check_calloc(nverts, sizeof(int)) 

  

bitset_init(self.active_vertices, self.num_verts + extra_vertices) 

bitset_set_first_n(self.active_vertices, self.num_verts) 

  

if verts is not None: 

self.add_vertices(verts) 

  

if arcs is not None: 

for u,v,l in arcs: 

self.add_arc_label(u,v,l) 

  

def __dealloc__(self): 

""" 

New and dealloc are both tested at class level. 

""" 

cdef SparseGraphBTNode **temp 

cdef SparseGraphLLNode *label_temp 

cdef int i 

  

# Freeing the list of arcs attached to each vertex 

for i from 0 <= i < self.active_vertices.size * self.hash_length: 

temp = &(self.vertices[i]) 

  

# While temp[0]=self.vertices[i] is not NULL, find a leaf in the 

# tree rooted at temp[0] and free it. Then go back to temp[0] and do 

# it again. When self.vertices[i] is NULL, go for self.vertices[i+1] 

while temp[0] != NULL: 

if temp[0].left != NULL: 

temp = &(temp[0].left) 

elif temp[0].right != NULL: 

temp = &(temp[0].right) 

else: 

label_temp = temp[0].labels 

while label_temp != NULL: 

temp[0].labels = label_temp.next 

sig_free(label_temp) 

label_temp = temp[0].labels 

sig_free(temp[0]) 

temp[0] = NULL 

temp = &(self.vertices[i]) 

  

sig_free(self.vertices) 

sig_free(self.in_degrees) 

sig_free(self.out_degrees) 

bitset_free(self.active_vertices) 

  

cpdef realloc(self, int total): 

""" 

Reallocate the number of vertices to use, without actually adding any. 

  

INPUT: 

  

- ``total`` - integer, the total size to make the array 

  

Returns -1 and fails if reallocation would destroy any active vertices. 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: S = SparseGraph(nverts=4, extra_vertices=4) 

sage: S.current_allocation() 

8 

sage: S.add_vertex(6) 

6 

sage: S.current_allocation() 

8 

sage: S.add_vertex(10) 

10 

sage: S.current_allocation() 

16 

sage: S.add_vertex(40) 

Traceback (most recent call last): 

... 

RuntimeError: Requested vertex is past twice the allocated range: use realloc. 

sage: S.realloc(50) 

sage: S.add_vertex(40) 

40 

sage: S.current_allocation() 

50 

sage: S.realloc(30) 

-1 

sage: S.current_allocation() 

50 

sage: S.del_vertex(40) 

sage: S.realloc(30) 

sage: S.current_allocation() 

30 

  

""" 

if total == 0: 

raise RuntimeError('Sparse graphs must allocate space for vertices!') 

cdef bitset_t bits 

if total < self.active_vertices.size: 

bitset_init(bits, self.active_vertices.size) 

bitset_set_first_n(bits, total) 

if not bitset_issubset(self.active_vertices, bits): 

bitset_free(bits) 

return -1 

bitset_free(bits) 

  

self.vertices = <SparseGraphBTNode **>check_reallocarray( 

self.vertices, total * self.hash_length, sizeof(SparseGraphBTNode *)) 

self.in_degrees = <int *>check_reallocarray(self.in_degrees, total, sizeof(int)) 

self.out_degrees = <int *>check_reallocarray(self.out_degrees, total, sizeof(int)) 

  

cdef int new_vertices = total - self.active_vertices.size 

  

# Initializing the entries corresponding to new vertices if any 

if new_vertices > 0: 

  

# self.vertices 

memset(self.vertices + self.active_vertices.size * self.hash_length, 0, 

new_vertices * self.hash_length * sizeof(SparseGraphBTNode *)) 

  

# self.in_degrees 

memset(self.in_degrees + self.active_vertices.size, 0, 

new_vertices * sizeof(int)) 

  

# self.out_degrees 

memset(self.out_degrees + self.active_vertices.size, 0, 

new_vertices * sizeof(int)) 

  

# self.active_vertices 

bitset_realloc(self.active_vertices, total) 

  

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

# Unlabeled arc functions 

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

  

cdef int add_arc_unsafe(self, int u, int v) except -1: 

""" 

Adds arc (u, v) to the graph with no label. 

  

INPUT: 

u, v -- non-negative integers 

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef int compared 

cdef SparseGraphBTNode **ins_pt = &(self.vertices[i]) 

while ins_pt[0] != NULL: 

compared = compare(ins_pt[0].vertex, v) 

if compared > 0: 

ins_pt = &(ins_pt[0].left) 

elif compared < 0: 

ins_pt = &(ins_pt[0].right) 

else: 

ins_pt[0].number += 1 

break 

if ins_pt[0] == NULL: 

ins_pt[0] = <SparseGraphBTNode *>check_malloc(sizeof(SparseGraphBTNode)) 

ins_pt[0].vertex = v 

ins_pt[0].number = 1 

ins_pt[0].left = NULL 

ins_pt[0].right = NULL 

ins_pt[0].labels = NULL 

self.in_degrees[v] += 1 

self.out_degrees[u] += 1 

self.num_arcs += 1 

  

cpdef add_arc(self, int u, int v): 

""" 

Adds arc ``(u, v)`` to the graph with no label. 

  

INPUT: 

  

- ``u, v`` -- non-negative integers, must be in self 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc(0,1) 

sage: G.add_arc(4,7) 

Traceback (most recent call last): 

... 

LookupError: Vertex (7) is not a vertex of the graph. 

sage: G.has_arc(1,0) 

False 

sage: G.has_arc(0,1) 

True 

  

""" 

self.check_vertex(u) 

self.check_vertex(v) 

self.add_arc_unsafe(u,v) 

  

cdef int has_arc_unsafe(self, int u, int v) except -1: 

""" 

Checks whether arc (u, v) is in the graph. 

  

INPUT: 

u, v -- non-negative integers, must be in self 

  

OUTPUT: 

0 -- False 

1 -- True 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef SparseGraphBTNode *temp = self.vertices[i] 

while temp != NULL: 

if temp.vertex == v: 

return 1 

if compare(temp.vertex, v) > 0: 

temp = temp.left 

else: # note compare < 0 

temp = temp.right 

return 0 

  

cpdef bint has_arc(self, int u, int v) except -1: 

""" 

Checks whether arc ``(u, v)`` is in the graph. 

  

INPUT: 

- ``u, v`` - integers 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(0,1) 

sage: G.has_arc(1,0) 

False 

sage: G.has_arc(0,1) 

True 

  

""" 

if u < 0 or u >= self.active_vertices.size or not bitset_in(self.active_vertices, u): 

return False 

if v < 0 or v >= self.active_vertices.size or not bitset_in(self.active_vertices, v): 

return False 

return self.has_arc_unsafe(u,v) 

  

cdef int del_arc_unsafe(self, int u, int v) except -1: 

""" 

Deletes *all* arcs from u to v. 

  

INPUT: 

u, v -- non-negative integers, must be in self 

  

OUTPUT: 

0 -- No error. 

1 -- No arc to delete. 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef int compared, left_len, right_len 

cdef SparseGraphBTNode *temp 

cdef SparseGraphBTNode **left_child 

cdef SparseGraphBTNode **right_child 

cdef SparseGraphBTNode **parent = &self.vertices[i] 

cdef SparseGraphLLNode *labels 

  

# Assigning to parent the SparseGraphBTNode corresponding to arc (u,v) 

while parent[0] != NULL: 

compared = compare(parent[0].vertex, v) 

if compared > 0: 

parent = &(parent[0].left) 

elif compared < 0: 

parent = &(parent[0].right) 

else:# if parent[0].vertex == v: 

break 

  

# If not found, there is no arc to delete ! 

if parent[0] == NULL: 

return 1 

  

# now parent[0] points to the BT node corresponding to (u,v) 

labels = parent[0].labels 

i = parent[0].number 

self.in_degrees[v] -= i 

self.out_degrees[u] -= i 

self.num_arcs -= i 

  

# Freeing the labels 

while labels != NULL: 

i = labels.number 

parent[0].labels = parent[0].labels.next 

sig_free(labels) 

labels = parent[0].labels 

self.in_degrees[v] -= i 

self.out_degrees[u] -= i 

self.num_arcs -= i 

  

# Now, if the SparseGraphBTNode element is to be removed, it has to be 

# replaced in the binary tree by one of its children. 

  

# If there is no left child 

if parent[0].left == NULL: 

temp = parent[0] 

parent[0] = parent[0].right 

sig_free(temp) 

return 0 

  

# If there is no right child 

elif parent[0].right == NULL: 

temp = parent[0] 

parent[0] = parent[0].left 

sig_free(temp) 

return 0 

  

# Both children 

else: 

left_len = 0 

right_len = 0 

left_child = &(parent[0].left) 

right_child = &(parent[0].right) 

  

# left_len is equal to the maximum length of a path LR...R. The 

# last element of this path is the value of left_child 

  

while left_child[0].right != NULL: 

left_len += 1 

left_child = &(left_child[0].right) 

# right_len is equal to the maximum length of a path RL...L. The 

# last element of this path is the value of right_child 

  

while right_child[0].left != NULL: 

right_len += 1 

right_child = &(right_child[0].left) 

  

# According to the respective lengths, replace parent by the left or 

# right child and place the other child at its expected place. 

if left_len > right_len: 

left_child[0].right = parent[0].right 

temp = parent[0] 

parent[0] = left_child[0] 

left_child[0] = left_child[0].left 

parent[0].left = temp.left 

sig_free(temp) 

return 0 

else: 

right_child[0].left = parent[0].left 

temp = parent[0] 

parent[0] = right_child[0] 

right_child[0] = right_child[0].right 

parent[0].right = temp.right 

sig_free(temp) 

return 0 

  

cpdef del_all_arcs(self, int u, int v): 

""" 

Deletes all arcs from ``u`` to ``v``. 

  

INPUT: 

- ``u, v`` - integers 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(0,1,0) 

sage: G.add_arc_label(0,1,1) 

sage: G.add_arc_label(0,1,2) 

sage: G.add_arc_label(0,1,3) 

sage: G.del_all_arcs(0,1) 

sage: G.has_arc(0,1) 

False 

sage: G.arc_label(0,1) 

0 

sage: G.del_all_arcs(0,1) 

  

""" 

self.check_vertex(u) 

self.check_vertex(v) 

self.del_arc_unsafe(u,v) 

  

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

# Neighbor functions 

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

  

cdef int out_neighbors_unsafe(self, int u, int *neighbors, int size) except -2: 

""" 

Gives all v such that (u, v) is an arc of the graph. 

  

INPUT: 

  

- ``u`` -- non-negative integer, must be in self neighbors -- must be a 

pointer to an (allocated) integer array size -- the length of the 

array 

  

OUTPUT: 

  

nonnegative integer -- the number of v such that (u, v) is an arc -1 

-- indicates that the array has been filled with neighbors, but 

there were more 

  

""" 

cdef int i, num_nbrs = 0, current_nbr = 0 

if self.out_degrees[u] == 0: 

return 0 

  

cdef SparseGraphBTNode ** pointers[1] 

cdef list l = [] 

cdef int n_neighbors = self.out_neighbors_BTNode_unsafe(u, pointers) 

if size >= n_neighbors: 

for i in range(n_neighbors): 

neighbors[i] = pointers[0][i].vertex 

else: 

for i in range(size): 

neighbors[i] = pointers[0][i].vertex 

n_neighbors = -1 

  

sig_free(pointers[0]) 

return n_neighbors 

  

cdef int out_neighbors_BTNode_unsafe(self, int u, SparseGraphBTNode *** p_pointers): 

""" 

Lists the out-neighbors of a vertex as BTNodes 

  

Technically, this function transforms a binary tree into a list. The 

information it returns is a list of pointers toward a 

``SparseGraphBTNode``, thus a ``SparseGraphBTNode **``. 

  

INPUT: 

  

- ``u`` -- the vertex to consider 

  

- ``p_pointers`` -- a pointer toward a ``SparseGraphBTNode **``, i.e. a 

``SparseGraphBTNode ***``. When the function terminates, 

``p_pointers[0]`` points toward a filled ``SparseGraphBTNode **``. It 

returns the length of this array. 

  

.. NOTE:: 

  

Don't forget to free ``p_pointers[0]`` ! 

""" 

cdef int i, num_nbrs = 0, current_nbr = 0 

cdef int degree = self.out_degrees[u] 

if degree == 0: 

p_pointers[0] = NULL 

return 0 

cdef SparseGraphBTNode **pointers = <SparseGraphBTNode **>check_allocarray(degree, sizeof(SparseGraphBTNode *)) 

p_pointers[0] = pointers 

for i from u * self.hash_length <= i < (u+1) * self.hash_length: 

if self.vertices[i] == NULL: 

continue 

pointers[num_nbrs] = self.vertices[i] 

num_nbrs += 1 

  

# While all the neighbors have not been added to the list, explore 

# element pointers[current_nbr] and append its children to the end 

# of pointers if necessary, the increment current_nbr. 

while current_nbr < num_nbrs: 

if pointers[current_nbr].left != NULL: 

pointers[num_nbrs] = pointers[current_nbr].left 

num_nbrs += 1 

if pointers[current_nbr].right != NULL: 

pointers[num_nbrs] = pointers[current_nbr].right 

num_nbrs += 1 

current_nbr += 1 

return num_nbrs 

  

cpdef list out_neighbors(self, int u): 

""" 

Gives all ``v`` such that ``(u, v)`` is an arc of the graph. 

  

INPUT: 

- ``u`` - integer 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc(0,1) 

sage: G.add_arc(1,2) 

sage: G.add_arc(1,3) 

sage: G.out_neighbors(0) 

[1] 

sage: G.out_neighbors(1) 

[2, 3] 

  

""" 

cdef int i, num_nbrs 

self.check_vertex(u) 

if self.out_degrees[u] == 0: 

return [] 

cdef int size = self.out_degrees[u] 

cdef int *neighbors = <int *>check_allocarray(size, sizeof(int)) 

num_nbrs = self.out_neighbors_unsafe(u, neighbors, size) 

output = [neighbors[i] for i from 0 <= i < num_nbrs] 

sig_free(neighbors) 

return output 

  

cpdef int out_degree(self, int u): 

""" 

Returns the out-degree of ``v`` 

  

INPUT: 

  

- ``u`` - integer 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc(0,1) 

sage: G.add_arc(1,2) 

sage: G.add_arc(1,3) 

sage: G.out_degree(0) 

1 

sage: G.out_degree(1) 

2 

""" 

return self.out_degrees[u] 

  

cdef list out_arcs_unsafe(self, int u, bint labels): 

r""" 

Builds the list of arcs leaving a vertex. 

  

Note that the source of each edge is *NOT* returned. 

  

INPUT: 

  

- ``u`` -- the vertex to consider 

  

- ``labels`` -- whether to return the labels alors with the outneighbor. 

If set to ``True``, the function returns a list of pairs 

``(destination, label)`` for each arc leaving `u`. If set to 

``False``, it returns a list of outneighbors (with multiplicity if 

several edges link two vertices). 

""" 

cdef SparseGraphBTNode ** pointers[1] 

cdef SparseGraphBTNode * node 

cdef int neighbors = self.out_neighbors_BTNode_unsafe(u, pointers) 

cdef SparseGraphLLNode *label 

cdef int i,j 

cdef list l = [] 

if labels: 

for i in range(neighbors): 

node = pointers[0][i] 

for j in range(node.number): 

l.append((node.vertex, 0)) 

label = node.labels 

while label != NULL: 

for k in range(label.number): 

l.append((node.vertex, label.label)) 

label = label.next 

else: 

for i in range(neighbors): 

node = pointers[0][i] 

for j in range(node.number): 

l.append(node.vertex) 

label = node.labels 

while label != NULL: 

for k in range(label.number): 

l.append(node.vertex) 

label = label.next 

  

if pointers[0] != NULL: 

sig_free(pointers[0]) 

  

return l 

  

cdef int in_neighbors_unsafe(self, int v, int *neighbors, int size) except -2: 

""" 

Gives all u such that (u, v) is an arc of the graph. 

  

INPUT: 

v -- non-negative integer, must be in self 

neighbors -- must be a pointer to an (allocated) integer array 

size -- the length of the array 

  

OUTPUT: 

nonnegative integer -- the number of u such that (u, v) is an arc 

-1 -- indicates that the array has been filled with neighbors, but 

there were more 

  

NOTE: Due to the implementation of SparseGraph, this method is much more 

expensive than out_neighbors_unsafe. 

  

""" 

cdef int i, num_nbrs = 0 

if self.in_degrees[v] == 0: 

return 0 

for i from 0 <= i < self.active_vertices.size: 

if not bitset_in(self.active_vertices, i): continue 

if self.has_arc_unsafe(i, v): 

if num_nbrs == size: 

return -1 

neighbors[num_nbrs] = i 

num_nbrs += 1 

return num_nbrs 

  

cpdef list in_neighbors(self, int v): 

""" 

Gives all ``u`` such that ``(u, v)`` is an arc of the graph. 

  

INPUT: 

- ``v`` - integer 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc(0,1) 

sage: G.add_arc(3,1) 

sage: G.add_arc(1,3) 

sage: G.in_neighbors(1) 

[0, 3] 

sage: G.in_neighbors(3) 

[1] 

  

NOTE: Due to the implementation of SparseGraph, this method is much more 

expensive than neighbors_unsafe. 

""" 

cdef int i, num_nbrs 

self.check_vertex(v) 

if self.in_degrees[v] == 0: 

return [] 

cdef int size = self.in_degrees[v] 

cdef int *neighbors = <int *>check_allocarray(size, sizeof(int)) 

num_nbrs = self.in_neighbors_unsafe(v, neighbors, size) 

output = [neighbors[i] for i from 0 <= i < num_nbrs] 

sig_free(neighbors) 

return output 

  

cpdef int in_degree(self, int u): 

""" 

Returns the in-degree of ``v`` 

  

INPUT: 

- ``u`` - integer 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc(0,1) 

sage: G.add_arc(1,2) 

sage: G.add_arc(1,3) 

sage: G.in_degree(0) 

0 

sage: G.in_degree(1) 

1 

""" 

return self.in_degrees[u] 

  

  

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

# Labeled arc functions 

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

  

cdef int add_arc_label_unsafe(self, int u, int v, int l) except -1: 

""" 

Adds arc (u, v) to the graph with label l. 

  

INPUT: 

u, v -- non-negative integers 

l -- a positive integer label, or zero for no label 

  

OUTPUT: 

0 -- No error. 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef int compared 

cdef SparseGraphBTNode **ins_pt = &(self.vertices[i]) 

cdef SparseGraphLLNode *label_ptr 

while ins_pt[0] != NULL: 

compared = compare(ins_pt[0].vertex, v) 

if compared > 0: 

ins_pt = &(ins_pt[0].left) 

elif compared < 0: 

ins_pt = &(ins_pt[0].right) 

else: 

break 

if ins_pt[0] == NULL: 

ins_pt[0] = <SparseGraphBTNode *>check_malloc(sizeof(SparseGraphBTNode)) 

ins_pt[0].number = 0 

ins_pt[0].vertex = v 

ins_pt[0].left = NULL 

ins_pt[0].right = NULL 

ins_pt[0].labels = NULL 

if l: 

label_ptr = ins_pt[0].labels 

while label_ptr != NULL and label_ptr.label != l: 

label_ptr = label_ptr.next 

if label_ptr == NULL: 

label_ptr = <SparseGraphLLNode *>check_malloc(sizeof(SparseGraphLLNode)) 

label_ptr.label = l 

label_ptr.number = 1 

label_ptr.next = ins_pt[0].labels 

ins_pt[0].labels = label_ptr 

else: 

label_ptr.number += 1 

else: 

ins_pt[0].number += 1 

self.in_degrees[v] += 1 

self.out_degrees[u] += 1 

self.num_arcs += 1 

  

def add_arc_label(self, int u, int v, int l=0): 

""" 

Adds arc ``(u, v)`` to the graph with label ``l``. 

  

INPUT: 

- ``u, v`` - non-negative integers, must be in self 

- ``l`` - a positive integer label, or zero for no label 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(0,1) 

sage: G.add_arc_label(4,7) 

Traceback (most recent call last): 

... 

LookupError: Vertex (7) is not a vertex of the graph. 

sage: G.has_arc(1,0) 

False 

sage: G.has_arc(0,1) 

True 

sage: G.add_arc_label(1,2,2) 

sage: G.arc_label(1,2) 

2 

  

""" 

self.check_vertex(u) 

self.check_vertex(v) 

if l < 0: 

raise ValueError("Label ({0}) must be a nonnegative integer.".format(l)) 

self.add_arc_label_unsafe(u,v,l) 

  

cdef int arc_label_unsafe(self, int u, int v): 

""" 

Retrieves the first label found associated with (u, v) (a positive 

integer). 

  

INPUT: 

u, v -- integers from 0, ..., n-1, where n is the number of vertices 

  

OUTPUT: 

positive integer -- indicates that there is a label on (u, v). 

0 -- either the arc (u, v) is unlabeled, or there is no arc at all. 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef int compared 

cdef SparseGraphBTNode *temp = self.vertices[i] 

while temp != NULL: 

compared = compare(temp.vertex, v) 

if compared > 0: 

temp = temp.left 

elif compared < 0: 

temp = temp.right 

else: 

break 

if temp == NULL or temp.labels == NULL: 

return 0 

return temp.labels.label 

  

cpdef int arc_label(self, int u, int v): 

""" 

Retrieves the first label found associated with ``(u, v)``. 

  

INPUT: 

- ``u, v`` - non-negative integers, must be in self 

  

OUTPUT: 

- positive integer - indicates that there is a label on ``(u, v)``. 

- 0 - either the arc ``(u, v)`` is unlabeled, or there is no arc at all. 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(3,4,7) 

sage: G.arc_label(3,4) 

7 

  

NOTES: 

  

To this function, an unlabeled arc is indistinguishable from a non-arc:: 

  

sage: G.add_arc_label(1,0) 

sage: G.arc_label(1,0) 

0 

sage: G.arc_label(1,1) 

0 

  

This function only returns the *first* label it finds from ``u`` to ``v``:: 

  

sage: G.add_arc_label(1,2,1) 

sage: G.add_arc_label(1,2,2) 

sage: G.arc_label(1,2) 

2 

  

""" 

self.check_vertex(u) 

self.check_vertex(v) 

return self.arc_label_unsafe(u,v) 

  

cdef int all_arcs_unsafe(self, int u, int v, int *arc_labels, int size): 

""" 

Gives the labels of all arcs (u, v). 

  

INPUT: 

u, v -- integers from 0, ..., n-1, where n is the number of vertices 

arc_labels -- must be a pointer to an (allocated) integer array 

size -- the length of the array 

  

OUTPUT: 

integer -- the number of arcs (u, v) 

-1 -- indicates that the array has been filled with labels, but 

there were more 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask), j 

cdef int compared, num_arcs 

cdef SparseGraphBTNode *temp = self.vertices[i] 

cdef SparseGraphLLNode *label 

while temp != NULL: 

compared = compare(temp.vertex, v) 

if compared > 0: 

temp = temp.left 

elif compared < 0: 

temp = temp.right 

else: # temp.vertex == v: 

break 

if temp == NULL: 

return 0 

j = 0 

num_arcs = temp.number 

while j < num_arcs and j < size: 

arc_labels[j] = 0 

j += 1 

label = temp.labels 

while label != NULL: 

num_arcs += label.number 

while j < num_arcs and j < size: 

arc_labels[j] = label.label 

j += 1 

label = label.next 

if j == size and label != NULL: 

return -1 

return num_arcs 

  

cpdef list all_arcs(self, int u, int v): 

""" 

Gives the labels of all arcs ``(u, v)``. An unlabeled arc is interpreted as 

having label 0. 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(1,2,1) 

sage: G.add_arc_label(1,2,2) 

sage: G.add_arc_label(1,2,2) 

sage: G.add_arc_label(1,2,2) 

sage: G.add_arc_label(1,2,3) 

sage: G.add_arc_label(1,2,3) 

sage: G.add_arc_label(1,2,4) 

sage: G.all_arcs(1,2) 

[4, 3, 3, 2, 2, 2, 1] 

  

""" 

cdef int size, num_arcs, i 

cdef int *arc_labels 

cdef list output 

self.check_vertex(u) 

self.check_vertex(v) 

if self.in_degrees[v] < self.out_degrees[u]: 

size = self.in_degrees[v] 

else: 

size = self.out_degrees[u] 

arc_labels = <int *>check_allocarray(size, sizeof(int)) 

num_arcs = self.all_arcs_unsafe(u, v, arc_labels, size) 

if num_arcs == -1: 

sig_free(arc_labels) 

raise RuntimeError("There was an error: there seem to be more arcs than self.in_degrees or self.out_degrees indicate.") 

output = [arc_labels[i] for i from 0 <= i < num_arcs] 

sig_free(arc_labels) 

return output 

  

cdef int del_arc_label_unsafe(self, int u, int v, int l): 

""" 

Delete an arc (u, v) with label l. 

  

INPUT: 

u, v -- integers from 0, ..., n-1, where n is the number of vertices 

l -- a positive integer label, or zero for no label 

  

OUTPUT: 

0 -- No error. 

1 -- No arc with label l. 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef int compared 

cdef SparseGraphBTNode **parent = &self.vertices[i] 

cdef SparseGraphLLNode **labels 

cdef SparseGraphLLNode *label 

while parent[0] != NULL: 

compared = compare(parent[0].vertex, v) 

if compared > 0: 

parent = &(parent[0].left) 

elif compared < 0: 

parent = &(parent[0].right) 

else: # if parent[0].vertex == v: 

break 

if parent[0] == NULL: 

return 1 # indicate an error 

if l == 0: 

if parent[0].number > 1: parent[0].number -= 1 

elif parent[0].number == 1: 

if parent[0].labels == NULL: 

self.del_arc_unsafe(u, v) 

return 0 

else: parent[0].number -= 1 

else: return 1 # indicate an error 

else: 

labels = &(parent[0].labels) 

while labels[0] != NULL and labels[0].label != l: 

labels = &(labels[0].next) 

if labels[0] == NULL: 

return 1 

label = labels[0] 

if label.number > 1: 

label.number -= 1 

else: 

labels[0] = labels[0].next 

sig_free(label) 

if labels == &(parent[0].labels) and labels[0] == NULL and parent[0].number == 0: 

# here we need to delete an "empty" binary tree node 

self.del_arc_unsafe(u, v) 

self.in_degrees[v] -= 1 

self.out_degrees[u] -= 1 

self.num_arcs -= 1 

  

cpdef del_arc_label(self, int u, int v, int l): 

""" 

Delete an arc ``(u, v)`` with label ``l``. 

  

INPUT: 

- ``u, v`` - non-negative integers, must be in self 

- ``l`` - a positive integer label, or zero for no label 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(0,1,0) 

sage: G.add_arc_label(0,1,1) 

sage: G.add_arc_label(0,1,2) 

sage: G.add_arc_label(0,1,2) 

sage: G.add_arc_label(0,1,3) 

sage: G.del_arc_label(0,1,2) 

sage: G.all_arcs(0,1) 

[0, 3, 2, 1] 

sage: G.del_arc_label(0,1,0) 

sage: G.all_arcs(0,1) 

[3, 2, 1] 

  

""" 

self.check_vertex(u) 

self.check_vertex(v) 

if l < 0: 

raise ValueError("Label ({0}) must be a nonnegative integer.".format(l)) 

self.del_arc_label_unsafe(u,v,l) 

  

cdef int has_arc_label_unsafe(self, int u, int v, int l): 

""" 

Indicates whether there is an arc (u, v) with label l. 

  

INPUT: 

u, v -- integers from 0, ..., n-1, where n is the number of vertices 

l -- a positive integer label, or zero for no label 

  

OUTPUT: 

0 -- False 

1 -- True 

  

""" 

cdef int i = (u * self.hash_length) + (v & self.hash_mask) 

cdef int compared 

cdef SparseGraphBTNode *temp = self.vertices[i] 

cdef SparseGraphLLNode *label 

while temp != NULL: 

compared = compare(temp.vertex, v) 

if compared > 0: 

temp = temp.left 

elif compared < 0: 

temp = temp.right 

else:# if temp.vertex == v: 

break 

if temp == NULL: 

return 0 

if l == 0 and temp.number > 0: 

return 1 

label = temp.labels 

while label != NULL: 

if label.label == l: 

return 1 

label = label.next 

return 0 

  

cpdef bint has_arc_label(self, int u, int v, int l): 

""" 

Indicates whether there is an arc ``(u, v)`` with label ``l``. 

  

INPUT: 

- ``u, v`` -- non-negative integers, must be in self 

- ``l`` -- a positive integer label, or zero for no label 

  

EXAMPLES:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: G = SparseGraph(5) 

sage: G.add_arc_label(0,1,0) 

sage: G.add_arc_label(0,1,1) 

sage: G.add_arc_label(0,1,2) 

sage: G.add_arc_label(0,1,2) 

sage: G.has_arc_label(0,1,1) 

True 

sage: G.has_arc_label(0,1,2) 

True 

sage: G.has_arc_label(0,1,3) 

False 

  

""" 

self.check_vertex(u) 

self.check_vertex(v) 

if l < 0: 

raise ValueError("Label ({0}) must be a nonnegative integer.".format(l)) 

return self.has_arc_label_unsafe(u,v,l) == 1 

  

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

# Further tests. Unit tests for methods, functions, classes defined with cdef. 

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

  

def _test_adjacency_sequence_out(): 

""" 

Randomly test the method ``SparseGraph.adjacency_sequence_out()``. No output 

indicates that no errors were found. 

  

TESTS:: 

  

sage: from sage.graphs.base.sparse_graph import _test_adjacency_sequence_out 

sage: _test_adjacency_sequence_out() # long time 

""" 

from sage.graphs.digraph import DiGraph 

from sage.graphs.graph_generators import GraphGenerators 

from sage.misc.prandom import randint, random 

low = 0 

high = 1000 

randg = DiGraph(GraphGenerators().RandomGNP(randint(low, high), random())) 

n = randg.order() 

# set all labels to 0 

E = [(u, v, 0) for u, v in randg.edges(labels=False)] 

cdef SparseGraph g = SparseGraph(n, 

verts=randg.vertices(), 

arcs=E) 

assert g.num_verts == randg.order(), ( 

"Graph order mismatch: %s vs. %s" % (g.num_verts, randg.order())) 

assert g.num_arcs == randg.size(), ( 

"Graph size mismatch: %s vs. %s" % (g.num_arcs, randg.size())) 

M = randg.adjacency_matrix() 

cdef int *V = <int *>check_allocarray(n, sizeof(int)) 

cdef int i = 0 

for v in randg.vertex_iterator(): 

V[i] = v 

i += 1 

cdef int *seq = <int *>check_allocarray(n, sizeof(int)) 

for 0 <= i < randint(50, 101): 

u = randint(low, n - 1) 

g.adjacency_sequence_out(n, V, u, seq) 

A = [seq[k] for k in range(n)] 

try: 

assert A == list(M[u]) 

except AssertionError: 

sig_free(V) 

sig_free(seq) 

raise AssertionError("Graph adjacency mismatch") 

sig_free(seq) 

sig_free(V) 

  

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

# Sparse Graph Backend 

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

  

cdef class SparseGraphBackend(CGraphBackend): 

""" 

Backend for Sage graphs using SparseGraphs. 

  

:: 

  

sage: from sage.graphs.base.sparse_graph import SparseGraphBackend 

  

This class is only intended for use by the Sage Graph and DiGraph class. 

If you are interested in using a SparseGraph, you probably want to do 

something like the following example, which creates a Sage Graph instance 

which wraps a SparseGraph object:: 

  

sage: G = Graph(30, implementation="c_graph", sparse=True) 

sage: G.add_edges([(0,1), (0,3), (4,5), (9, 23)]) 

sage: G.edges(labels=False) 

[(0, 1), (0, 3), (4, 5), (9, 23)] 

  

Note that Sage graphs using the backend are more flexible than SparseGraphs 

themselves. This is because SparseGraphs (by design) do not deal with Python 

objects:: 

  

sage: G.add_vertex((0,1,2)) 

sage: G.vertices() 

[0, 

... 

29, 

(0, 1, 2)] 

sage: from sage.graphs.base.sparse_graph import SparseGraph 

sage: SG = SparseGraph(30) 

sage: SG.add_vertex((0,1,2)) 

Traceback (most recent call last): 

... 

TypeError: an integer is required 

  

""" 

  

def __init__(self, int n, directed=True): 

""" 

Initialize a sparse graph with n vertices. 

  

EXAMPLES: 

  

sage: D = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: D.add_edge(0,1,None,False) 

sage: list(D.iterator_edges(range(9), True)) 

[(0, 1, None)] 

  

""" 

self._cg = SparseGraph(n) 

self._cg_rev = SparseGraph(n) if directed else self._cg 

self._directed = directed 

self.vertex_labels = {} 

self.vertex_ints = {} 

self.edge_labels = {} 

self.edge_labels_max = 1 

self.edge_labels_available_ids = [] 

  

cdef inline int new_edge_label(self, object l): 

""" 

Returns a new unique int representing the arbitrary label l. 

""" 

if l is None: 

return 0 

  

cdef int l_int 

if self.edge_labels_available_ids: 

l_int = self.edge_labels_available_ids.pop(-1) 

else: 

l_int = self.edge_labels_max 

self.edge_labels_max += 1 

  

self.edge_labels[l_int] = l 

return l_int 

  

def add_edge(self, object u, object v, object l, bint directed): 

""" 

Adds the edge ``(u,v)`` to self. 

  

INPUT: 

  

- ``u,v`` - the vertices of the edge 

- ``l`` - the edge label 

- ``directed`` - if False, also add ``(v,u)`` 

  

EXAMPLES:: 

  

sage: D = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: D.add_edge(0,1,None,False) 

sage: list(D.iterator_edges(range(9), True)) 

[(0, 1, None)] 

  

TESTS:: 

  

sage: D = DiGraph(implementation='c_graph', sparse=True) 

sage: D.add_edge(0,1,2) 

sage: D.add_edge(0,1,3) 

sage: D.edges() 

[(0, 1, 3)] 

  

Check :trac:`22991`:: 

  

sage: G = Graph(3, sparse=True) 

sage: G.add_edge(0,0) 

Traceback (most recent call last): 

... 

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

sage: G = Graph(3, sparse=True, loops=True) 

sage: G.add_edge(0,0); G.edges() 

[(0, 0, None)] 

""" 

if u is None: u = self.add_vertex(None) 

if v is None: v = self.add_vertex(None) 

  

cdef int u_int = self.check_labelled_vertex(u, self._directed) 

cdef int v_int = self.check_labelled_vertex(v, self._directed) 

  

cdef int l_int 

if l is None: 

l_int = 0 

else: 

l_int = self.new_edge_label(l) 

  

if u_int == v_int and not self._loops: 

raise ValueError(f"cannot add edge from {u!r} to {v!r} in graph without loops") 

  

if not self.multiple_edges(None): 

if self._cg.has_arc_label(u_int, v_int, l_int): 

return 

else: 

self._cg.del_all_arcs(u_int, v_int) 

if not directed: 

self._cg.del_all_arcs(v_int, u_int) 

if directed: 

self._cg.add_arc_label(u_int, v_int, l_int) 

self._cg_rev.add_arc_label(v_int, u_int, l_int) 

elif u_int == v_int: 

self._cg.add_arc_label(u_int, v_int, l_int) 

else: 

self._cg.add_arc_label(u_int, v_int, l_int) 

self._cg.add_arc_label(v_int, u_int, l_int) 

  

def add_edges(self, object edges, bint directed): 

""" 

Add edges from a list. 

  

INPUT: 

  

- ``edges`` - the edges to be added - can either be of the form 

``(u,v)`` or ``(u,v,l)`` 

- ``directed`` - if False, add ``(v,u)`` as well as ``(u,v)`` 

  

EXAMPLES:: 

  

sage: D = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: D.add_edges([(0,1), (2,3), (4,5), (5,6)], False) 

sage: list(D.iterator_edges(range(9), True)) 

[(0, 1, None), 

(2, 3, None), 

(4, 5, None), 

(5, 6, None)] 

  

""" 

cdef object u,v,l,e 

for e in edges: 

try: 

u,v,l = e 

except Exception: 

u,v = e 

l = None 

self.add_edge(u,v,l,directed) 

  

def del_edge(self, object u, object v, object l, bint directed): 

""" 

Delete edge ``(u,v,l)``. 

  

INPUT: 

  

- ``u,v`` - the vertices of the edge 

- ``l`` - the edge label 

- ``directed`` - if False, also delete ``(v,u,l)`` 

  

EXAMPLES:: 

  

sage: D = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: D.add_edges([(0,1), (2,3), (4,5), (5,6)], False) 

sage: list(D.iterator_edges(range(9), True)) 

[(0, 1, None), 

(2, 3, None), 

(4, 5, None), 

(5, 6, None)] 

sage: D.del_edge(0,1,None,True) 

sage: list(D.iterator_out_edges(range(9), True)) 

[(1, 0, None), 

(2, 3, None), 

(3, 2, None), 

(4, 5, None), 

(5, 4, None), 

(5, 6, None), 

(6, 5, None)] 

  

TESTS:: 

  

sage: G = Graph(implementation='c_graph', sparse=True) 

sage: G.add_edge(0,1,2) 

sage: G.delete_edge(0,1) 

sage: G.edges() 

[] 

  

sage: G = Graph(multiedges=True, implementation='c_graph', sparse=True) 

sage: G.add_edge(0,1,2) 

sage: G.add_edge(0,1,None) 

sage: G.delete_edge(0,1) 

sage: G.edges() 

[(0, 1, 2)] 

  

Do we remove loops correctly? (:trac:`12135`):: 

  

sage: g=Graph({0:[0,0,0]}, implementation='c_graph', sparse=True) 

sage: g.edges(labels=False) 

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

sage: g.delete_edge(0,0); g.edges(labels=False) 

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

""" 

if not ( self.has_vertex(u) and self.has_vertex(v) ): 

return 

cdef int u_int = self.check_labelled_vertex(u, self._directed) 

cdef int v_int = self.check_labelled_vertex(v, self._directed) 

  

if l is None: 

if self._cg.has_arc_label(u_int, v_int, 0): 

l_int = 0 

else: 

l_int = self._cg.arc_label(u_int, v_int) 

else: 

for l_int in self.edge_labels: 

if self.edge_labels[l_int] == l and self._cg.has_arc_label(u_int, v_int, l_int): 

break 

else: 

return 

  

if directed: 

self._cg.del_arc_label(u_int, v_int, l_int) 

self._cg_rev.del_arc_label(v_int, u_int, l_int) 

if l_int: 

self.edge_labels.pop(l_int) 

self.edge_labels_available_ids.append(l_int) 

else: 

self._cg.del_arc_label(u_int, v_int, l_int) 

if v_int != u_int: self._cg.del_arc_label(v_int, u_int, l_int) 

if l_int: 

self.edge_labels.pop(l_int) 

self.edge_labels_available_ids.append(l_int) 

  

def get_edge_label(self, object u, object v): 

""" 

Returns the edge label for ``(u,v)``. 

  

INPUT: 

  

- ``u,v`` - the vertices of the edge 

  

EXAMPLES:: 

  

sage: D = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: D.add_edges([(0,1,1), (2,3,2), (4,5,3), (5,6,2)], False) 

sage: list(D.iterator_edges(range(9), True)) 

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

sage: D.get_edge_label(3,2) 

2 

  

""" 

cdef int l_int 

if not self.has_vertex(u): 

raise LookupError("({0}) is not a vertex of the graph.".format(repr(u))) 

if not self.has_vertex(v): 

raise LookupError("({0}) is not a vertex of the graph.".format(repr(v))) 

cdef int u_int = self.get_vertex(u) 

cdef int v_int = self.get_vertex(v) 

if not (<SparseGraph>self._cg).has_arc_unsafe(u_int, v_int): 

raise LookupError("({0}, {1}) is not an edge of the graph.".format(repr(u),repr(v))) 

if self.multiple_edges(None): 

return [self.edge_labels[l_int] if l_int != 0 else None 

for l_int in self._cg.all_arcs(u_int, v_int)] 

l_int = self._cg.arc_label(u_int, v_int) 

return self.edge_labels[l_int] if l_int else None 

  

def has_edge(self, object u, object v, object l): 

""" 

Returns whether this graph has edge ``(u,v)`` with label ``l``. If ``l`` 

is ``None``, return whether this graph has an edge ``(u,v)`` with any 

label. 

  

INPUT: 

  

- ``u,v`` - the vertices of the edge 

- ``l`` - the edge label, or ``None`` 

  

EXAMPLES:: 

  

sage: D = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: D.add_edges([(0,1), (2,3), (4,5), (5,6)], False) 

sage: D.has_edge(0,1,None) 

True 

  

""" 

if not ( self.has_vertex(u) and self.has_vertex(v) ): 

return False 

cdef int u_int = self.get_vertex(u) 

cdef int v_int = self.get_vertex(v) 

if l is None: 

return self._cg.has_arc(u_int, v_int) 

for l_int in self._cg.all_arcs(u_int, v_int): 

if l_int and self.edge_labels[l_int] == l: 

return True 

return False 

  

def iterator_edges(self, object vertices, bint labels): 

""" 

Iterate over the edges incident to a sequence of vertices. Edges are 

assumed to be undirected. 

  

INPUT: 

  

- ``vertices`` - a list of vertex labels 

- ``labels`` - boolean, whether to return labels as well 

  

EXAMPLES:: 

  

sage: G = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: G.add_edge(1,2,3,False) 

sage: list(G.iterator_edges(range(9), False)) 

[(1, 2)] 

sage: list(G.iterator_edges(range(9), True)) 

[(1, 2, 3)] 

  

TESTS:: 

  

sage: g = graphs.PetersenGraph() 

sage: g.edges_incident([0,1,2]) 

[(0, 1, None), 

(0, 4, None), 

(0, 5, None), 

(1, 2, None), 

(1, 6, None), 

(2, 3, None), 

(2, 7, None)] 

""" 

cdef object u, v, l 

cdef int u_int, v_int, l_int 

cdef FrozenBitset b_vertices 

  

# ALL edges 

if not isinstance(vertices, list): 

if labels: 

for v in self.iterator_verts(): 

v_int = self.get_vertex(v) 

for u_int, l_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, True): 

if u_int >= v_int: 

u = self.vertex_label(u_int) 

l = self.edge_labels[l_int] if l_int else None 

yield (v, u, l) if v<=u else (u, v, l) 

  

else: 

for v in self.iterator_verts(): 

v_int = self.get_vertex(v) 

for u_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, False): 

if u_int >= v_int: 

u = self.vertex_label(u_int) 

yield (v, u) if v <= u else (u, v) 

  

# One vertex 

elif len(vertices) == 1: 

v = vertices[0] 

v_int = self.get_vertex(v) 

  

if labels: 

for u_int, l_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, True): 

u = self.vertex_label(u_int) 

l = self.edge_labels[l_int] if l_int else None 

yield (v, u, l) if v<=u else (u, v, l) 

else: 

for u_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, False): 

u = self.vertex_label(u_int) 

yield (v, u) if v <= u else (u, v) 

  

# Several vertices (nonempty list) 

elif vertices: 

b_vertices = FrozenBitset([self.get_vertex(v) for v in vertices]) 

if labels: 

for v in vertices: 

v_int = self.get_vertex(v) 

  

for u_int, l_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, True): 

if u_int >= v_int or u_int not in b_vertices: 

u = self.vertex_label(u_int) 

l = self.edge_labels[l_int] if l_int else None 

yield (v, u, l) if v<=u else (u, v, l) 

else: 

for v in vertices: 

v_int = self.get_vertex(v) 

for u_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, False): 

if u_int >= v_int or u_int not in b_vertices: 

u = self.vertex_label(u_int) 

yield (v, u) if v <= u else (u, v) 

  

def iterator_in_edges(self, object vertices, bint labels): 

""" 

Iterate over the incoming edges incident to a sequence of vertices. 

  

INPUT: 

  

- ``vertices`` - a list of vertex labels 

- ``labels`` - boolean, whether to return labels as well 

  

EXAMPLES:: 

  

sage: G = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: G.add_edge(1,2,3,True) 

sage: list(G.iterator_in_edges([1], False)) 

[] 

sage: list(G.iterator_in_edges([2], False)) 

[(1, 2)] 

sage: list(G.iterator_in_edges([2], True)) 

[(1, 2, 3)] 

  

""" 

cdef object u, v, L, l 

vertices = [self.get_vertex(v) for v in vertices if self.has_vertex(v)] 

cdef int u_int, v_int, l_int 

if self.multiple_edges(None): 

if labels: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int, l_int in (<SparseGraph> self._cg_rev).out_arcs_unsafe(v_int, True): 

u = self.vertex_label(u_int) 

l = self.edge_labels[l_int] if l_int else None 

yield (u, v, l) 

else: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int in (<SparseGraph> self._cg_rev).out_arcs_unsafe(v_int, False): 

u = self.vertex_label(u_int) 

yield (u, v) 

else: 

if labels: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int in self._cg_rev.out_neighbors(v_int): 

l_int = self._cg.arc_label(u_int, v_int) 

yield (self.vertex_label(u_int), 

v, 

None if l_int == 0 else self.edge_labels[l_int]) 

else: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int in self._cg_rev.out_neighbors(v_int): 

yield (self.vertex_label(u_int), 

v) 

  

def iterator_out_edges(self, object vertices, bint labels): 

""" 

Iterate over the outbound edges incident to a sequence of vertices. 

  

INPUT: 

- ``vertices`` - a list of vertex labels 

- ``labels`` - boolean, whether to return labels as well 

  

EXAMPLES:: 

  

sage: G = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: G.add_edge(1,2,3,True) 

sage: list(G.iterator_out_edges([2], False)) 

[] 

sage: list(G.iterator_out_edges([1], False)) 

[(1, 2)] 

sage: list(G.iterator_out_edges([1], True)) 

[(1, 2, 3)] 

  

""" 

cdef object u, v, L, l 

vertices = [self.get_vertex(v) for v in vertices if self.has_vertex(v)] 

cdef int u_int, v_int, l_int 

if self.multiple_edges(None): 

if labels: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int, l_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, True): 

u = self.vertex_label(u_int) 

l = self.edge_labels[l_int] if l_int else None 

yield (v, u, l) 

else: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int in (<SparseGraph> self._cg).out_arcs_unsafe(v_int, False): 

u = self.vertex_label(u_int) 

yield (v, u) 

else: 

if labels: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int in self._cg.out_neighbors(v_int): 

l_int = self._cg.arc_label(v_int, u_int) 

yield (v, 

self.vertex_label(u_int), 

None if l_int == 0 else self.edge_labels[l_int]) 

else: 

for v_int in vertices: 

v = self.vertex_label(v_int) 

for u_int in self._cg.out_neighbors(v_int): 

yield (v, 

self.vertex_label(u_int)) 

  

def multiple_edges(self, new): 

""" 

Get/set whether or not ``self`` allows multiple edges. 

  

INPUT: 

  

- ``new`` - boolean (to set) or ``None`` (to get) 

  

EXAMPLES:: 

  

sage: G = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: G.multiple_edges(True) 

sage: G.multiple_edges(None) 

True 

sage: G.multiple_edges(False) 

sage: G.multiple_edges(None) 

False 

sage: G.add_edge(0,1,0,True) 

sage: G.add_edge(0,1,0,True) 

sage: list(G.iterator_edges(range(9), True)) 

[(0, 1, 0)] 

  

""" 

if new is None: 

return self._multiple_edges 

self._multiple_edges = bool(new) 

  

def set_edge_label(self, object u, object v, object l, bint directed): 

""" 

Label the edge ``(u,v)`` by ``l``. 

  

INPUT: 

  

- ``u,v`` - the vertices of the edge 

- ``l`` - the edge label 

- ``directed`` - if False, also set ``(v,u)`` with label ``l`` 

  

EXAMPLES:: 

  

sage: G = sage.graphs.base.sparse_graph.SparseGraphBackend(9) 

sage: G.add_edge(1,2,None,True) 

sage: G.set_edge_label(1,2,'a',True) 

sage: list(G.iterator_edges(range(9), True)) 

[(1, 2, 'a')] 

  

Note that it fails silently if there is no edge there:: 

  

sage: G.set_edge_label(2,1,'b',True) 

sage: list(G.iterator_edges(range(9), True)) 

[(1, 2, 'a')] 

  

""" 

if not self.has_edge(u, v, None): 

return 

if self.multiple_edges(None): 

if len(self.get_edge_label(u, v)) > 1: 

raise RuntimeError("Cannot set edge label, since there are multiple edges from %s to %s."%(u,v)) 

# now we know there is exactly one edge from u to v 

cdef int l_int, ll_int 

if l is None: 

l_int = 0 

else: 

l_int = self.new_edge_label(l) 

cdef int u_int = self.get_vertex(u) 

cdef int v_int = self.get_vertex(v) 

if not (<SparseGraph>self._cg).has_arc_unsafe(u_int, v_int): 

return 

ll_int = (<SparseGraph>self._cg).arc_label_unsafe(u_int, v_int) 

if ll_int: 

self.edge_labels.pop(ll_int) 

self.edge_labels_available_ids.append(ll_int) 

if directed: 

self._cg.del_arc_label(u_int, v_int, ll_int) 

self._cg_rev.del_arc_label(v_int, u_int, ll_int) 

self._cg.add_arc_label(u_int, v_int, l_int) 

self._cg_rev.add_arc_label(v_int, u_int, l_int) 

elif u_int == v_int: 

self._cg.del_arc_label(u_int, v_int, ll_int) 

self._cg.add_arc_label(u_int, v_int, l_int) 

else: 

self._cg.del_arc_label(u_int, v_int, ll_int) 

self._cg.del_arc_label(v_int, u_int, ll_int) 

self._cg.add_arc_label(u_int, v_int, l_int) 

self._cg.add_arc_label(v_int, u_int, l_int)