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

""" 

Miscellaneous functions 

 

AUTHORS: 

 

- William Stein 

 

- William Stein (2006-04-26): added workaround for Windows where most 

users' home directory has a space in it. 

 

- Robert Bradshaw (2007-09-20): Ellipsis range/iterator. 

 

TESTS: 

 

The following test, verifying that :trac:`16181` has been resolved, needs 

to stay at the beginning of this file so that its context is not 

poisoned by other tests:: 

 

sage: sage.misc.misc.inject_variable('a', 0) 

sage: a 

0 

 

Check the fix from :trac:`8323`:: 

 

sage: 'name' in globals() 

False 

sage: 'func' in globals() 

False 

""" 

 

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

# Copyright (C) 2006 William Stein <wstein@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 print_function, absolute_import 

from six.moves import range 

from six import integer_types 

 

import os 

import stat 

import sys 

import time 

import resource 

import sage.misc.prandom as random 

import warnings 

from .lazy_string import lazy_string 

 

from sage.env import DOT_SAGE, HOSTNAME 

 

LOCAL_IDENTIFIER = '%s.%s'%(HOSTNAME , os.getpid()) 

 

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

# File and directory utilities 

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

 

def sage_makedirs(dir): 

""" 

Python version of ``mkdir -p``: try to create a directory, and also 

create all intermediate directories as necessary. Succeed silently 

if the directory already exists (unlike ``os.makedirs()``). 

Raise other errors (like permission errors) normally. 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import sage_makedirs 

sage: sage_makedirs(DOT_SAGE) # no output 

 

The following fails because we are trying to create a directory in 

place of an ordinary file (the main Sage executable):: 

 

sage: sage_executable = os.path.join(SAGE_ROOT, 'sage') 

sage: sage_makedirs(sage_executable) 

Traceback (most recent call last): 

... 

OSError: ... 

""" 

try: 

os.makedirs(dir) 

except OSError: 

if not os.path.isdir(dir): 

raise 

 

 

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

# Now that the variable DOT_SAGE has been set, 

# we make sure that the DOT_SAGE directory 

# has restrictive permissions, since otherwise 

# possibly just anybody can easily see every 

# command you type, since it is in the history, 

# and every worksheet you create, etc. 

# We do the following: 

# 1. If there is no DOT_SAGE, we create it. 

# 2. Check to see if the permissions on DOT_SAGE are 

# sufficiently restrictive. If not, we change them. 

 

sage_makedirs(DOT_SAGE) 

 

if hasattr(os, 'chmod'): 

_mode = os.stat(DOT_SAGE)[stat.ST_MODE] 

_desired_mode = 0o40700 # drwx------ 

if _mode != _desired_mode: 

# On Cygwin, if the sage directory is not in a filesystem mounted with 

# 'acl' support, setting the permissions may fail silently, so only 

# print the message after we've changed the permissions and confirmed 

# that the change succeeded 

os.chmod(DOT_SAGE, _desired_mode) 

if os.stat(DOT_SAGE)[stat.ST_MODE] == _desired_mode: 

print("Setting permissions of DOT_SAGE directory so only you " 

"can read and write it.") 

 

 

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

# Next we create the Sage temporary directory. 

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

 

@lazy_string 

def SAGE_TMP(): 

""" 

EXAMPLES:: 

 

sage: from sage.misc.misc import SAGE_TMP 

sage: SAGE_TMP 

l'.../temp/...' 

""" 

d = os.path.join(DOT_SAGE, 'temp', HOSTNAME, str(os.getpid())) 

sage_makedirs(d) 

return d 

 

 

@lazy_string 

def ECL_TMP(): 

""" 

Temporary directory that should be used by ECL interfaces launched from 

Sage. 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import ECL_TMP 

sage: ECL_TMP 

l'.../temp/.../ecl' 

""" 

d = os.path.join(str(SAGE_TMP), 'ecl') 

sage_makedirs(d) 

return d 

 

 

@lazy_string 

def SPYX_TMP(): 

""" 

EXAMPLES:: 

 

sage: from sage.misc.misc import SPYX_TMP 

sage: SPYX_TMP 

l'.../temp/.../spyx' 

""" 

return os.path.join(str(SAGE_TMP), 'spyx') 

 

 

@lazy_string 

def SAGE_TMP_INTERFACE(): 

""" 

EXAMPLES:: 

 

sage: from sage.misc.misc import SAGE_TMP_INTERFACE 

sage: SAGE_TMP_INTERFACE 

l'.../temp/.../interface' 

""" 

d = os.path.join(str(SAGE_TMP), 'interface') 

sage_makedirs(d) 

return d 

 

SAGE_DB = os.path.join(DOT_SAGE, 'db') 

sage_makedirs(SAGE_DB) 

 

try: 

# Create the matplotlib config directory. 

sage_makedirs(os.environ["MPLCONFIGDIR"]) 

except KeyError: 

pass 

 

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

# Functions to help with interfacing with CXX code that 

# uses the GMP library 

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

def to_gmp_hex(n): 

from sage.misc.superseded import deprecation 

deprecation(21926, "to_gmp_hex() is deprecated") 

return hex(n).replace("L","").replace("0x","") 

 

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

# timing 

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

 

def cputime(t=0, subprocesses=False): 

""" 

Return the time in CPU seconds since Sage started, or with 

optional argument ``t``, return the time since ``t``. This is how 

much time Sage has spent using the CPU. If ``subprocesses=False`` 

this does not count time spent in subprocesses spawned by Sage 

(e.g., Gap, Singular, etc.). If ``subprocesses=True`` this 

function tries to take all subprocesses with a working 

``cputime()`` implementation into account. 

 

The measurement for the main Sage process is done via a call to 

:func:`resource.getrusage()`, so it avoids the wraparound problems in 

:func:`time.clock()` on Cygwin. 

 

INPUT: 

 

- ``t`` - (optional) time in CPU seconds, if ``t`` is a result 

from an earlier call with ``subprocesses=True``, then 

``subprocesses=True`` is assumed. 

 

- subprocesses -- (optional), include subprocesses (default: 

``False``) 

 

OUTPUT: 

 

- ``float`` - time in CPU seconds if ``subprocesses=False`` 

 

- :class:`GlobalCputime` - object which holds CPU times of 

subprocesses otherwise 

 

EXAMPLES:: 

 

sage: t = cputime() 

sage: F = gp.factor(2^199-1) 

sage: cputime(t) # somewhat random 

0.010999000000000092 

 

sage: t = cputime(subprocesses=True) 

sage: F = gp.factor(2^199-1) 

sage: cputime(t) # somewhat random 

0.091999 

 

sage: w = walltime() 

sage: F = gp.factor(2^199-1) 

sage: walltime(w) # somewhat random 

0.58425593376159668 

 

.. NOTE:: 

 

Even with ``subprocesses=True`` there is no guarantee that the 

CPU time is reported correctly because subprocesses can be 

started and terminated at any given time. 

""" 

