Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

""" 

Pynac interface 

""" 

  

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

# Copyright (C) 2008 William Stein <wstein@gmail.com> 

# Copyright (C) 2008 Burcin Erocal <burcin@erocal.org> 

# Copyright (C) 2017 Jeroen Demeyer <jdemeyer@cage.ugent.be> 

# 

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

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

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

# (at your option) any later version. 

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

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

from __future__ import absolute_import, division, print_function 

  

from cpython cimport * 

from libc cimport math 

  

from sage.ext.stdsage cimport PY_NEW 

from sage.libs.gmp.all cimport * 

from sage.libs.gsl.types cimport * 

from sage.libs.gsl.complex cimport * 

from sage.libs.gsl.gamma cimport gsl_sf_lngamma_complex_e 

from sage.libs.mpmath import utils as mpmath_utils 

from sage.libs.pari.all import pari 

  

from sage.cpython.string cimport str_to_bytes, char_to_str 

  

from sage.arith.all import gcd, lcm, is_prime, factorial, bernoulli 

  

from sage.structure.element cimport Element, parent, coercion_model 

from sage.structure.sage_object import loads, dumps 

  

from sage.rings.integer_ring import ZZ 

from sage.rings.integer cimport Integer, smallInteger 

from sage.rings.rational cimport Rational 

from sage.rings.real_mpfr import RR, RealField 

from sage.rings.rational cimport rational_power_parts 

from sage.rings.real_double cimport RealDoubleElement 

from sage.rings.all import CC 

  

from sage.symbolic.expression cimport Expression, new_Expression_from_GEx 

from sage.symbolic.function import get_sfunction_from_serial 

from sage.symbolic.function cimport Function 

from sage.symbolic.substitution_map cimport new_SubstitutionMap_from_GExMap 

from sage.symbolic import ring 

  

from .constant cimport PynacConstant 

  

  

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

# Symbolic function helpers 

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

  

cdef ex_to_pyExpression(GEx juice): 

""" 

Convert given GiNaC::ex object to a python Expression instance. 

  

Used to pass parameters to custom power and series functions. 

""" 

cdef Expression nex 

nex = <Expression>Expression.__new__(Expression) 

nex._gobj = GEx(juice) 

nex._parent = ring.SR 

return nex 

  

cdef exprseq_to_PyTuple(GEx seq): 

""" 

Convert an exprseq to a Python tuple. 

  

Used while converting arguments of symbolic functions to Python objects. 

  

EXAMPLES:: 

  

sage: from sage.symbolic.function import BuiltinFunction 

sage: class TFunc(BuiltinFunction): 

....: def __init__(self): 

....: BuiltinFunction.__init__(self, 'tfunc', nargs=0) 

....: 

....: def _eval_(self, *args): 

....: print("len(args): %s, types: %s"%(len(args), str(list(map(type, args))))) 

....: for i, a in enumerate(args): 

....: if isinstance(a, tuple): 

....: print("argument %s is a tuple, with types %s"%(str(i), str(list(map(type, a))))) 

....: 

sage: tfunc = TFunc() 

sage: u = SR._force_pyobject((1, x+1, 2)) 

sage: tfunc(u, x, SR._force_pyobject((3.0, 2^x))) 

len(args): 3, types: [<... 'tuple'>, <type 'sage.symbolic.expression.Expression'>, <... 'tuple'>] 

argument 0 is a tuple, with types [<type 'sage.rings.integer.Integer'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.rings.integer.Integer'>] 

argument 2 is a tuple, with types [<type 'sage.rings.real_mpfr.RealLiteral'>, <type 'sage.symbolic.expression.Expression'>] 

tfunc((1, x + 1, 2), x, (3.00000000000000, 2^x)) 

""" 

from sage.symbolic.ring import SR 

res = [] 

for i in range(seq.nops()): 

if is_a_numeric(seq.op(i)): 

res.append(py_object_from_numeric(seq.op(i))) 

elif is_exactly_a_exprseq(seq.op(i)): 

res.append(exprseq_to_PyTuple(seq.op(i))) 

else: 

res.append(new_Expression_from_GEx(SR, seq.op(i))) 

return tuple(res) 

  

def unpack_operands(Expression ex): 

""" 

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import unpack_operands 

sage: t = SR._force_pyobject((1, 2, x, x+1, x+2)) 

sage: unpack_operands(t) 

(1, 2, x, x + 1, x + 2) 

sage: type(unpack_operands(t)) 

<... 'tuple'> 

sage: list(map(type, unpack_operands(t))) 

[<type 'sage.rings.integer.Integer'>, <type 'sage.rings.integer.Integer'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.symbolic.expression.Expression'>] 

sage: u = SR._force_pyobject((t, x^2)) 

sage: unpack_operands(u) 

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

sage: type(unpack_operands(u)[0]) 

<... 'tuple'> 

""" 

return exprseq_to_PyTuple(ex._gobj) 

  

cdef exvector_to_PyTuple(GExVector seq): 

""" 

Converts arguments list given to a function to a PyTuple. 

  

Used to pass arguments to python methods assigned to custom 

evaluation, derivative, etc. functions of symbolic functions. 

  

We convert Python objects wrapped in symbolic expressions back to regular 

Python objects. 

  

EXAMPLES:: 

  

sage: from sage.symbolic.function import BuiltinFunction 

sage: class TFunc(BuiltinFunction): 

....: def __init__(self): 

....: BuiltinFunction.__init__(self, 'tfunc', nargs=0) 

....: 

....: def _eval_(self, *args): 

....: print("len(args): %s, types: %s"%(len(args), str(list(map(type, args))))) 

sage: tfunc = TFunc() 

sage: u = SR._force_pyobject((1, x+1, 2)) 

sage: tfunc(u, x, 3.0, 5.0r) 

len(args): 4, types: [<... 'tuple'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.rings.real_mpfr.RealLiteral'>, <... 'float'>] 

tfunc((1, x + 1, 2), x, 3.00000000000000, 5.0) 

  

TESTS: 

  

Check if symbolic functions in the arguments are preserved:: 

  

sage: tfunc(sin(x), tfunc(1, x^2)) 

len(args): 2, types: [<type 'sage.rings.integer.Integer'>, <type 'sage.symbolic.expression.Expression'>] 

len(args): 2, types: [<type 'sage.symbolic.expression.Expression'>, <type 'sage.symbolic.expression.Expression'>] 

tfunc(sin(x), tfunc(1, x^2)) 

  

""" 

from sage.symbolic.ring import SR 

res = [] 

for i in range(seq.size()): 

if is_a_numeric(seq.at(i)): 

res.append(py_object_from_numeric(seq.at(i))) 

elif is_exactly_a_exprseq(seq.at(i)): 

res.append(exprseq_to_PyTuple(seq.at(i))) 

else: 

res.append(new_Expression_from_GEx(SR, seq.at(i))) 

return tuple(res) 

  

cdef GEx pyExpression_to_ex(res) except *: 

""" 

Converts an Expression object to a GiNaC::ex. 

  

Used to pass return values of custom python evaluation, derivation 

functions back to C++ level. 

""" 

if res is None: 

raise TypeError("function returned None, expected return value of type sage.symbolic.expression.Expression") 

try: 

t = ring.SR.coerce(res) 

except TypeError as err: 

raise TypeError("function did not return a symbolic expression or an element that can be coerced into a symbolic expression") 

return (<Expression>t)._gobj 

  

cdef paramset_to_PyTuple(const_paramset_ref s): 

""" 

Converts a std::multiset<unsigned> to a PyTuple. 

  

Used to pass a list of parameter numbers with respect to which a function 

is differentiated to the printing functions py_print_fderivative and 

py_latex_fderivative. 

""" 

cdef GParamSetIter itr = s.begin() 

res = [] 

while itr != s.end(): 

res.append(itr.obj()) 

itr.inc() 

return res 

  

def paramset_from_Expression(Expression e): 

""" 

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import paramset_from_Expression 

sage: f = function('f') 

sage: paramset_from_Expression(f(x).diff(x)) 

[0L] # 32-bit 

[0] # 64-bit 

""" 

return paramset_to_PyTuple(ex_to_fderivative(e._gobj).get_parameter_set()) 

  

cdef int GINAC_FN_SERIAL = 0 

  

cdef set_ginac_fn_serial(): 

""" 

Initialize the GINAC_FN_SERIAL variable to the number of functions 

defined by GiNaC. This allows us to prevent collisions with C++ level 

special functions when a user asks to construct a symbolic function 

with the same name. 

""" 

global GINAC_FN_SERIAL 

GINAC_FN_SERIAL = g_registered_functions().size() 

  

cdef int py_get_ginac_serial(): 

""" 

Returns the number of C++ level functions defined by GiNaC. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import get_ginac_serial 

sage: get_ginac_serial() >= 35 

True 

""" 

global GINAC_FN_SERIAL 

return GINAC_FN_SERIAL 

  

def get_ginac_serial(): 