if isinstance(t, GlobalCputime): 

subprocesses=True 

 

if not subprocesses: 

try: 

t = float(t) 

except TypeError: 

t = 0.0 

u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] 

return u+s - t 

else: 

if t == 0: 

ret = GlobalCputime(cputime()) 

for s in sage.interfaces.quit.expect_objects: 

S = s() 

if S and S.is_running(): 

try: 

ct = S.cputime() 

ret.total += ct 

ret.interfaces[s] = ct 

except NotImplementedError: 

pass 

return ret 

else: 

if not isinstance(t, GlobalCputime): 

t = GlobalCputime(t) 

ret = GlobalCputime(cputime() - t.local) 

for s in sage.interfaces.quit.expect_objects: 

S = s() 

if S and S.is_running(): 

try: 

ct = S.cputime() - t.interfaces.get(s, 0.0) 

ret.total += ct 

ret.interfaces[s] = ct 

except NotImplementedError: 

pass 

return ret 

 

class GlobalCputime: 

""" 

Container for CPU times of subprocesses. 

 

AUTHOR: 

 

- Martin Albrecht - (2008-12): initial version 

 

EXAMPLES: 

 

Objects of this type are returned if ``subprocesses=True`` is 

passed to :func:`cputime`:: 

 

sage: cputime(subprocesses=True) # indirect doctest, output random 

0.2347431 

 

We can use it to keep track of the CPU time spent in Singular for 

example:: 

 

sage: t = cputime(subprocesses=True) 

sage: P = PolynomialRing(QQ,7,'x') 

sage: I = sage.rings.ideal.Katsura(P) 

sage: gb = I.groebner_basis() # calls Singular 

sage: cputime(subprocesses=True) - t # output random 

0.462987 

 

For further processing we can then convert this container to a 

float:: 

 

sage: t = cputime(subprocesses=True) 

sage: float(t) #output somewhat random 

2.1088339999999999 

 

.. SEEALSO:: 

 

:func:`cputime` 

""" 

def __init__(self, t): 

""" 

Create a new CPU time object which also keeps track of 

subprocesses. 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import GlobalCputime 

sage: ct = GlobalCputime(0.0); ct 

0.0... 

""" 

self.total = t 

self.local = t 

self.interfaces = {} 

 

def __repr__(self): 

""" 

EXAMPLES:: 

 

sage: cputime(subprocesses=True) # indirect doctest, output random 

0.2347431 

""" 

return str(self.total) 

 

def __add__(self, other): 

""" 

EXAMPLES:: 

 

sage: t = cputime(subprocesses=True) 

sage: P = PolynomialRing(QQ,7,'x') 

sage: I = sage.rings.ideal.Katsura(P) 

sage: gb = I.groebner_basis() # calls Singular 

sage: cputime(subprocesses=True) + t # output random 

2.798708 

""" 

if not isinstance(other, GlobalCputime): 

other = GlobalCputime(other) 

ret = GlobalCputime(self.total + other.total) 

return ret 

 

def __sub__(self, other): 

""" 

EXAMPLES:: 

 

sage: t = cputime(subprocesses=True) 

sage: P = PolynomialRing(QQ,7,'x') 

sage: I = sage.rings.ideal.Katsura(P) 

sage: gb = I.groebner_basis() # calls Singular 

sage: cputime(subprocesses=True) - t # output random 

0.462987 

""" 

if not isinstance(other, GlobalCputime): 

other = GlobalCputime(other) 

ret = GlobalCputime(self.total - other.total) 

return ret 

 

def __float__(self): 

""" 

EXAMPLES:: 

 

sage: t = cputime(subprocesses=True) 

sage: float(t) #output somewhat random 

2.1088339999999999 

""" 

return float(self.total) 

 

def walltime(t=0): 

""" 

Return the wall time in second, or with optional argument t, return 

the wall time since time t. "Wall time" means the time on a wall 

clock, i.e., the actual time. 

 

INPUT: 

 

 

- ``t`` - (optional) float, time in CPU seconds 

 

OUTPUT: 

 

- ``float`` - time in seconds 

 

 

EXAMPLES:: 

 

sage: w = walltime() 

sage: F = factor(2^199-1) 

sage: walltime(w) # somewhat random 

0.8823847770690918 

""" 

return time.time() - t 

 

 

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

# simple verbosity system 

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

LEVEL=0 # default 

 

verbose_files = [] 

 

def verbose(mesg="", t=0, level=1, caller_name=None): 

""" 

Print a message if the current verbosity is at least level. 

 

INPUT: 

 

 

- ``mesg`` - str, a message to print 

 

- ``t`` - int, optional, if included, will also print 

cputime(t), - which is the time since time t. Thus t should have 

been obtained with t=cputime() 

 

- ``level`` - int, (default: 1) the verbosity level of 

what we are printing 

 

- ``caller_name`` - string (default: None), the name 

of the calling function; in most cases Python can deduce this, so 

it need not be provided. 

 

 

OUTPUT: possibly prints a message to stdout; also returns 

cputime() 

 

EXAMPLES:: 

 

sage: set_verbose(1) 

sage: t = cputime() 

sage: t = verbose("This is Sage.", t, level=1, caller_name="william") # not tested 

VERBOSE1 (william): This is Sage. (time = 0.0) 

sage: set_verbose(0) 

""" 

if level>LEVEL: 

return cputime() 

 

frame = sys._getframe(1).f_code 

file_name = frame.co_filename 

lineno = frame.co_firstlineno 

if 'all' in verbose_files or level<=0: 

show = True 

else: 

show = False 

for X in verbose_files: 

if file_name.find(X) != -1: 

show = True 

break 

 

if not show: 

return cputime() 

 

if t != 0 and mesg=="": 

mesg = "Finished." 

 

# see recipe 14.7 in Python Cookbook 

if caller_name is None: 

caller_name = frame.co_name 

if caller_name == "?: ": 

caller_name = "" 

short_file_name = os.path.split(frame.co_filename)[1] 

if '<' in short_file_name and '>' in short_file_name: 

s = "verbose %s (%s) %s"%(level, caller_name, mesg) 

else: 

s = "verbose %s (%s: %s, %s) %s"%(level, lineno, short_file_name, caller_name, mesg) 

if t!=0: 

s = s + " (time = %s)"%cputime(t) 

print(s) 

sys.stdout.flush() 

return cputime() 

 

def todo(mesg=""): 

from sage.misc.superseded import deprecation 

deprecation(21926, "todo() is deprecated") 

caller_name = sys._getframe(1).f_code.co_name 

raise NotImplementedError("{}: todo -- {}".format(caller_name, mesg)) 

 

def set_verbose(level, files='all'): 

""" 

Set the global Sage verbosity level. 

 

INPUT: 

 

- ``level`` - an integer between 0 and 2, inclusive. 

 

- ``files`` (default: 'all'): list of files to make verbose, or 

'all' to make ALL files verbose (the default). 

 

OUTPUT: changes the state of the verbosity flag and possibly 

appends to the list of files that are verbose. 

 

EXAMPLES:: 

 

sage: set_verbose(2) 

sage: verbose("This is Sage.", level=1) # not tested 

VERBOSE1 (?): This is Sage. 

sage: verbose("This is Sage.", level=2) # not tested 

VERBOSE2 (?): This is Sage. 

sage: verbose("This is Sage.", level=3) # not tested 

[no output] 

sage: set_verbose(0) 

""" 

if isinstance(level, str): 

set_verbose_files([level]) 

global LEVEL 

LEVEL = level 

if isinstance(files, str): 

files = [files] 

set_verbose_files(files) 

 

def set_verbose_files(file_name): 

""" 

 

""" 

if not isinstance(file_name, list): 

file_name = [file_name] 

global verbose_files 

verbose_files = file_name 

 

def get_verbose_files(): 

""" 

 

""" 

return verbose_files 

 

def unset_verbose_files(file_name): 

""" 

 

""" 

if not isinstance(file_name, list): 

file_name = [file_name] 

for X in file_name: 

verbose_files.remove(X) 

 

 

def get_verbose(): 

""" 

Return the global Sage verbosity level. 

 

INPUT: int level: an integer between 0 and 2, inclusive. 

 

OUTPUT: changes the state of the verbosity flag. 

 

EXAMPLES:: 

 

sage: get_verbose() 

0 

sage: set_verbose(2) 

sage: get_verbose() 

2 

sage: set_verbose(0) 

""" 

global LEVEL 

return LEVEL 

 

 

 

def generic_cmp(x,y): 

""" 

Compare x and y and return -1, 0, or 1. 

 

This is similar to x.__cmp__(y), but works even in some cases 

when a .__cmp__ method is not defined. 

""" 

from sage.misc.superseded import deprecation 

deprecation(21926, "generic_cmp() is deprecated") 

if x < y: 

return -1 

elif x == y: 

return 0 

return 1 

 

 

def cmp_props(left, right, props): 

from sage.misc.superseded import deprecation 

deprecation(23149, "cmp_props is deprecated") 

for a in props: 

lx = left.__getattribute__(a)() 

rx = right.__getattribute__(a)() 

if lx < rx: 

return -1 

elif lx > rx: 

return 1 

return 0 

 

 

def union(x, y=None): 

""" 

Return the union of x and y, as a list. The resulting list need not 

be sorted and can change from call to call. 

 

INPUT: 

 

 

- ``x`` - iterable 

 

- ``y`` - iterable (may optionally omitted) 

 

 

OUTPUT: list 

 

EXAMPLES:: 

 

sage: answer = union([1,2,3,4], [5,6]); answer 

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

sage: union([1,2,3,4,5,6], [5,6]) == answer 

True 

sage: union((1,2,3,4,5,6), [5,6]) == answer 

True 

sage: union((1,2,3,4,5,6), set([5,6])) == answer 

True 

""" 

if y is None: 

return list(set(x)) 

return list(set(x).union(y)) 

 

def uniq(x): 

""" 

Return the sublist of all elements in the list x that is sorted and 

is such that the entries in the sublist are unique. 

 

EXAMPLES:: 

 

sage: v = uniq([1,1,8,-5,3,-5,'a','x','a']) 

sage: v # potentially random ordering of output 

['a', 'x', -5, 1, 3, 8] 

sage: set(v) == set(['a', 'x', -5, 1, 3, 8]) 

True 

""" 

v = sorted(set(x)) 

return v 

 

 

def coeff_repr(c, is_latex=False): 

if not is_latex: 

try: 

return c._coeff_repr() 

except AttributeError: 

pass 

if isinstance(c, integer_types + (float,)): 

return str(c) 

if is_latex and hasattr(c, '_latex_'): 

s = c._latex_() 

else: 

s = str(c).replace(' ','') 

if s.find("+") != -1 or s.find("-") != -1: 

if is_latex: 

return "\\left(%s\\right)"%s 

else: 

return "(%s)"%s 

return s 

 

def repr_lincomb(terms, is_latex=False, scalar_mult="*", strip_one=False, repr_monomial = None, latex_scalar_mult = None): 

""" 

Compute a string representation of a linear combination of some 

formal symbols. 

 

INPUT: 

 

- ``terms`` -- list of terms, as pairs (support, coefficient) 

- ``is_latex`` -- whether to produce latex (default: ``False``) 

- ``scalar_mult`` -- string representing the multiplication (default:``'*'``) 

- ``latex_scalar_mult`` -- latex string representing the multiplication 

(default: ``''`` if ``scalar_mult`` is ``'*'``; otherwise ``scalar_mult``) 

- ``coeffs`` -- for backward compatibility 

 

OUTPUT: 

 

- ``str`` - a string 

 

EXAMPLES:: 

 

sage: repr_lincomb([('a',1), ('b',-2), ('c',3)]) 

'a - 2*b + 3*c' 

sage: repr_lincomb([('a',0), ('b',-2), ('c',3)]) 

'-2*b + 3*c' 

sage: repr_lincomb([('a',0), ('b',2), ('c',3)]) 

'2*b + 3*c' 

sage: repr_lincomb([('a',1), ('b',0), ('c',3)]) 

'a + 3*c' 

sage: repr_lincomb([('a',-1), ('b','2+3*x'), ('c',3)]) 

'-a + (2+3*x)*b + 3*c' 

sage: repr_lincomb([('a', '1+x^2'), ('b', '2+3*x'), ('c', 3)]) 

'(1+x^2)*a + (2+3*x)*b + 3*c' 

sage: repr_lincomb([('a', '1+x^2'), ('b', '-2+3*x'), ('c', 3)]) 

'(1+x^2)*a + (-2+3*x)*b + 3*c' 

sage: repr_lincomb([('a', 1), ('b', -2), ('c', -3)]) 

'a - 2*b - 3*c' 

sage: t = PolynomialRing(RationalField(),'t').gen() 

sage: repr_lincomb([('a', -t), ('s', t - 2), ('', t^2 + 2)]) 

'-t*a + (t-2)*s + (t^2+2)' 

 

Examples for ``scalar_mult``:: 

 

sage: repr_lincomb([('a',1), ('b',2), ('c',3)], scalar_mult='*') 

'a + 2*b + 3*c' 

sage: repr_lincomb([('a',2), ('b',0), ('c',-3)], scalar_mult='**') 

'2**a - 3**c' 

sage: repr_lincomb([('a',-1), ('b',2), ('c',3)], scalar_mult='**') 

'-a + 2**b + 3**c' 

 

Examples for ``scalar_mult`` and ``is_latex``:: 

 

sage: repr_lincomb([('a',-1), ('b',2), ('c',3)], is_latex=True) 

'-a + 2b + 3c' 

sage: repr_lincomb([('a',-1), ('b',-1), ('c',3)], is_latex=True, scalar_mult='*') 

'-a - b + 3c' 

sage: repr_lincomb([('a',-1), ('b',2), ('c',-3)], is_latex=True, scalar_mult='**') 

'-a + 2**b - 3**c' 

sage: repr_lincomb([('a',-2), ('b',-1), ('c',-3)], is_latex=True, latex_scalar_mult='*') 

'-2*a - b - 3*c' 

 

Examples for ``strip_one``:: 

 

sage: repr_lincomb([ ('a',1), (1,-2), ('3',3) ]) 

'a - 2*1 + 3*3' 

sage: repr_lincomb([ ('a',-1), (1,1), ('3',3) ]) 

'-a + 1 + 3*3' 

sage: repr_lincomb([ ('a',1), (1,-2), ('3',3) ], strip_one = True) 

'a - 2 + 3*3' 

sage: repr_lincomb([ ('a',-1), (1,1), ('3',3) ], strip_one = True) 

'-a + 1 + 3*3' 

sage: repr_lincomb([ ('a',1), (1,-1), ('3',3) ], strip_one = True) 

'a - 1 + 3*3' 

 

Examples for ``repr_monomial``:: 

 

sage: repr_lincomb([('a',1), ('b',2), ('c',3)], repr_monomial = lambda s: s+"1") 

'a1 + 2*b1 + 3*c1' 

""" 