""" 

Number of C++ level functions defined by GiNaC. (Defined mainly for testing.) 

  

EXAMPLES:: 

  

sage: sage.libs.pynac.pynac.get_ginac_serial() >= 35 

True 

""" 

return py_get_ginac_serial() 

  

cdef get_fn_serial_c(): 

""" 

Return overall size of Pynac function registry. 

""" 

return g_registered_functions().size() 

  

def get_fn_serial(): 

""" 

Return the overall size of the Pynac function registry which 

corresponds to the last serial value plus one. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import get_fn_serial 

sage: from sage.symbolic.function import get_sfunction_from_serial 

sage: get_fn_serial() > 125 

True 

sage: print(get_sfunction_from_serial(get_fn_serial())) 

None 

sage: get_sfunction_from_serial(get_fn_serial() - 1) is not None 

True 

""" 

return get_fn_serial_c() 

  

cdef subs_args_to_PyTuple(const GExMap& map, unsigned options, const GExVector& seq): 

""" 

Convert arguments from ``GiNaC::subs()`` to a PyTuple. 

  

EXAMPLES:: 

  

sage: from sage.symbolic.function import BuiltinFunction 

sage: class TFunc(BuiltinFunction): 

....: def __init__(self): 

....: BuiltinFunction.__init__(self, 'tfunc', nargs=0) 

....: 

....: def _subs_(self, *args): 

....: print("len(args): %s, types: %s"%(len(args), str(list(map(type, args))))) 

....: return args[-1] 

sage: tfunc = TFunc() 

sage: tfunc(x).subs(x=1) 

len(args): 3, types: [<type 'sage.symbolic.substitution_map.SubstitutionMap'>, 

<type 'int'>, # 64-bit 

<type 'long'>, # 32-bit 

<type 'sage.symbolic.expression.Expression'>] 

x 

""" 

from sage.symbolic.ring import SR 

res = [] 

res.append(new_SubstitutionMap_from_GExMap(map)) 

res.append(options) 

return tuple(res) + exvector_to_PyTuple(seq) 

  

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

# Printing helpers 

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

  

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

# Pynac's precedence levels, as extracted from the raw source code on 

# 2009-05-15. If this changes in Pynac it could cause a bug in 

# printing. But it's hardcoded in Pynac now, so there's not much to 

# be done (at present). 

# Container: 10 

# Expairseq: 10 

# Relational: 20 

# Numeric: 30 

# Pseries: 38 

# Addition: 40 

# Integral: 45 

# Multiplication: 50 

# Noncummative mult: 50 

# Index: 55 

# Power: 60 

# Clifford: 65 

# Function: 70 

# Structure: 70 

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

  

cdef stdstring* py_repr(o, int level): 

""" 

Return string representation of o. If level > 0, possibly put 

parentheses around the string. 

""" 

s = repr(o) 

if level >= 20: 

# s may need parens (e.g., is in an exponent), so decide if we 

# have to put parentheses around s: 

# A regexp might seem better, but I don't think it's really faster. 

# It would be more readable. Python does the below (with in) very quickly. 

if level <= 50: 

t = s[1:] # ignore leading minus 

else: 

t = s 

# Python complexes are always printed with parentheses 

# we try to avoid double parentheses 

if not isinstance(o, complex) and \ 

(' ' in t or '/' in t or '+' in t or '-' in t or '*' in t \ 

or '^' in t): 

s = '(%s)'%s 

return string_from_pystr(s) 

  

cdef stdstring* py_latex(o, int level): 

""" 

Return latex string representation of o. If level > 0, possibly 

put parentheses around the string. 

""" 

from sage.misc.latex import latex 

s = latex(o) 

if level >= 20: 

if ' ' in s or '/' in s or '+' in s or '-' in s or '*' in s or '^' in s or '\\frac' in s: 

s = '\\left(%s\\right)'%s 

return string_from_pystr(s) 

  

cdef stdstring* string_from_pystr(py_str) except NULL: 

""" 

Creates a C++ string with the same contents as the given python string. 

  

Used when passing string output to Pynac for printing, since we don't want 

to mess with reference counts of the python objects and we cannot guarantee 

they won't be garbage collected before the output is printed. 

""" 

cdef bytes s 

if isinstance(py_str, bytes): 

s = <bytes>py_str 

elif isinstance(py_str, str): 

# Note: This should only by the case on Python 3 since on Python 2 

# bytes is str 

s = str_to_bytes(py_str) 

else: 

s = b"(INVALID)" # Avoid segfaults for invalid input 

return new stdstring(s) 

  

cdef stdstring* py_latex_variable(var_name): 

""" 

Returns a c++ string containing the latex representation of the given 

variable name. 

  

Real work is done by the function sage.misc.latex.latex_variable_name. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_latex_variable_for_doctests 

sage: py_latex_variable = py_latex_variable_for_doctests 

  

sage: py_latex_variable('a') 

a 

sage: py_latex_variable('abc') 

\mathit{abc} 

sage: py_latex_variable('a_00') 

a_{00} 

sage: py_latex_variable('sigma_k') 

\sigma_{k} 

sage: py_latex_variable('sigma389') 

\sigma_{389} 

sage: py_latex_variable('beta_00') 

\beta_{00} 

""" 

from sage.misc.latex import latex_variable_name 

py_vlatex = latex_variable_name(var_name) 

return string_from_pystr(py_vlatex) 

  

def py_latex_variable_for_doctests(x): 

""" 

Internal function used so we can doctest a certain cdef'd method. 

  

EXAMPLES:: 

  

sage: sage.libs.pynac.pynac.py_latex_variable_for_doctests('x') 

x 

sage: sage.libs.pynac.pynac.py_latex_variable_for_doctests('sigma') 

\sigma 

""" 

cdef stdstring* ostr = py_latex_variable(x) 

print(char_to_str(ostr.c_str())) 

del ostr 

  

def py_print_function_pystring(id, args, fname_paren=False): 

""" 

Return a string with the representation of the symbolic function specified 

by the given id applied to args. 

  

INPUT: 

  

- id -- serial number of the corresponding symbolic function 

- params -- Set of parameter numbers with respect to which to take the 

derivative. 

- args -- arguments of the function. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_print_function_pystring, get_ginac_serial, get_fn_serial 

sage: from sage.symbolic.function import get_sfunction_from_serial 

sage: var('x,y,z') 

(x, y, z) 

sage: foo = function('foo', nargs=2) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_print_function_pystring(i, (x,y)) 

'foo(x, y)' 

sage: py_print_function_pystring(i, (x,y), True) 

'(foo)(x, y)' 

sage: def my_print(self, *args): return "my args are: " + ', '.join(map(repr, args)) 

sage: foo = function('foo', nargs=2, print_func=my_print) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_print_function_pystring(i, (x,y)) 

'my args are: x, y' 

""" 

cdef Function func = get_sfunction_from_serial(id) 

# This function is called from two places, from function::print in Pynac 

# and from py_print_fderivative. function::print checks if the serial 

# belongs to a function defined at the C++ level. There are no C++ level 

# functions that return an instance of fderivative when derivated. Hence, 

# func will never be None. 

assert(func is not None) 

  

# if function has a custom print function call it 

if hasattr(func,'_print_'): 

res = func._print_(*args) 

# make sure the output is a string 

if res is None: 

return "" 

if not isinstance(res, str): 

return str(res) 

return res 

  

# otherwise use default output 

if fname_paren: 

olist = ['(', func._name, ')'] 

else: 

olist = [func._name] 

olist.extend(['(', ', '.join(map(repr, args)), ')']) 

return ''.join(olist) 

  

cdef stdstring* py_print_function(unsigned id, args): 

return string_from_pystr(py_print_function_pystring(id, args)) 

  

def py_latex_function_pystring(id, args, fname_paren=False): 

r""" 

Return a string with the latex representation of the symbolic function 

specified by the given id applied to args. 

  

See documentation of py_print_function_pystring for more information. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_latex_function_pystring, get_ginac_serial, get_fn_serial 

sage: from sage.symbolic.function import get_sfunction_from_serial 

sage: var('x,y,z') 

(x, y, z) 

sage: foo = function('foo', nargs=2) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_latex_function_pystring(i, (x,y^z)) 

'{\\rm foo}\\left(x, y^{z}\\right)' 

sage: py_latex_function_pystring(i, (x,y^z), True) 

'\\left({\\rm foo}\\right)\\left(x, y^{z}\\right)' 

sage: py_latex_function_pystring(i, (int(0),x)) 

'{\\rm foo}\\left(0, x\\right)' 

  

Test latex_name:: 

  

sage: foo = function('foo', nargs=2, latex_name=r'\mathrm{bar}') 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_latex_function_pystring(i, (x,y^z)) 

'\\mathrm{bar}\\left(x, y^{z}\\right)' 

  

Test custom func:: 

  

sage: def my_print(self, *args): return "my args are: " + ', '.join(map(repr, args)) 

sage: foo = function('foo', nargs=2, print_latex_func=my_print) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_latex_function_pystring(i, (x,y^z)) 

'my args are: x, y^z' 

  

  

""" 