# Setting scalar_mult: symbol used for scalar multiplication 

if is_latex: 

if latex_scalar_mult is not None: 

scalar_mult = latex_scalar_mult 

elif scalar_mult == "*": 

scalar_mult = "" 

 

if repr_monomial is None: 

if is_latex: 

repr_monomial = lambda monomial: monomial._latex_() if hasattr(monomial, '_latex_') else str(monomial) 

else: 

repr_monomial = str 

 

s = "" 

first = True 

 

if scalar_mult is None: 

scalar_mult = "" if is_latex else "*" 

 

for (monomial,c) in terms: 

if c != 0: 

coeff = coeff_repr(c) 

negative = False 

if len(coeff)>0 and coeff[0] == "-": 

negative = True 

try: 

if c < 0: 

negative = True 

except NotImplementedError: 

# comparisons may not be implemented for some coefficients 

pass 

if negative: 

coeff = coeff_repr(-c, is_latex) 

else: 

coeff = coeff_repr(c, is_latex) 

if coeff == "1": 

coeff = "" 

if coeff != "0": 

if negative: 

if first: 

sign = "-" # add trailing space? 

else: 

sign = " - " 

else: 

if first: 

sign = "" 

else: 

sign= " + " 

b = repr_monomial(monomial) 

if len(b) > 0: 

if coeff != "": 

if b =="1" and strip_one: 

b = "" 

else: 

b = scalar_mult + b 

s += "%s%s%s"%(sign, coeff, b) 

first = False 

if first: 

return "0" # this can happen only if are only terms with coeff_repr(c) == "0" 

#elif s == "": 

#return "1" # is empty string representation invalid? 

else: 

return s 

 

 

def strunc(s, n = 60): 

""" 

Truncate at first space after position n, adding '...' if 

nontrivial truncation. 

""" 

n = int(n) 

s = str(s) 

if len(s) > n: 

i = n 

while i < len(s) and s[i] != ' ': 

i += 1 

return s[:i] + " ..." 

#return s[:n-4] + " ..." 

return s 

 

 

 

def newton_method_sizes(N): 

r""" 

Returns a sequence of integers 

`1 = a_1 \leq a_2 \leq \cdots \leq a_n = N` such that 

`a_j = \lceil a_{j+1} / 2 \rceil` for all `j`. 

 

This is useful for Newton-style algorithms that double the 

precision at each stage. For example if you start at precision 1 

and want an answer to precision 17, then it's better to use the 

intermediate stages 1, 2, 3, 5, 9, 17 than to use 1, 2, 4, 8, 16, 

17. 

 

INPUT: 

 

 

- ``N`` - positive integer 

 

 

EXAMPLES:: 

 

sage: newton_method_sizes(17) 

[1, 2, 3, 5, 9, 17] 

sage: newton_method_sizes(16) 

[1, 2, 4, 8, 16] 

sage: newton_method_sizes(1) 

[1] 

 

AUTHORS: 

 

- David Harvey (2006-09-09) 

""" 

 

N = int(N) 

if N < 1: 

raise ValueError("N (={}) must be a positive integer".format(N)) 

 

output = [] 

while N > 1: 

output.append(N) 

N = (N + 1) >> 1 

 

output.append(1) 

output.reverse() 

return output 

 

 

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

# Generally useful 

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

 

 

def assert_attribute(x, attr, init=None): 

""" 

If the object x has the attribute attr, do nothing. If not, set 

x.attr to init. 

""" 

from sage.misc.superseded import deprecation 

deprecation(21926, "assert_attribute() is deprecated") 

if attr in x.__dict__: return 

if attr[:2] == "__": 

z = str(x.__class__).split("'") 

if len(z) > 1: 

z = z[1] 

else: 

z = z[0] 

attr = "_" + z[len(x.__module__)+1:] + attr 

x.__dict__[attr] = init 

 

 

def compose(f, g): 

""" 

Return the composition of one-variable functions: `f \circ g` 

 

See also :func:`nest()` 

 

INPUT: 

- `f` -- a function of one variable 

- `g` -- another function of one variable 

 

OUTPUT: 

A function, such that compose(f,g)(x) = f(g(x)) 

 

EXAMPLES:: 

 

sage: def g(x): return 3*x 

sage: def f(x): return x + 1 

sage: h1 = compose(f,g) 

sage: h2 = compose(g,f) 

sage: _ = var ('x') 

sage: h1(x) 

3*x + 1 

sage: h2(x) 

3*x + 3 

 

:: 

 

sage: _ = function('f g') 

sage: _ = var ('x') 

sage: compose(f,g)(x) 

f(g(x)) 

 

""" 

return lambda x: f(g(x)) 

 

 

def self_compose(f, n): 

""" 

Return the function `f` composed with itself `n` times. 

 

See :func:`nest()` if you want `f(f(...(f(x))...))` for 

known `x`. 

 

 

INPUT: 

- `f` -- a function of one variable 

- `n` -- a nonnegative integer 

 

OUTPUT: 

A function, the result of composing `f` with itself `n` times 

 

EXAMPLES:: 

 

sage: def f(x): return x^2 + 1 

sage: g = self_compose(f, 3) 

doctest:... DeprecationWarning: self_compose() is deprecated, use nest() instead 

See http://trac.sagemath.org/21926 for details. 

sage: x = var('x') 

sage: g(x) 

((x^2 + 1)^2 + 1)^2 + 1 

 

:: 

 

sage: def f(x): return x + 1 

sage: g = self_compose(f, 10000) 

sage: g(0) 

10000 

 

:: 

 

sage: x = var('x') 

sage: self_compose(sin, 0)(x) 

x 

 

""" 

from sage.misc.superseded import deprecation 

deprecation(21926, "self_compose() is deprecated, use nest() instead") 

from sage.rings.all import Integer 

n = Integer(n) 

 

if n < 0: 

raise ValueError("n must be a nonnegative integer, not {}.".format(n)) 

 

return lambda x: nest(f, n, x) 

 

 

def nest(f, n, x): 

""" 

Return `f(f(...f(x)...))`, where the composition occurs n times. 

 

See also :func:`compose()` and :func:`self_compose()` 

 

INPUT: 

- `f` -- a function of one variable 

- `n` -- a nonnegative integer 

- `x` -- any input for `f` 

 

OUTPUT: 

`f(f(...f(x)...))`, where the composition occurs n times 

 

EXAMPLES:: 

 

sage: def f(x): return x^2 + 1 

sage: x = var('x') 

sage: nest(f, 3, x) 

((x^2 + 1)^2 + 1)^2 + 1 

 

:: 

 

sage: _ = function('f') 

sage: _ = var('x') 

sage: nest(f, 10, x) 

f(f(f(f(f(f(f(f(f(f(x)))))))))) 

 

:: 

 

sage: _ = function('f') 

sage: _ = var('x') 

sage: nest(f, 0, x) 

x 

 

""" 

from sage.rings.all import Integer 

n = Integer(n) 

 

if n < 0: 

raise ValueError("n must be a nonnegative integer, not {}.".format(n)) 

 

for i in range(n): 

x = f(x) 

return x 

 

 

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

# The A \ b operator 

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

 

class BackslashOperator: 

""" 

Implements Matlab-style backslash operator for solving systems:: 

 

A \\ b 

 

The preparser converts this to multiplications using 

``BackslashOperator()``. 

 

EXAMPLES:: 

 

sage: preparse("A \ matrix(QQ,2,1,[1/3,'2/3'])") 

"A * BackslashOperator() * matrix(QQ,Integer(2),Integer(1),[Integer(1)/Integer(3),'2/3'])" 

sage: preparse("A \ matrix(QQ,2,1,[1/3,2*3])") 

'A * BackslashOperator() * matrix(QQ,Integer(2),Integer(1),[Integer(1)/Integer(3),Integer(2)*Integer(3)])' 

sage: preparse("A \ B + C") 

'A * BackslashOperator() * B + C' 

sage: preparse("A \ eval('C+D')") 

"A * BackslashOperator() * eval('C+D')" 

sage: preparse("A \ x / 5") 

'A * BackslashOperator() * x / Integer(5)' 

sage: preparse("A^3 \ b") 

'A**Integer(3) * BackslashOperator() * b' 

""" 

def __rmul__(self, left): 

""" 

EXAMPLES:: 

 

sage: A = random_matrix(ZZ, 4) 

sage: B = random_matrix(ZZ, 4) 

sage: temp = A * BackslashOperator() 

sage: temp.left is A 

True 

sage: X = temp * B 

sage: A * X == B 

True 

""" 

self.left = left 

return self 

 

def __mul__(self, right): 

""" 

EXAMPLES:: 

 

sage: A = matrix(RDF, 5, 5, 2) 

sage: b = vector(RDF, 5, range(5)) 

sage: v = A \ b 

sage: v.zero_at(1e-19) # On at least one platform, we get a "negative zero" 

(0.0, 0.5, 1.0, 1.5, 2.0) 

sage: v = A._backslash_(b) 

sage: v.zero_at(1e-19) 

(0.0, 0.5, 1.0, 1.5, 2.0) 

sage: v = A * BackslashOperator() * b 

sage: v.zero_at(1e-19) 

(0.0, 0.5, 1.0, 1.5, 2.0) 

""" 

return self.left._backslash_(right) 

 

 

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

# is_iterator function 

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

def is_iterator(it): 

""" 

Tests if it is an iterator. 

 

The mantra ``if hasattr(it, 'next')`` was used to tests if ``it`` is an 

iterator. This is not quite correct since ``it`` could have a ``next`` 

methods with a different semantic. 

 

EXAMPLES:: 

 

sage: it = iter([1,2,3]) 

sage: is_iterator(it) 

True 

 

sage: class wrong(): 

....: def __init__(self): self.n = 5 

....: def next(self): 

....: self.n -= 1 

....: if self.n == 0: raise StopIteration 

....: return self.n 

sage: x = wrong() 

sage: is_iterator(x) 

False 

sage: list(x) 

Traceback (most recent call last): 

... 

TypeError: iteration over non-sequence 

 

sage: class good(wrong): 

....: def __iter__(self): return self 

sage: x = good() 

sage: is_iterator(x) 

True 

sage: list(x) 

[4, 3, 2, 1] 

 

sage: P = Partitions(3) 

sage: is_iterator(P) 

False 

sage: is_iterator(iter(P)) 

True 

""" 

# see trac #7398 for a discussion 

try: 

return it is iter(it) 

except Exception: 

return False 

 

 

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

# Useful but hard to classify 

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

 

 

def random_sublist(X, s): 

""" 

Return a pseudo-random sublist of the list X where the probability 

of including a particular element is s. 

 

INPUT: 

 

 

- ``X`` - list 

 

- ``s`` - floating point number between 0 and 1 

 

 

OUTPUT: list 

 

EXAMPLES:: 

 

sage: S = [1,7,3,4,18] 

sage: random_sublist(S, 0.5) 

[1, 3, 4] 

sage: random_sublist(S, 0.5) 

[1, 3] 

""" 

return [a for a in X if random.random() <= s] 

 

 

def some_tuples(elements, repeat, bound, max_samples=None): 