cdef Function func = get_sfunction_from_serial(id) 

# This function is called from two places, from function::print in Pynac 

# and from py_latex_fderivative. function::print checks if the serial 

# belongs to a function defined at the C++ level. There are no C++ level 

# functions that return an instance of fderivative when derivated. Hence, 

# func will never be None. 

assert(func is not None) 

  

# if function has a custom print method call it 

if hasattr(func, '_print_latex_'): 

res = func._print_latex_(*args) 

# make sure the output is a string 

if res is None: 

return "" 

if not isinstance(res, str): 

return str(res) 

return res 

  

# otherwise, use the latex name if defined 

if func._latex_name: 

name = func._latex_name 

else: 

# if latex_name is not defined, then call 

# latex_variable_name with "is_fname=True" flag 

from sage.misc.latex import latex_variable_name 

name = latex_variable_name(func._name, is_fname=True) 

if fname_paren: 

olist = [r'\left(', name, r'\right)'] 

else: 

olist = [name] 

# print the arguments 

from sage.misc.latex import latex 

olist.extend([r'\left(', ', '.join([latex(x) for x in args]), 

r'\right)'] ) 

return ''.join(olist) 

  

cdef stdstring* py_latex_function(unsigned id, args): 

return string_from_pystr(py_latex_function_pystring(id, args)) 

  

def tolerant_is_symbol(a): 

""" 

Utility function to test if something is a symbol. 

  

Returns False for arguments that do not have an is_symbol attribute. 

Returns the result of calling the is_symbol method otherwise. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import tolerant_is_symbol 

sage: tolerant_is_symbol(var("x")) 

True 

sage: tolerant_is_symbol(None) 

False 

sage: None.is_symbol() 

Traceback (most recent call last): 

... 

AttributeError: 'NoneType' object has no attribute 'is_symbol' 

""" 

try: 

return a.is_symbol() 

except AttributeError: 

return False 

  

cdef stdstring* py_print_fderivative(unsigned id, params, 

args): 

""" 

Return a string with the representation of the derivative of the symbolic 

function specified by the given id, lists of params and args. 

  

INPUT: 

  

- id -- serial number of the corresponding symbolic function 

- params -- Set of parameter numbers with respect to which to take the 

derivative. 

- args -- arguments of the function. 

""" 

if all([tolerant_is_symbol(a) for a in args]) and len(set(args))==len(args): 

diffvarstr = ', '.join([repr(args[i]) for i in params]) 

py_res = ''.join(['diff(',py_print_function_pystring(id,args,False),', ',diffvarstr,')']) 

else: 

ostr = ''.join(['D[', ', '.join([repr(int(x)) for x in params]), ']']) 

fstr = py_print_function_pystring(id, args, True) 

py_res = ostr + fstr 

return string_from_pystr(py_res) 

  

def py_print_fderivative_for_doctests(id, params, args): 

""" 

Used for testing a cdef'd function. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_print_fderivative_for_doctests as py_print_fderivative, get_ginac_serial, get_fn_serial 

sage: var('x,y,z') 

(x, y, z) 

sage: from sage.symbolic.function import get_sfunction_from_serial 

sage: foo = function('foo', nargs=2) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_print_fderivative(i, (0, 1, 0, 1), (x, y^z)) 

D[0, 1, 0, 1](foo)(x, y^z) 

  

Test custom print function:: 

  

sage: def my_print(self, *args): return "func_with_args(" + ', '.join(map(repr, args)) +')' 

sage: foo = function('foo', nargs=2, print_func=my_print) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_print_fderivative(i, (0, 1, 0, 1), (x, y^z)) 

D[0, 1, 0, 1]func_with_args(x, y^z) 

  

""" 

cdef stdstring* ostr = py_print_fderivative(id, params, args) 

print(char_to_str(ostr.c_str())) 

del ostr 

  

cdef stdstring* py_latex_fderivative(unsigned id, params, 

args): 

""" 

Return a string with the latex representation of the derivative of the 

symbolic function specified by the given id, lists of params and args. 

  

See documentation of py_print_fderivative for more information. 

  

""" 

if all([tolerant_is_symbol(a) for a in args]) and len(set(args))==len(args): 

param_iter=iter(params) 

v=next(param_iter) 

nv=1 

diff_args=[] 

for next_v in param_iter: 

if next_v == v: 

nv+=1 

else: 

if nv == 1: 

diff_args.append(r"\partial %s"%(args[v]._latex_(),)) 

else: 

diff_args.append(r"(\partial %s)^{%s}"%(args[v]._latex_(),nv)) 

v=next_v 

nv=1 

if nv == 1: 

diff_args.append(r"\partial %s"%(args[v]._latex_(),)) 

else: 

diff_args.append(r"(\partial %s)^{%s}"%(args[v]._latex_(),nv)) 

if len(params) == 1: 

operator_string=r"\frac{\partial}{%s}"%(''.join(diff_args),) 

else: 

operator_string=r"\frac{\partial^{%s}}{%s}"%(len(params),''.join(diff_args)) 

py_res = operator_string+py_latex_function_pystring(id,args,False) 

else: 

ostr = ''.join(['\mathrm{D}_{',', '.join([repr(int(x)) for x in params]), '}']) 

fstr = py_latex_function_pystring(id, args, True) 

py_res = ostr + fstr 

return string_from_pystr(py_res) 

  

def py_latex_fderivative_for_doctests(id, params, args): 

r""" 

Used internally for writing doctests for certain cdef'd functions. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_latex_fderivative_for_doctests as py_latex_fderivative, get_ginac_serial, get_fn_serial 

  

sage: var('x,y,z') 

(x, y, z) 

sage: from sage.symbolic.function import get_sfunction_from_serial 

sage: foo = function('foo', nargs=2) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z)) 

\mathrm{D}_{0, 1, 0, 1}\left({\rm foo}\right)\left(x, y^{z}\right) 

  

Test latex_name:: 

  

sage: foo = function('foo', nargs=2, latex_name=r'\mathrm{bar}') 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z)) 

\mathrm{D}_{0, 1, 0, 1}\left(\mathrm{bar}\right)\left(x, y^{z}\right) 

  

Test custom func:: 

  

sage: def my_print(self, *args): return "func_with_args(" + ', '.join(map(repr, args)) +')' 

sage: foo = function('foo', nargs=2, print_latex_func=my_print) 

sage: for i in range(get_ginac_serial(), get_fn_serial()): 

....: if get_sfunction_from_serial(i) == foo: break 

  

sage: get_sfunction_from_serial(i) == foo 

True 

sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z)) 

\mathrm{D}_{0, 1, 0, 1}func_with_args(x, y^z) 

""" 

cdef stdstring* ostr = py_latex_fderivative(id, params, args) 

print(char_to_str(ostr.c_str())) 

del ostr 

  

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

# Archive helpers 

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

  

cdef stdstring* py_dumps(o): 

s = dumps(o, compress=False) 

# pynac archive format terminates atoms with zeroes. 

# since pickle output can break the archive format 

# we use the base64 data encoding 

import base64 

s = base64.b64encode(s) 

return string_from_pystr(s) 

  

cdef py_loads(s): 

import base64 

s = base64.b64decode(s) 

return loads(s) 

  

cdef py_get_sfunction_from_serial(unsigned s): 

""" 

Return the Python object associated with a serial. 

""" 

return get_sfunction_from_serial(s) 

  

cdef unsigned py_get_serial_from_sfunction(f): 

""" 

Given a Function object return its serial. 

  

Python's unpickling mechanism is used to unarchive a symbolic function with 

custom methods (evaluation, differentiation, etc.). Pynac extracts a string 

representation from the archive, calls loads() to recreate the stored 

function. This allows us to extract the serial from the Python object to 

set the corresponding member variable of the C++ object representing this 

function. 

""" 

return (<Function>f)._serial 

  

cdef unsigned py_get_serial_for_new_sfunction(stdstring &s, 

unsigned nargs): 

""" 

Return a symbolic function with the given name and number of arguments. 

  

When unarchiving a user defined symbolic function, Pynac goes through 

the registry of existing functions. If there is no function already defined 

with the archived name and number of arguments, this method is called to 

create one and set up the function tables properly. 

""" 

from sage.symbolic.function_factory import function_factory 

cdef Function fn = function_factory(s.c_str(), nargs) 

return fn._serial 

  

  

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

# Modular helpers 

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

  

cdef int py_get_parent_char(o) except -1: 

""" 

TESTS: 

  

:trac:`24072` fixes the workaround provided in :trac:`21187`:: 

  

sage: p = next_prime(2^100) 

sage: R.<y> = FiniteField(p)[] 

sage: y = SR(y) 

Traceback (most recent call last): 

... 

TypeError: positive characteristic not allowed in symbolic computations 

""" 

if not isinstance(o, Element): 

return 0 

  

c = (<Element>o)._parent.characteristic() 

  

# Pynac only differentiates between 

# - characteristic 0 

# - characteristic 2 

# - characteristic > 0 but not 2 

# 

# To avoid integer overflow in the last case, we just return 3 

# instead of the actual characteristic. 

if not c: 

return 0 

elif c == 2: 

return 2 

else: 

return 3 

  

  

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

# power helpers 

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

  

cdef py_rational_power_parts(base, exp): 

if type(base) is not Rational: 

base = Rational(base) 

if type(exp) is not Rational: 

exp = Rational(exp) 

res= rational_power_parts(base, exp) 

return res + (bool(res[0] == 1),) 

  

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

# Binomial Coefficients 

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

  

  

cdef py_binomial_int(int n, unsigned int k): 

cdef bint sign 

if n < 0: 

n = -n + (k-1) 

sign = k%2 

else: 

sign = 0 

cdef Integer ans = PY_NEW(Integer) 

# Compute the binomial coefficient using GMP. 

mpz_bin_uiui(ans.value, n, k) 

# Return the answer or the negative of it (only if k is odd and n is negative). 

if sign: 

return -ans 

else: 

return ans 

  

cdef py_binomial(n, k): 

# Keep track of the sign we should use. 

cdef bint sign 

if n < 0: 

n = k-n-1 

sign = k%2 

else: 

sign = 0 

# Convert n and k to unsigned ints. 

cdef unsigned int n_ = n, k_ = k 

cdef Integer ans = PY_NEW(Integer) 

# Compute the binomial coefficient using GMP. 

mpz_bin_uiui(ans.value, n_, k_) 

# Return the answer or the negative of it (only if k is odd and n is negative). 

if sign: 

return -ans 

else: 

return ans 

  

def test_binomial(n, k): 

""" 

The Binomial coefficients. It computes the binomial coefficients. For 

integer n and k and positive n this is the number of ways of choosing k 

objects from n distinct objects. If n is negative, the formula 

binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. 

  

INPUT: 

  

- n, k -- integers, with k >= 0. 

  

OUTPUT: 

  

integer 

  

EXAMPLES:: 

  

sage: import sage.libs.pynac.pynac 

sage: sage.libs.pynac.pynac.test_binomial(5,2) 

10 

sage: sage.libs.pynac.pynac.test_binomial(-5,3) 

-35 

sage: -sage.libs.pynac.pynac.test_binomial(3-(-5)-1, 3) 

-35 

""" 

return py_binomial(n, k) 

  

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

# GCD 

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

cdef py_gcd(n, k): 

if isinstance(n, Integer) and isinstance(k, Integer): 

if mpz_cmp_si((<Integer>n).value,1) == 0: 

return n 

elif mpz_cmp_si((<Integer>k).value,1) == 0: 

return k 

return n.gcd(k) 

  

if type(n) is Rational and type(k) is Rational: 

return n.content(k) 

try: 

return gcd(n,k) 

except (TypeError, ValueError, AttributeError): 

# some strange meaning in case of weird things with no usual lcm. 

return 1 

  

  

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

# LCM 

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

cdef py_lcm(n, k): 

if isinstance(n, Integer) and isinstance(k, Integer): 

if mpz_cmp_si((<Integer>n).value,1) == 0: 

return k 

elif mpz_cmp_si((<Integer>k).value,1) == 0: 

return n 

return n.lcm(k) 

try: 

return lcm(n,k) 

except (TypeError, ValueError, AttributeError): 

# some strange meaning in case of weird things with no usual lcm, e.g., 

# elements of finite fields. 

return 1 

  

  

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

# Real Part 

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

cdef py_real(x): 

""" 

Returns the real part of x. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_real_for_doctests as py_real 

sage: py_real(I) 

0 

sage: py_real(CC(1,5)) 

1.00000000000000 

sage: py_real(CC(1)) 

1.00000000000000 

sage: py_real(RR(1)) 

1.00000000000000 

  

sage: py_real(Mod(2,7)) 

2 

  

sage: py_real(QQ['x'].gen()) 

x 

sage: py_real(float(2)) 

2.0 

sage: py_real(complex(2,2)) 

2.0 

""" 

if isinstance(x, (float, int, long)): 

return x 

elif isinstance(x, complex): 

return x.real 

  

try: 

return x.real() 

except AttributeError: 

pass 

try: 

return x.real_part() 

except AttributeError: 

pass 

  

return x # assume x is real 

  

def py_real_for_doctests(x): 

""" 

Used for doctesting py_real. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_real_for_doctests 

sage: py_real_for_doctests(I) 

0 

""" 

return py_real(x) 

  

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

# Imaginary Part 

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

cdef py_imag(x): 

""" 

Return the imaginary part of x. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_imag_for_doctests as py_imag 

sage: py_imag(I) 

1 

sage: py_imag(CC(1,5)) 

5.00000000000000 

sage: py_imag(CC(1)) 

0.000000000000000 

sage: py_imag(RR(1)) 

0 

sage: py_imag(Mod(2,7)) 

0 

  

sage: py_imag(QQ['x'].gen()) 

0 

sage: py_imag(float(2)) 

0.0 

sage: py_imag(complex(2,2)) 

2.0 

""" 

if isinstance(x, float): 

return 0.0 

if isinstance(x, complex): 

return x.imag 

try: 

return x.imag() 

except AttributeError: 

pass 

try: 

return x.imag_part() 

except AttributeError: 

pass 

  

  

return 0 # assume x is real 

  

def py_imag_for_doctests(x): 

""" 

Used for doctesting py_imag. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_imag_for_doctests 

sage: py_imag_for_doctests(I) 

1 

""" 

return py_imag(x) 

  

  

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

# Conjugate 

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

cdef py_conjugate(x): 

try: 

return x.conjugate() 

except AttributeError: 

return x # assume is real since it doesn't have an imag attribute. 

  

cdef bint py_is_rational(x): 

return (type(x) is Rational or 

type(x) is Integer or 

isinstance(x, (int, long))) 

  

cdef bint py_is_equal(x, y): 

""" 

Return True precisely if x and y are equal. 

""" 

return bool(x==y) 

  

cdef bint py_is_integer(x): 

r""" 

Returns True if pynac should treat this object as an integer. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_is_integer_for_doctests 

sage: py_is_integer = py_is_integer_for_doctests 

  

sage: py_is_integer(1r) 

True 

sage: py_is_integer(long(1)) 

True 

sage: py_is_integer(3^57) 

True 

sage: py_is_integer(SR(5)) 

True 

sage: py_is_integer(4/2) 

True 

sage: py_is_integer(QQbar(sqrt(2))^2) 

True 

sage: py_is_integer(3.0) 

False 

sage: py_is_integer(3.0r) 

False 

""" 

if isinstance(x, (int, long, Integer)): 

return True 

if not isinstance(x, Element): 

return False 

P = (<Element>x)._parent 

return (P is ring.SR or P.is_exact()) and x in ZZ 

  

  

def py_is_integer_for_doctests(x): 

""" 

Used internally for doctesting purposes. 

  

TESTS:: 

  

sage: sage.libs.pynac.pynac.py_is_integer_for_doctests(1r) 

True 

sage: sage.libs.pynac.pynac.py_is_integer_for_doctests(1/3) 

False 

sage: sage.libs.pynac.pynac.py_is_integer_for_doctests(2) 

True 

""" 

return py_is_integer(x) 

  

cdef bint py_is_even(x): 

try: 

return not(x%2) 

except Exception: 

try: 

return not(ZZ(x)%2) 

except Exception: 

pass 

return 0 

  

  

cdef bint py_is_crational(x): 

if py_is_rational(x): 

return True 

elif isinstance(x, Element) and (<Element>x)._parent is pynac_I._parent: 

return True 

else: 

return False 

  

def py_is_crational_for_doctest(x): 

""" 

Returns True if pynac should treat this object as an element of `\QQ(i)`. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_is_crational_for_doctest 

sage: py_is_crational_for_doctest(1) 

True 

sage: py_is_crational_for_doctest(-2r) 

True 

sage: py_is_crational_for_doctest(1.5) 

False 

sage: py_is_crational_for_doctest(I.pyobject()) 

True 

sage: py_is_crational_for_doctest(I.pyobject()+1/2) 

True 

""" 

return py_is_crational(x) 

  

cdef bint py_is_real(a): 

if isinstance(a, (int, long, Integer, float)): 

return True 

try: 

P = parent(a) 

if P.is_field() and P.is_finite(): 

return False 

except NotImplementedError: 

return False 

except AttributeError: 

pass 

return py_imag(a) == 0 

  

cdef bint py_is_prime(n): 

try: 

return n.is_prime() 

except Exception: # yes, I'm doing this on purpose. 

pass 

try: 

return is_prime(n) 

except Exception: 

pass 

return False 

  

  

cdef bint py_is_exact(x): 

if isinstance(x, (int, long, Integer)): 

return True 

if not isinstance(x, Element): 

return False 

P = (<Element>x)._parent 

return P is ring.SR or P.is_exact() 

  

  

cdef py_numer(n): 