r""" 

Return an iterator over at most ``bound`` number of ``repeat``-tuples of 

``elements``. 

 

INPUT: 

 

- ``elements`` -- an iterable 

- ``repeat`` -- integer (default ``None``), the length of the tuples to be returned. 

If ``None``, just returns entries from ``elements``. 

- ``bound`` -- the maximum number of tuples returned (ignored if ``max_samples`` given) 

- ``max_samples`` -- non-negative integer (default ``None``). If given, 

then a sample of the possible tuples will be returned, 

instead of the first few in the standard order. 

 

OUTPUT: 

 

If ``max_samples`` is not provided, an iterator over the first 

``bound`` tuples of length ``repeat``, in the standard nested-for-loop order. 

 

If ``max_samples`` is provided, a list of at most ``max_samples`` tuples, 

sampled uniformly from the possibilities. In this case, ``elements`` 

must be finite. 

 

TESTS:: 

 

sage: from sage.misc.misc import some_tuples 

sage: l = some_tuples([0,1,2,3], 2, 3) 

sage: l 

<itertools.islice object at ...> 

sage: len(list(l)) 

3 

 

sage: l = some_tuples(range(50), 3, 10) 

sage: len(list(l)) 

10 

 

sage: l = some_tuples(range(3), 2, None, max_samples=10) 

sage: len(list(l)) 

9 

""" 

if max_samples is None: 

from itertools import islice, product 

P = elements if repeat is None else product(elements, repeat=repeat) 

return islice(P, bound) 

else: 

if not (hasattr(elements, '__len__') and hasattr(elements, '__getitem__')): 

elements = list(elements) 

n = len(elements) 

N = n if repeat is None else n**repeat 

if N <= max_samples: 

from itertools import product 

return elements if repeat is None else product(elements, repeat=repeat) 

return _some_tuples_sampling(elements, repeat, max_samples, n) 

 

def _some_tuples_sampling(elements, repeat, max_samples, n): 

""" 

Internal function for :func:`some_tuples`. 

 

TESTS:: 

 

sage: from sage.misc.misc import _some_tuples_sampling 

sage: list(_some_tuples_sampling(range(3), 3, 2, 3)) 

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

sage: list(_some_tuples_sampling(range(20), None, 4, 20)) 

[0, 6, 9, 3] 

""" 

from sage.rings.integer import Integer 

N = n if repeat is None else n**repeat 

# We sample on range(N) and create tuples manually since we don't want to create the list of all possible tuples in memory 

for a in random.sample(range(N), max_samples): 

if repeat is None: 

yield elements[a] 

else: 

yield tuple(elements[j] for j in Integer(a).digits(n, padto=repeat)) 

 

def powerset(X): 

r""" 

Iterator over the *list* of all subsets of the iterable X, in no 

particular order. Each list appears exactly once, up to order. 

 

INPUT: 

 

 

- ``X`` - an iterable 

 

 

OUTPUT: iterator of lists 

 

EXAMPLES:: 

 

sage: list(powerset([1,2,3])) 

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

sage: [z for z in powerset([0,[1,2]])] 

[[], [0], [[1, 2]], [0, [1, 2]]] 

 

Iterating over the power set of an infinite set is also allowed:: 

 

sage: i = 0 

sage: L = [] 

sage: for x in powerset(ZZ): 

....: if i > 10: 

....: break 

....: else: 

....: i += 1 

....: L.append(x) 

sage: print(" ".join(str(x) for x in L)) 

[] [0] [1] [0, 1] [-1] [0, -1] [1, -1] [0, 1, -1] [2] [0, 2] [1, 2] 

 

You may also use subsets as an alias for powerset:: 

 

sage: subsets([1,2,3]) 

<generator object powerset at 0x...> 

sage: list(subsets([1,2,3])) 

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

 

The reason we return lists instead of sets is that the elements of 

sets must be hashable and many structures on which one wants the 

powerset consist of non-hashable objects. 

 

 

AUTHORS: 

 

- William Stein 

 

- Nils Bruin (2006-12-19): rewrite to work for not-necessarily 

finite objects X. 

""" 

yield [] 

pairs = [] 

for x in X: 

pairs.append((2**len(pairs),x)) 

for w in range(2**(len(pairs)-1), 2**(len(pairs))): 

yield [x for m, x in pairs if m & w] 

 

subsets = powerset 

 

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

# Type checking 

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

def typecheck(x, C, var="x"): 

""" 

Check that x is of instance C. If not raise a TypeError with an 

error message. 

""" 

from sage.misc.superseded import deprecation 

deprecation(21926, "typecheck is deprecated, use isinstance instead") 

if not isinstance(x, C): 

raise TypeError("{} (={}) must be of type {}.".format(var, x, C)) 

 

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

# This will likely eventually be useful. 

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

 

# From the Python Cookbook Ver 2, Recipe 20.4 

class cached_attribute(object): 

""" 

Computes attribute value and caches it in the instance. 

""" 

def __init__(self, method, name=None): 

from sage.misc.superseded import deprecation 

deprecation(21926, "cached_attribute is deprecated") 

# record the unbound-method and the name 

self.method = method 

self.name = name or method.__name__ 

def __get__(self, inst, cls): 

if inst is None: 

# instance attribute accessed on class, return self 

return self 

# compute, cache and return the instance's attribute value 

result = self.method(inst) 

setattr(inst, self.name, result) 

return result 

 

class lazy_prop(object): 

def __init__(self, calculate_function): 

from sage.misc.superseded import deprecation 

deprecation(21926, "lazy_prop is deprecated") 

self._calculate = calculate_function 

self.__doc__ = calculate_function.__doc__ 

 

def __call__(self, obj, _=None): 

if obj is None: 

return self 

value = self._calculate(obj) 

setattr(obj, self._calculate.__name__, value) 

return value 

 

def prop(f): 

from sage.misc.superseded import deprecation 

deprecation(21926, "prop() is deprecated") 

return property(f, None, None, f.__doc__) 

 

 

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

# Misc. 

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

 

def exists(S, P): 

""" 

If S contains an element x such that P(x) is True, this function 

returns True and the element x. Otherwise it returns False and 

None. 

 

Note that this function is NOT suitable to be used in an 

if-statement or in any place where a boolean expression is 

expected. For those situations, use the Python built-in 

 

any(P(x) for x in S) 

 

INPUT: 

 

 

- ``S`` - object (that supports enumeration) 

 

- ``P`` - function that returns True or False 

 

 

OUTPUT: 

 

 

- ``bool`` - whether or not P is True for some element 

x of S 

 

- ``object`` - x 

 

 

EXAMPLES: lambda functions are very useful when using the exists 

function:: 

 

sage: exists([1,2,5], lambda x : x > 7) 

(False, None) 

sage: exists([1,2,5], lambda x : x > 3) 

(True, 5) 

 

The following example is similar to one in the MAGMA handbook. We 

check whether certain integers are a sum of two (small) cubes:: 

 

sage: cubes = [t**3 for t in range(-10,11)] 

sage: exists([(x,y) for x in cubes for y in cubes], lambda v : v[0]+v[1] == 218) 

(True, (-125, 343)) 

sage: exists([(x,y) for x in cubes for y in cubes], lambda v : v[0]+v[1] == 219) 

(False, None) 

""" 

for x in S: 

if P(x): return True, x 

return False, None 

 

def forall(S, P): 

""" 

If P(x) is true every x in S, return True and None. If there is 

some element x in S such that P is not True, return False and x. 

 

Note that this function is NOT suitable to be used in an 

if-statement or in any place where a boolean expression is 

expected. For those situations, use the Python built-in 

 

all(P(x) for x in S) 

 

INPUT: 

 

 

- ``S`` - object (that supports enumeration) 

 

- ``P`` - function that returns True or False 

 

 

OUTPUT: 

 

 

- ``bool`` - whether or not P is True for all elements 

of S 

 

- ``object`` - x 

 

 

EXAMPLES: lambda functions are very useful when using the forall 

function. As a toy example we test whether certain integers are 

greater than 3. 

 

:: 

 

sage: forall([1,2,5], lambda x : x > 3) 

(False, 1) 

sage: forall([1,2,5], lambda x : x > 0) 

(True, None) 

 

Next we ask whether every positive integer less than 100 is a 

product of at most 2 prime factors:: 

 

sage: forall(range(1,100), lambda n : len(factor(n)) <= 2) 

(False, 30) 

 

The answer is no, and 30 is a counterexample. However, every 

positive integer 100 is a product of at most 3 primes. 

 

:: 

 

sage: forall(range(1,100), lambda n : len(factor(n)) <= 3) 

(True, None) 

""" 

for x in S: 

if not P(x): return False, x 

return True, None 

 

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

# which source file? 

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

import inspect 

def sourcefile(object): 

""" 

Work out which source or compiled file an object was defined in. 

""" 

from sage.misc.superseded import deprecation 

deprecation(21926, "sourcefile(x) is deprecated, use inspect.getfile(x) instead") 

return inspect.getfile(object) 

 

 

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

# debug tracing 

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

import pdb 

set_trace = pdb.set_trace 

 

 

 

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

# Word wrap lines 

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

def word_wrap(s, ncols=85): 

t = [] 

if ncols == 0: 

return s 

for x in s.split('\n'): 

if len(x) == 0 or x.lstrip()[:5] == 'sage:': 

t.append(x) 

continue 

while len(x) > ncols: 

k = ncols 

while k > 0 and x[k] != ' ': 

k -= 1 

if k == 0: 

k = ncols 

end = '\\' 

else: 

end = '' 

t.append(x[:k] + end) 

x = x[k:] 

k=0 

while k < len(x) and x[k] == ' ': 

k += 1 

x = x[k:] 

t.append(x) 

return '\n'.join(t) 

 

 

def getitem(v, n): 

r""" 

Variant of getitem that coerces to an int if a TypeError is 

raised. 

 

(This is not needed anymore - classes should define an 

__index__ method.) 

 

Thus, e.g., ``getitem(v,n)`` will work even if 

`v` is a Python list and `n` is a Sage integer. 

 

EXAMPLES:: 

 

sage: v = [1,2,3] 

 

The following used to fail in Sage <= 1.3.7. Now it works fine:: 

 

sage: v[ZZ(1)] 

2 

 

This always worked. 

 

:: 

 

sage: getitem(v, ZZ(1)) 

doctest:... DeprecationWarning: getitem(v, n) is deprecated, use v[n] instead 

See http://trac.sagemath.org/21926 for details. 

2 

""" 

from sage.misc.superseded import deprecation 

deprecation(21926, "getitem(v, n) is deprecated, use v[n] instead") 

try: 

return v[n] 

except TypeError: 

return v[int(n)] 

 

def pad_zeros(s, size=3): 

""" 

EXAMPLES:: 

 

sage: pad_zeros(100) 

'100' 

sage: pad_zeros(10) 

'010' 

sage: pad_zeros(10, 5) 

'00010' 

sage: pad_zeros(389, 5) 

'00389' 

sage: pad_zeros(389, 10) 

'0000000389' 

""" 

return "0"*(size-len(str(s))) + str(s) 

 

import sage.server.support 

 

def embedded(): 

""" 

Return True if this copy of Sage is running embedded in the Sage 

notebook. 

 

EXAMPLES:: 

 

sage: sage.misc.misc.embedded() # output True if in the notebook 

False 

""" 

return sage.server.support.EMBEDDED_MODE 

 

 

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

# Operators 

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

class AttrCallObject(object): 

def __init__(self, name, args, kwds): 

""" 

TESTS:: 

 

sage: f = attrcall('core', 3); f 

*.core(3) 

sage: TestSuite(f).run() 

""" 

self.name = name 

self.args = args 

self.kwds = kwds 

 

def __call__(self, x, *args): 

""" 

Gets the ``self.name`` method from ``x``, calls it with 

``self.args`` and ``args`` as positional parameters and 

``self.kwds`` as keyword parameters, and returns the result. 

 

EXAMPLES:: 

 

sage: core = attrcall('core', 3) 

sage: core(Partition([4,2])) 

[4, 2] 

 

sage: series = attrcall('series', x) 

sage: series(sin(x), 4) 

1*x + (-1/6)*x^3 + Order(x^4) 

""" 

return getattr(x, self.name)(*(self.args+args), **self.kwds) 

 

def __repr__(self): 

""" 

Returns a string representation of this object. The star in the 

output represents the object passed into self. 

 

EXAMPLES:: 

 

sage: attrcall('core', 3) 

*.core(3) 

sage: attrcall('hooks', flatten=True) 

*.hooks(flatten=True) 

sage: attrcall('hooks', 3, flatten=True) 

*.hooks(3, flatten=True) 

""" 

s = "*.%s(%s"%(self.name, ", ".join(map(repr, self.args))) 

if self.kwds: 

if len(self.args) > 0: 

s += ", " 

s += ", ".join("%s=%s"%keyvalue for keyvalue in self.kwds.items()) 

s += ")" 

return s 

 

def __eq__(self, other): 

""" 

Equality testing 

 

EXAMPLES:: 

 

sage: attrcall('core', 3, flatten = True) == attrcall('core', 3, flatten = True) 

True 

sage: attrcall('core', 2) == attrcall('core', 3) 

False 

sage: attrcall('core', 2) == 1 

False 

""" 

return self.__class__ == other.__class__ and self.__dict__ == other.__dict__ 

 

def __ne__(self, other): 

""" 

Equality testing 

 

EXAMPLES:: 

 

sage: attrcall('core', 3, flatten = True) != attrcall('core', 3, flatten = True) 

False 

sage: attrcall('core', 2) != attrcall('core', 3) 

True 

sage: attrcall('core', 2) != 1 

True 

""" 