""" 

Return the numerator of the given object. This is called for 

typesetting coefficients. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_numer_for_doctests as py_numer 

sage: py_numer(2r) 

2 

sage: py_numer(3) 

3 

sage: py_numer(2/3) 

2 

sage: C.<i> = NumberField(x^2+1) 

sage: py_numer(2/3*i) 

2*i 

sage: class no_numer: 

....: def denominator(self): 

....: return 5 

....: def __mul__(left, right): 

....: return 42 

... 

sage: py_numer(no_numer()) 

42 

""" 

if isinstance(n, (int, long, Integer)): 

return n 

try: 

return n.numerator() 

except AttributeError: 

try: 

return n*n.denominator() 

except AttributeError: 

return n 

  

def py_numer_for_doctests(n): 

""" 

This function is used to test py_numer(). 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_numer_for_doctests 

sage: py_numer_for_doctests(2/3) 

2 

""" 

return py_numer(n) 

  

cdef py_denom(n): 

""" 

Return the denominator of the given object. This is called for 

typesetting coefficients. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_denom_for_doctests as py_denom 

sage: py_denom(5) 

1 

sage: py_denom(2/3) 

3 

sage: C.<i> = NumberField(x^2+1) 

sage: py_denom(2/3*i) 

3 

""" 

if isinstance(n, (int, long, Integer)): 

return 1 

try: 

return n.denominator() 

except AttributeError: 

return 1 

  

def py_denom_for_doctests(n): 

""" 

This function is used to test py_denom(). 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_denom_for_doctests 

sage: py_denom_for_doctests(2/3) 

3 

""" 

return py_denom(n) 

  

cdef bint py_is_cinteger(x): 

return py_is_integer(x) or (py_is_crational(x) and py_denom(x) == 1) 

  

def py_is_cinteger_for_doctest(x): 

""" 

Returns True if pynac should treat this object as an element of `\ZZ(i)`. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_is_cinteger_for_doctest 

sage: py_is_cinteger_for_doctest(1) 

True 

sage: py_is_cinteger_for_doctest(long(-3)) 

True 

sage: py_is_cinteger_for_doctest(I.pyobject()) 

True 

sage: py_is_cinteger_for_doctest(I.pyobject() - 3) 

True 

sage: py_is_cinteger_for_doctest(I.pyobject() + 1/2) 

False 

""" 

return py_is_cinteger(x) 

  

cdef py_float(n, PyObject* kwds): 

""" 

Evaluate pynac numeric objects numerically. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_float_for_doctests as py_float 

sage: py_float(I, {'parent':ComplexField(10)}) 

1.0*I 

sage: py_float(pi, {'parent':RealField(100)}) 

3.1415926535897932384626433833 

sage: py_float(10, {'parent':CDF}) 

10.0 

sage: type(py_float(10, {'parent':CDF})) 

<type 'sage.rings.complex_double.ComplexDoubleElement'> 

sage: py_float(1/2, {'parent':CC}) 

0.500000000000000 

sage: type(py_float(1/2, {'parent':CC})) 

<type 'sage.rings.complex_number.ComplexNumber'> 

""" 

if kwds is not NULL: 

p = (<object>kwds)['parent'] 

if p is float: 

try: 

return float(n) 

except TypeError: 

return complex(n) 

elif p is complex: 

return p(n) 

else: 

try: 

return p(n) 

except (TypeError,ValueError): 

return p.complex_field()(n) 

else: 

try: 

return RR(n) 

except TypeError: 

return CC(n) 

  

def py_float_for_doctests(n, kwds): 

""" 

This function is for testing py_float. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_float_for_doctests 

sage: py_float_for_doctests(pi, {'parent':RealField(80)}) 

3.1415926535897932384626 

sage: py_float_for_doctests(I, {'parent':RealField(80)}) 

1.0000000000000000000000*I 

sage: py_float_for_doctests(I, {'parent':float}) 

1j 

sage: py_float_for_doctests(pi, {'parent':complex}) 

(3.141592653589793+0j) 

""" 

return py_float(n, <PyObject*>kwds) 

  

  

cdef py_RDF_from_double(double x): 

cdef RealDoubleElement r = RealDoubleElement.__new__(RealDoubleElement) 

r._value = x 

return r 

  

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

# SPECIAL FUNCTIONS 

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

cdef py_tgamma(x): 

""" 

The gamma function exported to pynac. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_tgamma_for_doctests as py_tgamma 

sage: py_tgamma(4) 

6 

sage: py_tgamma(1/2) 

1.77245385090552 

""" 

if isinstance(x, (int, long)): 

x = float(x) 

if type(x) is float: 

return math.tgamma(PyFloat_AS_DOUBLE(x)) 

  

# try / except blocks are faster than 

# if hasattr(x, 'gamma') 

try: 

res = x.gamma() 

except AttributeError: 

return CC(x).gamma() 

  

# the result should be numeric, however the gamma method of rationals may 

# return symbolic expressions. for example (1/2).gamma() -> sqrt(pi). 

if isinstance(res, Expression): 

try: 

return RR(res) 

except ValueError: 

return CC(res) 

return res 

  

def py_tgamma_for_doctests(x): 

""" 

This function is for testing py_tgamma(). 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_tgamma_for_doctests 

sage: py_tgamma_for_doctests(3) 

2 

""" 

return py_tgamma(x) 

  

cdef py_factorial(x): 

""" 

The factorial function exported to pynac. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_factorial_py as py_factorial 

sage: py_factorial(4) 

24 

sage: py_factorial(-2/3) 

2.67893853470775 

""" 

# factorial(x) is only defined for non-negative integers x 

# so we first test if x can be coerced into ZZ and is non-negative. 

# If this is not the case then we return the symbolic expression gamma(x+1) 

# This fixes Trac 9240 

try: 

x_in_ZZ = ZZ(x) 

coercion_success = True 

except (TypeError, ValueError): 

coercion_success = False 

  

if coercion_success and x_in_ZZ >= 0: 

return factorial(x) 

else: 

return py_tgamma(x+1) 

  

def py_factorial_py(x): 

""" 

This function is a python wrapper around py_factorial(). This wrapper 

is needed when we override the eval() method for GiNaC's factorial 

function in sage.functions.other.Function_factorial. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_factorial_py 

sage: py_factorial_py(3) 

6 

""" 

return py_factorial(x) 

  

cdef py_doublefactorial(x): 

n = Integer(x) 

if n < -1: 

raise ValueError("argument must be >= -1") 

from sage.misc.misc_c import prod # fast balanced product 