return not self == other 

 

def __hash__(self): 

""" 

Hash value 

 

This method tries to ensure that, when two ``attrcall`` 

objects are equal, they have the same hash value. 

 

.. warning:: dicts are not hashable, so we instead hash their 

items; however the order of those items might differ. The 

proper fix would be to use a frozen dict for ``kwds``, when 

frozen dicts will be available in Python. 

 

EXAMPLES:: 

 

sage: x = attrcall('core', 3, flatten = True, blah = 1) 

sage: hash(x) # random # indirect doctest 

210434060 

sage: type(hash(x)) 

<... 'int'> 

sage: y = attrcall('core', 3, blah = 1, flatten = True) 

sage: hash(y) == hash(x) 

True 

sage: y = attrcall('core', 3, flatten = True, blah = 2) 

sage: hash(y) != hash(x) 

True 

sage: hash(attrcall('core', 2)) != hash(attrcall('core', 3)) 

True 

sage: hash(attrcall('core', 2)) != hash(1) 

True 

 

Note: a missing ``__hash__`` method here used to break the 

unique representation of parents taking ``attrcall`` objects 

as input; see :trac:`8911`. 

""" 

return hash((self.args, tuple(self.kwds.items()))) 

 

def attrcall(name, *args, **kwds): 

""" 

Returns a callable which takes in an object, gets the method named 

name from that object, and calls it with the specified arguments 

and keywords. 

 

INPUT: 

 

- ``name`` - a string of the name of the method you 

want to call 

 

- ``args, kwds`` - arguments and keywords to be passed 

to the method 

 

EXAMPLES:: 

 

sage: f = attrcall('core', 3); f 

*.core(3) 

sage: [f(p) for p in Partitions(5)] 

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

""" 

return AttrCallObject(name, args, kwds) 

 

def call_method(obj, name, *args, **kwds): 

""" 

Call the method ``name`` on ``obj``. 

 

This has to exist somewhere in Python!!! 

 

.. SEEALSO:: :func:`operator.methodcaller` :func:`attrcal` 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import call_method 

sage: call_method(1, "__add__", 2) 

3 

""" 

return getattr(obj, name)(*args, **kwds) 

 

def is_in_string(line, pos): 

r""" 

Returns True if the character at position pos in line occurs 

within a string. 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import is_in_string 

sage: line = 'test(\'#\')' 

sage: is_in_string(line, line.rfind('#')) 

True 

sage: is_in_string(line, line.rfind(')')) 

False 

""" 

i = 0 

in_single_quote = False 

in_double_quote = False 

in_triple_quote = False 

 

def in_quote(): 

return in_single_quote or in_double_quote or in_triple_quote 

 

while i < pos: 

# Update quote parsing 

# We only do this if this quote isn't backquoted itself, 

# which is the case if the previous character isn't 

# a backslash, or it is but both previous characters 

# are backslashes. 

if line[i-1:i] != '\\' or line[i-2:i] == '\\\\': 

if line[i:i+3] in ['"""', "'''"]: 

if not in_quote(): 

in_triple_quote = True 

elif in_triple_quote: 

in_triple_quote = False 

elif line[i] == "'": 

if not in_quote(): 

in_single_quote = True 

elif in_single_quote: 

in_single_quote = False 

elif line[i] == '"': 

if not in_quote(): 

in_double_quote = True 

elif in_double_quote: 

in_double_quote = False 

i += 1 

return in_quote() 

 

 

def get_main_globals(): 

""" 

Return the main global namespace. 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import get_main_globals 

sage: G = get_main_globals() 

sage: bla = 1 

sage: G['bla'] 

1 

sage: bla = 2 

sage: G['bla'] 

2 

sage: G['ble'] = 5 

sage: ble 

5 

 

This is analogous to :func:`globals`, except that it can be called 

from any function, even if it is in a Python module:: 

 

sage: def f(): 

....: G = get_main_globals() 

....: assert G['bli'] == 14 

....: G['blo'] = 42 

sage: bli = 14 

sage: f() 

sage: blo 

42 

 

ALGORITHM: 

 

The main global namespace is discovered by going up the frame 

stack until the frame for the :mod:`__main__` module is found. 

Should this frame not be found (this should not occur in normal 

operation), an exception "ValueError: call stack is not deep 

enough" will be raised by ``_getframe``. 

 

See :meth:`inject_variable_test` for a real test that this works 

within deeply nested calls in a function defined in a Python 

module. 

""" 

import sys 

depth = 0 

while True: 

G = sys._getframe(depth).f_globals 

if G.get("__name__", None) == "__main__": 

break 

depth += 1 

return G 

 

 

def inject_variable(name, value, warn=True): 

""" 

Inject a variable into the main global namespace. 

 

INPUT: 

 

- ``name`` -- a string 

- ``value`` -- anything 

- ``warn`` -- a boolean (default: :obj:`False`) 

 

EXAMPLES:: 

 

sage: from sage.misc.misc import inject_variable 

sage: inject_variable("a", 314) 

sage: a 

314 

 

A warning is issued the first time an existing value is overwritten:: 

 

sage: inject_variable("a", 271) 

doctest:...: RuntimeWarning: redefining global value `a` 

sage: a 

271 

sage: inject_variable("a", 272) 

sage: a 

272 

 

That's because warn seem to not reissue twice the same warning: 

 

sage: from warnings import warn 

sage: warn("blah") 

doctest:...: UserWarning: blah 

sage: warn("blah") 

 

Warnings can be disabled:: 

 

sage: b = 3 

sage: inject_variable("b", 42, warn=False) 

sage: b 

42 

 

Use with care! 

""" 

assert isinstance(name, str) 

# Using globals() does not work, even in Cython, because 

# inject_variable is called not only from the interpreter, but 

# also from functions in various modules. 

G = get_main_globals() 

if name in G and warn: 

warnings.warn("redefining global value `%s`"%name, RuntimeWarning, stacklevel = 2) 

G[name] = value 

 

 

def inject_variable_test(name, value, depth): 

""" 

A function for testing deep calls to inject_variable 

 

TESTS:: 

 

sage: from sage.misc.misc import inject_variable_test 

sage: inject_variable_test("a0", 314, 0) 

sage: a0 

314 

sage: inject_variable_test("a1", 314, 1) 

sage: a1 

314 

sage: inject_variable_test("a2", 314, 2) 

sage: a2 

314 

sage: inject_variable_test("a2", 271, 2) 

doctest:...: RuntimeWarning: redefining global value `a2` 

sage: a2 

271 

 

""" 

if depth == 0: 

inject_variable(name, value) 

else: 

inject_variable_test(name, value, depth - 1)