return prod([n - 2*i for i in range(n//2)]) 

  

def doublefactorial(n): 

""" 

The double factorial combinatorial function: 

  

n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1. 

  

INPUT: 

  

- n -- an integer > = 1 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import doublefactorial 

sage: doublefactorial(-1) 

1 

sage: doublefactorial(0) 

1 

sage: doublefactorial(1) 

1 

sage: doublefactorial(5) 

15 

sage: doublefactorial(20) 

3715891200 

sage: prod( [20,18,..,2] ) 

3715891200 

""" 

return py_doublefactorial(n) 

  

  

cdef py_fibonacci(n): 

return Integer(pari(n).fibonacci()) 

  

cdef py_step(n): 

""" 

Return step function of n. 

""" 

if n < 0: 

return ZERO 

elif n > 0: 

return ONE 

return ONE_HALF 

  

cdef py_bernoulli(x): 

return bernoulli(x) 

  

cdef py_sin(x): 

""" 

TESTS:: 

  

sage: sin(float(2)) #indirect doctest 

0.9092974268256817 

sage: sin(2.) 

0.909297426825682 

sage: sin(2.*I) 

3.62686040784702*I 

sage: sin(QQbar(I)) # known bug 

I*sinh(1) 

""" 

try: 

return x.sin() 

except AttributeError: 

pass 

try: 

return RR(x).sin() 

except (TypeError, ValueError): 

return CC(x).sin() 

  

cdef py_cos(x): 

""" 

TESTS:: 

  

sage: cos(float(2)) #indirect doctest 

-0.4161468365471424 

sage: cos(2.) 

-0.416146836547142 

sage: cos(2.*I) 

3.76219569108363 

sage: cos(QQbar(I)) # known bug 

cosh(1) 

""" 

try: 

return x.cos() 

except AttributeError: 

pass 

try: 

return RR(x).cos() 

except (TypeError, ValueError): 

return CC(x).cos() 

  

cdef py_stieltjes(x): 

""" 

Return the Stieltjes constant of the given index. 

  

The value is expected to be a non-negative integer. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_stieltjes_for_doctests as py_stieltjes 

sage: py_stieltjes(0) 

0.577215664901533 

sage: py_stieltjes(1.0) 

-0.0728158454836767 

sage: py_stieltjes(RealField(100)(5)) 

0.00079332381730106270175333487744 

sage: py_stieltjes(-1) 

Traceback (most recent call last): 

... 

ValueError: Stieltjes constant of negative index 

""" 

n = ZZ(x) 

if n < 0: 

raise ValueError("Stieltjes constant of negative index") 

import mpmath 

if isinstance(x, Element) and hasattr((<Element>x)._parent, 'prec'): 

prec = (<Element>x)._parent.prec() 

else: 

prec = 53 

return mpmath_utils.call(mpmath.stieltjes, n, prec=prec) 

  

def py_stieltjes_for_doctests(x): 

""" 

This function is for testing py_stieltjes(). 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_stieltjes_for_doctests 

sage: py_stieltjes_for_doctests(0.0) 

0.577215664901533 

""" 

return py_stieltjes(x) 

  

cdef py_zeta(x): 

""" 

Return the value of the zeta function at the given value. 

  

The value is expected to be a numerical object, in RR, CC, RDF or CDF, 

different from 1. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_zeta_for_doctests as py_zeta 

sage: py_zeta(CC.0) 

0.00330022368532410 - 0.418155449141322*I 

sage: py_zeta(CDF(5)) 

1.03692775514337 

sage: py_zeta(RealField(100)(5)) 

1.0369277551433699263313654865 

""" 

try: 

return x.zeta() 

except AttributeError: 

return CC(x).zeta() 

  

def py_zeta_for_doctests(x): 

""" 

This function is for testing py_zeta(). 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_zeta_for_doctests 

sage: py_zeta_for_doctests(CC.0) 

0.00330022368532410 - 0.418155449141322*I 

""" 

return py_zeta(x) 

  

cdef py_exp(x): 

""" 

Return the value of the exp function at the given value. 

  

The value is expected to be a numerical object, in RR, CC, RDF or CDF. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_exp_for_doctests as py_exp 

sage: py_exp(CC(1)) 

2.71828182845905 

sage: py_exp(CC(.5*I)) 

0.877582561890373 + 0.479425538604203*I 

sage: py_exp(float(1)) 

2.718281828459045... 

sage: py_exp(QQbar(I)) 

0.540302305868140 + 0.841470984807897*I 

""" 

if type(x) is float: 

return math.exp(PyFloat_AS_DOUBLE(x)) 

try: 

return x.exp() 

except AttributeError: 

pass 

try: 

return RR(x).exp() 

except (TypeError, ValueError): 

return CC(x).exp() 

  

def py_exp_for_doctests(x): 

""" 

This function tests py_exp. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_exp_for_doctests 

sage: py_exp_for_doctests(CC(2)) 

7.38905609893065 

""" 

return py_exp(x) 

  

cdef py_log(x): 

""" 

Return the value of the log function at the given value. 

  

The value is expected to be a numerical object, in RR, CC, RDF or CDF. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_log_for_doctests as py_log 

sage: py_log(CC(e)) 

1.00000000000000 

sage: py_log(CC.0) 

1.57079632679490*I 

sage: py_log(float(e)) 

1.0 

sage: py_log(float(0)) 

-inf 

sage: py_log(float(-1)) 

3.141592653589793j 

sage: py_log(int(1)) 

0.0 

sage: py_log(long(1)) 

0.0 

sage: py_log(int(0)) 

-inf 

sage: py_log(long(0)) 

-inf 

sage: py_log(complex(0)) 

-inf 

sage: py_log(2) 

0.693147180559945 

""" 

cdef gsl_complex res 

cdef double real, imag 

if isinstance(x, (int, long)): 

x = float(x) 

if type(x) is float: 

real = PyFloat_AS_DOUBLE(x) 

if real > 0: 

return math.log(real) 

elif real < 0: 

res = gsl_complex_log(gsl_complex_rect(real, 0)) 

return PyComplex_FromDoubles(res.dat[0], res.dat[1]) 

else: 

return float('-inf') 

elif type(x) is complex: 

real = PyComplex_RealAsDouble(x) 

imag = PyComplex_ImagAsDouble(x) 

if real == 0 and imag == 0: 

return float('-inf') 

res = gsl_complex_log(gsl_complex_rect(real, imag)) 

return PyComplex_FromDoubles(res.dat[0], res.dat[1]) 

elif isinstance(x, Integer): 

return x.log().n() 

elif hasattr(x, 'log'): 

return x.log() 

try: 

return RR(x).log() 

except (TypeError, ValueError): 

return CC(x).log() 

  

def py_log_for_doctests(x): 

""" 

This function tests py_log. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_log_for_doctests 

sage: py_log_for_doctests(CC(e)) 

1.00000000000000 

""" 

return py_log(x) 

  

cdef py_tan(x): 

try: 

return x.tan() 

except AttributeError: 

pass 

try: 

return RR(x).tan() 

except TypeError: 

return CC(x).tan() 

  

cdef py_asin(x): 

try: 

return x.arcsin() 

except AttributeError: 

return RR(x).arcsin() 

  

cdef py_acos(x): 

try: 

return x.arccos() 

except AttributeError: 

return RR(x).arccos() 

  

cdef py_atan(x): 

try: 

return x.arctan() 

except AttributeError: 

return RR(x).arctan() 

  

cdef py_atan2(x, y): 

""" 

Return the value of the two argument arctan function at the given values. 

  

The values are expected to be numerical objects, for example in RR, CC, 

RDF or CDF. 

  

Note that the usual call signature of this function has the arguments 

reversed. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_atan2_for_doctests as py_atan2 

sage: py_atan2(0, 1) 

1.57079632679490 

sage: py_atan2(0.r, 1.r) 

1.5707963267948966 

sage: CC100 = ComplexField(100) 

sage: py_atan2(CC100(0), CC100(1)) 

1.5707963267948966192313216916 

sage: RR100 = RealField(100) 

sage: py_atan2(RR100(0), RR100(1)) 

1.5707963267948966192313216916 

  

Check that :trac:`21428` is fixed:: 

  

sage: plot(real(sqrt(x - 1.*I)), (x,0,1)) 

Graphics object consisting of 1 graphics primitive 

  

Check that :trac:`22553` is fixed:: 

  

sage: arctan2(1.5, -1.300000000000001) 

2.284887025407... 

sage: atan2(2.1000000000000000000000000000000000000, -1.20000000000000000000000000000000) 

2.089942441041419571002776071... 

  

Check that :trac:`22877` is fixed:: 

  

sage: atan2(CC(I), CC(I+1)) 

0.553574358897045 + 0.402359478108525*I 

sage: atan2(CBF(I), CBF(I+1)) 

[0.55357435889705 +/- 5.58e-15] + [0.402359478108525 +/- 7.11e-16]*I 

  

Check that :trac:`23776` is fixed and RDF input gives real output:: 

  

sage: atan2(RDF(-3), RDF(-1)) 

-1.8925468811915387 

""" 

from sage.symbolic.constants import pi, NaN 

P = coercion_model.common_parent(x, y) 

if P is ZZ: 

P = RR 

if y != 0: 

if RR.has_coerce_map_from(P): 

if x > 0: 

res = py_atan(abs(y/x)) 

elif x < 0: 

res = P(pi) - py_atan(abs(y/x)) 

else: 

res = P(pi)/2 

return res if y > 0 else -res 

else: 

return -I*py_log((x + I*y)/py_sqrt(x**2 + y**2)) 

else: 

if x > 0: 

return P(0) 

elif x < 0: 

return P(pi) 

else: 

return P(NaN) 

  

def py_atan2_for_doctests(x, y): 

""" 

Wrapper function to test py_atan2. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_atan2_for_doctests 

sage: py_atan2_for_doctests(0., 1.) 

1.57079632679490 

""" 

return py_atan2(x, y) 

  

cdef py_sinh(x): 

try: 

return x.sinh() 

except AttributeError: 

return RR(x).sinh() 

  

  

cdef py_cosh(x): 

if type(x) is float: 

return math.cosh(PyFloat_AS_DOUBLE(x)) 

try: 

return x.cosh() 

except AttributeError: 

return RR(x).cosh() 

  

cdef py_tanh(x): 

try: 

return x.tanh() 

except AttributeError: 

return RR(x).tanh() 

  

  

cdef py_asinh(x): 

try: 

return x.arcsinh() 

except AttributeError: 

pass 

try: 

return RR(x).arcsinh() 

except TypeError: 

return CC(x).arcsinh() 

  

cdef py_acosh(x): 

try: 

return x.arccosh() 

except AttributeError: 

pass 

try: 

return RR(x).arccosh() 

except TypeError: 

return CC(x).arccosh() 

  

  

cdef py_atanh(x): 

try: 

return x.arctanh() 

except AttributeError: 

pass 

try: 

return RR(x).arctanh() 

except TypeError: 

return CC(x).arctanh() 

  

cdef py_lgamma(x): 

""" 

Return the value of the principal branch of the log gamma function at the 

given value. 

  

The value is expected to be a numerical object, in RR, CC, RDF or CDF, or 

of the Python ``float`` or ``complex`` type. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_lgamma_for_doctests as py_lgamma 

sage: py_lgamma(4) 

1.79175946922805 

sage: py_lgamma(4.r) # abs tol 2e-14 

1.79175946922805 

sage: py_lgamma(4r) # abs tol 2e-14 

1.79175946922805 

sage: py_lgamma(CC.0) 

-0.650923199301856 - 1.87243664726243*I 

sage: py_lgamma(ComplexField(100).0) 

-0.65092319930185633888521683150 - 1.8724366472624298171188533494*I 

""" 

from mpmath import loggamma 

  

try: 

return x.log_gamma() 

except AttributeError: 

pass 

try: 

return RR(x).log_gamma() 

except TypeError: 

return mpmath_utils.call(loggamma, x, parent=parent(x)) 

  

def py_lgamma_for_doctests(x): 

""" 

This function tests py_lgamma. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_lgamma_for_doctests 

sage: py_lgamma_for_doctests(CC(I)) 

-0.650923199301856 - 1.87243664726243*I 

""" 

return py_lgamma(x) 

  

cdef py_isqrt(x): 

return Integer(x).isqrt() 

  

cdef py_sqrt(x): 

try: 

# WORRY: What if Integer's sqrt calls symbolic one and we go in circle? 

return x.sqrt() 

except AttributeError as msg: 

return math.sqrt(float(x)) 

  

cdef py_abs(x): 

return abs(x) 

  

cdef py_mod(x, n): 

""" 

Return x mod n. Both x and n are assumed to be integers. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_mod_for_doctests as py_mod 

sage: py_mod(I.parent(5), 4) 

1 

sage: py_mod(3, -2) 

-1 

sage: py_mod(3/2, 2) 

Traceback (most recent call last): 

... 

TypeError: no conversion of this rational to integer 

  

  

Note: The original code for this function in GiNaC checks if the arguments 

are integers, and returns 0 otherwise. We omit this check, since all the 

calls to py_mod are preceded by an integer check. We also raise an error 

if converting the arguments to integers fails, since silently returning 0 

would hide possible misuses of this function. 

  

Regarding the sign of the return value, the CLN reference manual says: 

  

If x and y are both >= 0, mod(x,y) = rem(x,y) >= 0. In general, 

mod(x,y) has the sign of y or is zero, and rem(x,y) has the sign of 

x or is zero. 

  

This matches the behavior of the % operator for integers in Sage. 

""" 

return Integer(x) % Integer(n) 

  

def py_mod_for_doctests(x, n): 

""" 

This function is a python wrapper so py_mod can be tested. The real tests 

are in the docstring for py_mod. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_mod_for_doctests 

sage: py_mod_for_doctests(5, 2) 

1 

""" 

return py_mod(x, n) 

  

cdef py_smod(a, b): 

# Modulus (in symmetric representation). 

# Equivalent to Maple's mods. 

# returns a mod b in the range [-iquo(abs(b)-1,2), iquo(abs(b),2)] 

a = Integer(a); b = Integer(b) 

b = abs(b) 

c = a % b 

if c > b//2: 

c -= b 

return c 

  

cdef py_irem(x, n): 

return Integer(x) % Integer(n) 

  

cdef py_iquo(x, n): 

return Integer(x)//Integer(n) 

  

cdef py_iquo2(x, n): 

x = Integer(x); n = Integer(n) 

try: 

q = x//n 

r = x - q*n 

return q, r 

except (TypeError, ValueError): 

return 0, 0 

  

cdef int py_int_length(x) except -1: 

# Size in binary notation. For integers, this is the smallest n >= 0 such 

# that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that 

# 2^(n-1) <= x < 2^n. This returns 0 if x is not an integer. 

return Integer(x).nbits() 

  

cdef py_li(x, n, parent): 

""" 

Returns a numerical approximation of polylog(n, x) with precision given 

by the ``parent`` argument. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_li_for_doctests as py_li 

sage: py_li(0,2,RR) 

0.000000000000000 

sage: py_li(-1,2,RR) 

-0.822467033424113 

sage: py_li(0, 1, float) 

0.000000000000000 

""" 

import mpmath 

try: 

prec = parent.prec() 

except AttributeError: 

prec = 53 

return mpmath_utils.call(mpmath.polylog, n, x, prec=prec) 

  

def py_li_for_doctests(x, n, parent): 

""" 

This function is a python wrapper so py_li can be tested. The real tests 

are in the docstring for py_li. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_li_for_doctests 

sage: py_li_for_doctests(0,2,float) 

0.000000000000000 

""" 

return py_li(x, n, parent) 

  

cdef py_psi(x): 

""" 

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_psi_for_doctests as py_psi 

sage: py_psi(0) 

Traceback (most recent call last): 

... 

ValueError: polygamma pole 

sage: py_psi(1) 

-0.577215664901533 

sage: euler_gamma.n() 

0.577215664901533 

""" 

import mpmath 

if isinstance(x, Element) and hasattr((<Element>x)._parent, 'prec'): 

prec = (<Element>x)._parent.prec() 

else: 

prec = 53 

return mpmath_utils.call(mpmath.psi, 0, x, prec=prec) 

  

def py_psi_for_doctests(x): 

""" 

This function is a python wrapper so py_psi can be tested. The real tests 

are in the docstring for py_psi. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_psi_for_doctests 

sage: py_psi_for_doctests(2) 

0.422784335098467 

""" 

return py_psi(x) 

  

cdef py_psi2(n, x): 

""" 

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_psi2_for_doctests as py_psi2 

sage: py_psi2(2, 1) 

-2.40411380631919 

""" 

import mpmath 

if isinstance(x, Element) and hasattr((<Element>x)._parent, 'prec'): 

prec = (<Element>x)._parent.prec() 

else: 

prec = 53 

return mpmath_utils.call(mpmath.psi, n, x, prec=prec) 

  

def py_psi2_for_doctests(n, x): 

""" 

This function is a python wrapper so py_psi2 can be tested. The real tests 

are in the docstring for py_psi2. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_psi2_for_doctests 

sage: py_psi2_for_doctests(1, 2) 

0.644934066848226 

""" 

return py_psi2(n, x) 

  

cdef py_li2(x): 

""" 

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_li2_for_doctests as py_li2 

sage: py_li2(-1.1) 

-0.890838090262283 

""" 

import mpmath 

if isinstance(x, Element) and hasattr((<Element>x)._parent, 'prec'): 

prec = (<Element>x)._parent.prec() 

else: 

prec = 53 

return mpmath_utils.call(mpmath.polylog, 2, x, prec=prec) 

  

  

def py_li2_for_doctests(x): 

""" 

This function is a python wrapper so py_psi2 can be tested. The real tests 

are in the docstring for py_psi2. 

  

EXAMPLES:: 

  

sage: from sage.libs.pynac.pynac import py_li2_for_doctests 

sage: py_li2_for_doctests(-1.1) 

-0.890838090262283 

""" 

return py_li2(x) 

  

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

# Constants 

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

  

cdef GConstant py_get_constant(const char* name): 

""" 

Returns a constant given its name. This is called by 

constant::unarchive in constant.cpp in Pynac and is used for 

pickling. 

""" 

from sage.symbolic.constants import constants_name_table 

cdef PynacConstant pc 

c = constants_name_table.get(name, None) 

if c is None: 

raise RuntimeError 

else: 

pc = c._pynac 

return pc.pointer[0] 

  

cdef py_eval_constant(unsigned serial, kwds): 

from sage.symbolic.constants import constants_table 

constant = constants_table[serial] 

return kwds['parent'](constant) 

  

cdef py_eval_unsigned_infinity(): 

""" 

Returns unsigned_infinity. 

""" 

from sage.rings.infinity import unsigned_infinity 

return unsigned_infinity 

  

def py_eval_unsigned_infinity_for_doctests(): 

""" 

This function tests py_eval_unsigned_infinity. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_eval_unsigned_infinity_for_doctests as py_eval_unsigned_infinity 

sage: py_eval_unsigned_infinity() 

Infinity 

""" 

return py_eval_unsigned_infinity() 

  

cdef py_eval_infinity(): 

""" 

Returns positive infinity, i.e., oo. 

""" 

from sage.rings.infinity import infinity 

return infinity 

  

def py_eval_infinity_for_doctests(): 

""" 

This function tests py_eval_infinity. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_eval_infinity_for_doctests as py_eval_infinity 

sage: py_eval_infinity() 

+Infinity 

""" 

return py_eval_infinity() 

  

cdef py_eval_neg_infinity(): 

""" 

Returns minus_infinity. 

""" 

from sage.rings.infinity import minus_infinity 

return minus_infinity 

  

def py_eval_neg_infinity_for_doctests(): 

""" 

This function tests py_eval_neg_infinity. 

  

TESTS:: 

  

sage: from sage.libs.pynac.pynac import py_eval_neg_infinity_for_doctests as py_eval_neg_infinity 

sage: py_eval_neg_infinity() 

-Infinity 

""" 

return py_eval_neg_infinity() 

  

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

# Constructors 

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

  

cdef py_integer_from_long(long x): 

return smallInteger(x) 

  

cdef py_integer_from_python_obj(x): 

return Integer(x) 

  

cdef py_integer_from_mpz(mpz_t bigint): 

cdef Integer z = PY_NEW(Integer) 

mpz_set(z.value, bigint) 

return z 

  

cdef py_rational_from_mpq(mpq_t bigrat): 

cdef Rational rat = Rational.__new__(Rational) 

mpq_set(rat.value, bigrat) 

mpq_canonicalize(rat.value) 

return rat 

  

cdef bint py_is_Integer(x): 

return isinstance(x, Integer) 

  

cdef bint py_is_Rational(x): 

return isinstance(x, Rational) 

  

cdef mpz_ptr py_mpz_from_integer(x): 

return <mpz_ptr>((<Integer>x).value) 

  

cdef mpq_ptr py_mpq_from_rational(x): 

return <mpq_ptr>((<Rational>x).value) 

  

ZERO = ring.SR(0) 

ONE = ring.SR(1) 

ONE_HALF = ring.SR(Rational((1,2))) 

  

symbol_table = {'functions':{}} 

def register_symbol(obj, conversions): 

""" 

Add an object to the symbol table, along with how to convert it to 

other systems such as Maxima, Mathematica, etc. This table is used 

to convert *from* other systems back to Sage. 

  

INPUT: 

  

- `obj` -- a symbolic object or function. 

  

- `conversions` -- a dictionary of conversions, where the keys 

are the names of interfaces (e.g., 

'maxima'), and the values are the string 

representation of obj in that system. 

  

  

  

EXAMPLES:: 

  

sage: sage.libs.pynac.pynac.register_symbol(SR(5),{'maxima':'five'}) 

sage: SR(maxima_calculus('five')) 

5 

""" 

conversions = dict(conversions) 

try: 

conversions['sage'] = obj.name() 

except AttributeError: 

pass 

for system, value in conversions.iteritems(): 

system_table = symbol_table.get(system, None) 

if system_table is None: 

symbol_table[system] = system_table = {} 

system_table[value] = obj 

  

  

  

import sage.rings.integer 

ginac_pyinit_Integer(sage.rings.integer.Integer) 

  

import sage.rings.real_double 

ginac_pyinit_Float(sage.rings.real_double.RDF) 

  

cdef Element pynac_I 

I = None 

  

def init_pynac_I(): 

""" 

Initialize the numeric I object in pynac. We use the generator of QQ(i). 

  

EXAMPLES:: 

  

sage: I 

I 

sage: I^2 

-1 

  

Note that conversions to real fields will give TypeErrors:: 

  

sage: float(I) 

Traceback (most recent call last): 

... 

TypeError: unable to simplify to float approximation 

sage: gp(I) 

I 

sage: RR(I) 

Traceback (most recent call last): 

... 

TypeError: unable to convert '1.00000000000000*I' to a real number 

  

We can convert to complex fields:: 

  

sage: C = ComplexField(200); C 

Complex Field with 200 bits of precision 

sage: C(I) 

1.0000000000000000000000000000000000000000000000000000000000*I 

sage: I._complex_mpfr_field_(ComplexField(53)) 

1.00000000000000*I 

  

sage: I._complex_double_(CDF) 

1.0*I 

sage: CDF(I) 

1.0*I 

  

sage: z = I + I; z 

2*I 

sage: C(z) 

2.0000000000000000000000000000000000000000000000000000000000*I 

sage: 1e8*I 

1.00000000000000e8*I 

  

sage: complex(I) 

1j 

  

sage: QQbar(I) 

I 

  

sage: abs(I) 

1 

  

sage: I.minpoly() 

x^2 + 1 

sage: maxima(2*I) 

2*%i 

  

TESTS: 

  

sage: repr(I) 

'I' 

sage: latex(I) 

i 

  

sage: sage.libs.pynac.pynac.init_pynac_I() 

sage: type(sage.libs.pynac.pynac.I) 

<type 'sage.symbolic.expression.Expression'> 

sage: type(sage.libs.pynac.pynac.I.pyobject()) 

<type 'sage.rings.number_field.number_field_element_quadratic.NumberFieldElement_quadratic'> 

  

Check that :trac:`10064` is fixed:: 

  

sage: y = I*I*x / x # so y is the expression -1 

sage: y.is_positive() 

False 

sage: z = -x / x 

sage: z.is_positive() 

False 

sage: bool(z == y) 

True 

""" 

global pynac_I, I 

from sage.rings.number_field.number_field import QuadraticField 

K = QuadraticField(-1, 'I', embedding=CC.gen(), latex_name='i') 

pynac_I = K.gen() 

ginac_pyinit_I(pynac_I) 

I = new_Expression_from_GEx(ring.SR, g_I) 

  

  

def init_function_table(): 

""" 

Initializes the function pointer table in Pynac. This must be 

called before Pynac is used; otherwise, there will be segfaults. 

""" 

  

py_funcs.py_gcd = &py_gcd 

py_funcs.py_lcm = &py_lcm 

py_funcs.py_real = &py_real 

py_funcs.py_imag = &py_imag 

py_funcs.py_numer = &py_numer 

py_funcs.py_denom = &py_denom 

  

py_funcs.py_is_rational = &py_is_rational 

py_funcs.py_is_real = &py_is_real 

py_funcs.py_is_integer = &py_is_integer 

py_funcs.py_is_equal = &py_is_equal 

py_funcs.py_is_even = &py_is_even 

py_funcs.py_is_prime = &py_is_prime 

py_funcs.py_is_exact = &py_is_exact 

  

py_funcs.py_integer_from_mpz = &py_integer_from_mpz 

py_funcs.py_rational_from_mpq = &py_rational_from_mpq 

py_funcs.py_integer_from_long = &py_integer_from_long 

py_funcs.py_integer_from_python_obj = &py_integer_from_python_obj 

py_funcs.py_is_Integer = &py_is_Integer 

py_funcs.py_is_Rational = &py_is_Rational 

py_funcs.py_mpz_from_integer = &py_mpz_from_integer 

py_funcs.py_mpq_from_rational = &py_mpq_from_rational 

  

py_funcs.py_float = &py_float 

  

py_funcs.py_factorial = &py_factorial 

py_funcs.py_doublefactorial = &py_doublefactorial 

py_funcs.py_fibonacci = &py_fibonacci 

py_funcs.py_step = &py_step 

py_funcs.py_bernoulli = &py_bernoulli 

py_funcs.py_sin = &py_sin 

py_funcs.py_cos = &py_cos 

py_funcs.py_stieltjes = &py_stieltjes 

py_funcs.py_zeta = &py_zeta 

py_funcs.py_exp = &py_exp 

py_funcs.py_log = &py_log 

py_funcs.py_tan = &py_tan 

py_funcs.py_asin = &py_asin 

py_funcs.py_acos = &py_acos 

py_funcs.py_atan = &py_atan 

py_funcs.py_atan2 = &py_atan2 

py_funcs.py_sinh = &py_sinh 

py_funcs.py_cosh = &py_cosh 

py_funcs.py_tanh = &py_tanh 

py_funcs.py_asinh = &py_asinh 

py_funcs.py_acosh = &py_acosh 

py_funcs.py_atanh = &py_atanh 

py_funcs.py_isqrt = &py_isqrt 

py_funcs.py_sqrt = &py_sqrt 

py_funcs.py_mod = &py_mod 

py_funcs.py_smod = &py_smod 

py_funcs.py_irem = &py_irem 

py_funcs.py_psi = &py_psi 

py_funcs.py_psi2 = &py_psi2 

  

py_funcs.py_eval_constant = &py_eval_constant 

py_funcs.py_eval_unsigned_infinity = &py_eval_unsigned_infinity 

py_funcs.py_eval_infinity = &py_eval_infinity 

py_funcs.py_eval_neg_infinity = &py_eval_neg_infinity 

  

py_funcs.py_get_parent_char = &py_get_parent_char 

  

py_funcs.py_latex = &py_latex 

py_funcs.py_repr = &py_repr 

  

py_funcs.py_dumps = &py_dumps 

py_funcs.py_loads = &py_loads 

  

py_funcs.exvector_to_PyTuple = &exvector_to_PyTuple 

py_funcs.pyExpression_to_ex = &pyExpression_to_ex 

py_funcs.ex_to_pyExpression = &ex_to_pyExpression 

py_funcs.subs_args_to_PyTuple = &subs_args_to_PyTuple 

py_funcs.py_print_function = &py_print_function 

py_funcs.py_latex_function = &py_latex_function 

py_funcs.py_get_ginac_serial = &py_get_ginac_serial 

py_funcs.py_get_sfunction_from_serial = &py_get_sfunction_from_serial 

py_funcs.py_get_serial_from_sfunction = &py_get_serial_from_sfunction 

py_funcs.py_get_serial_for_new_sfunction = &py_get_serial_for_new_sfunction 

  

py_funcs.py_get_constant = &py_get_constant 

py_funcs.py_print_fderivative = &py_print_fderivative 

py_funcs.py_latex_fderivative = &py_latex_fderivative 

py_funcs.paramset_to_PyTuple = &paramset_to_PyTuple 

  

init_function_table() 

init_pynac_I() 

  

set_ginac_fn_serial()