Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

r""" 

Elements 

  

AUTHORS: 

  

- David Harvey (2006-10-16): changed CommutativeAlgebraElement to 

derive from CommutativeRingElement instead of AlgebraElement 

  

- David Harvey (2006-10-29): implementation and documentation of new 

arithmetic architecture 

  

- William Stein (2006-11): arithmetic architecture -- pushing it 

through to completion. 

  

- Gonzalo Tornaria (2007-06): recursive base extend for coercion -- 

lots of tests 

  

- Robert Bradshaw (2007-2010): arithmetic operators and coercion 

  

- Maarten Derickx (2010-07): added architecture for is_square and sqrt 

  

- Jeroen Demeyer (2016-08): moved all coercion to the base class 

:class:`Element`, see :trac:`20767` 

  

The Abstract Element Class Hierarchy 

==================================== 

  

This is the abstract class hierarchy, i.e., these are all 

abstract base classes. 

  

:: 

  

SageObject 

Element 

ModuleElement 

RingElement 

CommutativeRingElement 

IntegralDomainElement 

DedekindDomainElement 

PrincipalIdealDomainElement 

EuclideanDomainElement 

FieldElement 

CommutativeAlgebraElement 

AlgebraElement (note -- can't derive from module, since no multiple inheritance) 

Matrix 

InfinityElement 

AdditiveGroupElement 

Vector 

  

MonoidElement 

MultiplicativeGroupElement 

ElementWithCachedMethod 

  

  

How to Define a New Element Class 

================================= 

  

Elements typically define a method ``_new_c``, e.g., 

  

.. code-block:: cython 

  

cdef _new_c(self, defining data): 

cdef FreeModuleElement_generic_dense x 

x = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense) 

x._parent = self._parent 

x._entries = v 

  

that creates a new sibling very quickly from defining data 

with assumed properties. 

  

.. _element_arithmetic: 

  

Arithmetic for Elements 

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

  

Sage has a special system for handling arithmetic operations on Sage 

elements (that is instances of :class:`Element`), in particular to 

manage uniformly mixed arithmetic operations using the :mod:`coercion 

model <sage.structure.coerce>`. We describe here the rules that must 

be followed by both arithmetic implementers and callers. 

  

A quick summary for the impatient 

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

  

To implement addition for any :class:`Element` subclass, override the 

``def _add_(self, other)`` method instead of the usual Python 

``__add__`` :python:`special method <reference/datamodel.html#special-method-names>`. 

Within ``_add_(self, other)``, you may assume that ``self`` and 

``other`` have the same parent. 

  

If the implementation is generic across all elements in a given 

category `C`, then this method can be put in ``C.ElementMethods``. 

  

When writing *Cython* code, ``_add_`` should be a cpdef method: 

``cpdef _add_(self, other)``. 

  

When doing arithmetic with two elements having different parents, 

the :mod:`coercion model <sage.structure.coerce>` is responsible for 

"coercing" them to a common parent and performing arithmetic on the 

coerced elements. 

  

Arithmetic in more detail 

^^^^^^^^^^^^^^^^^^^^^^^^^ 

  

The aims of this system are to provide (1) an efficient calling protocol 

from both Python and Cython, (2) uniform coercion semantics across Sage, 

(3) ease of use, (4) readability of code. 

  

We will take addition as an example; all other operators are similar. 

There are two relevant functions, with differing names 

(single vs. double underscores). 

  

- **def Element.__add__(left, right)** 

  

This function is called by Python or Cython when the binary "+" 

operator is encountered. It assumes that at least one of its 

arguments is an :class:`Element`. 

  

It has a fast pathway to deal with the most common case where both 

arguments have the same parent. Otherwise, it uses the coercion 

model to work out how to make them have the same parent. The 

coercion model then adds the coerced elements (technically, it calls 

``operator.add``). Note that the result of coercion is not required 

to be a Sage :class:`Element`, it could be a plain Python type. 

  

Note that, although this function is declared as ``def``, it doesn't 

have the usual overheads associated with Python functions (either 

for the caller or for ``__add__`` itself). This is because Python 

has optimised calling protocols for such special functions. 

  

- **def Element._add_(self, other)** 

  

This is the function that you should override to implement addition 

in a subclass of :class:`Element`. 

  

The two arguments to this function are guaranteed to have the **same 

parent**, but not necessarily the same Python type. 

  

When implementing ``_add_`` in a Cython extension type, use 

``cpdef _add_`` instead of ``def _add_``. 

  

In Cython code, if you want to add two elements and you know that 

their parents are identical, you are encouraged to call this 

function directly, instead of using ``x + y``. This only works if 

Cython knows that the left argument is an ``Element``. You can 

always cast explicitly: ``(<Element>x)._add_(y)`` to force this. 

In plain Python, ``x + y`` is always the fastest way to add two 

elements because the special method ``__add__`` is optimized 

unlike the normal method ``_add_``. 

  

The difference in the names of the arguments (``left, right`` 

versus ``self, other``) is intentional: ``self`` is guaranteed to be an 

instance of the class in which the method is defined. In Cython, we know 

that at least one of ``left`` or ``right`` is an instance of the class 

but we do not know a priori which one. 

  

Powering is a special case: first of all, the 3-argument version of 

``pow()`` is not supported. Second, the coercion model checks whether 

the exponent looks like an integer. If so, the function ``_pow_int`` 

is called. If the exponent is not an integer, the arguments are coerced 

to a common parent and ``_pow_`` is called. So, if your type only 

supports powering to an integer exponent, you should implement only 

``_pow_int``. If you want to support arbitrary powering, implement both 

``_pow_`` and ``_pow_int``. 

  

For addition, multiplication and powering (not for other operators), 

there is a fast path for operations with a C ``long``. For example, 

implement ``cdef _add_long(self, long n)`` with optimized code for 

``self + n``. The addition and multiplication are assumed to be 

commutative, so they are also called for ``n + self`` or ``n * self``. 

From Cython code, you can also call ``_add_long`` or ``_mul_long`` 

directly. This is strictly an optimization: there is a default 

implementation falling back to the generic arithmetic function. 

  

Examples 

^^^^^^^^ 

  

We need some :class:`Parent` to work with:: 

  

sage: from sage.structure.parent import Parent 

sage: class ExampleParent(Parent): 

....: def __init__(self, name, **kwds): 

....: Parent.__init__(self, **kwds) 

....: self.rename(name) 

  

We start with a very basic example of a Python class implementing 

``_add_``:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _add_(self, other): 

....: return 42 

sage: p = ExampleParent("Some parent") 

sage: x = MyElement(p) 

sage: x + x 

42 

  

When two different parents are involved, this no longer works since 

there is no coercion:: 

  

sage: q = ExampleParent("Other parent") 

sage: y = MyElement(q) 

sage: x + y 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: 'Some parent' and 'Other parent' 

  

If ``_add_`` is not defined, an error message is raised, referring to 

the parents:: 

  

sage: x = Element(p) 

sage: x._add_(x) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_add_' 

sage: x + x 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: 'Some parent' and 'Some parent' 

sage: y = Element(q) 

sage: x + y 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: 'Some parent' and 'Other parent' 

  

We can also implement arithmetic generically in categories:: 

  

sage: class MyCategory(Category): 

....: def super_categories(self): 

....: return [Sets()] 

....: class ElementMethods: 

....: def _add_(self, other): 

....: return 42 

sage: p = ExampleParent("Parent in my category", category=MyCategory()) 

sage: x = Element(p) 

sage: x + x 

42 

  

Implementation details 

^^^^^^^^^^^^^^^^^^^^^^ 

  

Implementing the above features actually takes a bit of magic. Casual 

callers and implementers can safely ignore it, but here are the 

details for the curious. 

  

To achieve fast arithmetic, it is critical to have a fast path in Cython 

to call the ``_add_`` method of a Cython object. So we would like 

to declare ``_add_`` as a ``cpdef`` method of class :class:`Element`. 

Remember however that the abstract classes coming 

from categories come after :class:`Element` in the method resolution 

order (or fake method resolution order in case of a Cython 

class). Hence any generic implementation of ``_add_`` in such an 

abstract class would in principle be shadowed by ``Element._add_``. 

This is worked around by defining ``Element._add_`` as a ``cdef`` 

instead of a ``cpdef`` method. Concrete implementations in subclasses 

should be ``cpdef`` or ``def`` methods. 

  

Let us now see what happens upon evaluating ``x + y`` when ``x`` and ``y`` 

are instances of a class that does not implement ``_add_`` but where 

``_add_`` is implemented in the category. 

First, ``x.__add__(y)`` is called, where ``__add__`` is implemented 

in :class:`Element`. 

Assuming that ``x`` and ``y`` have the same parent, a Cython call to 

``x._add_(y)`` will be done. 

The latter is implemented to trigger a Python level call to ``x._add_(y)`` 

which will succeed as desired. 

  

In case that Python code calls ``x._add_(y)`` directly, 

``Element._add_`` will be invisible, and the method lookup will 

continue down the MRO and find the ``_add_`` method in the category. 

""" 

  

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

# Copyright (C) 2006-2016 ... 

# Copyright (C) 2016 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 sage.ext.stdsage cimport * 

  

from cpython.ref cimport PyObject 

  

import types 

cdef add, sub, mul, div, truediv, floordiv, mod, pow 

cdef iadd, isub, imul, idiv, itruediv, ifloordiv, imod, ipow 

from operator import (add, sub, mul, truediv, floordiv, mod, pow, 

iadd, isub, imul, itruediv, ifloordiv, imod, ipow) 

try: 

from operator import div, idiv 

except ImportError: 

div = idiv = None 

  

cdef dict _coerce_op_symbols = dict( 

add='+', sub='-', mul='*', div='/', truediv='/', floordiv='//', mod='%', pow='^', 

iadd='+', isub='-', imul='*', idiv='/', itruediv='/', ifloordiv='//', imod='%', ipow='^') 

  

from sage.structure.richcmp cimport rich_to_bool 

from sage.structure.coerce cimport py_scalar_to_element 

from sage.structure.parent cimport Parent 

from sage.cpython.type cimport can_assign_class 

from sage.cpython.getattr cimport getattr_from_other_class 

from sage.misc.lazy_format import LazyFormat 

from sage.misc import sageinspect 

from sage.misc.classcall_metaclass cimport ClasscallMetaclass 

from sage.misc.superseded import deprecated_function_alias 

from sage.arith.long cimport integer_check_long_py 

from sage.arith.power cimport generic_power as arith_generic_power 

from sage.arith.numerical_approx cimport digits_to_bits 

from sage.misc.decorators import sage_wraps 

  

  

def make_element(_class, _dict, parent): 

""" 

This function is only here to support old pickles. 

  

Pickling functionality is moved to Element.{__getstate__,__setstate__} 

functions. 

""" 

from sage.misc.pickle_old import make_element_old 

return make_element_old(_class, _dict, parent) 

  

  

cdef unary_op_exception(op, x): 

try: 

op = op.__name__ 

op = _coerce_op_symbols[op] 

except (AttributeError, KeyError): 

pass 

px = parent(x) 

return TypeError(f"unsupported operand parent for {op}: '{px}'") 

  

  

cdef bin_op_exception(op, x, y): 

try: 

op = op.__name__ 

op = _coerce_op_symbols[op] 

except (AttributeError, KeyError): 

pass 

px = parent(x) 

py = parent(y) 

return TypeError(f"unsupported operand parent(s) for {op}: '{px}' and '{py}'") 

  

  

def is_Element(x): 

""" 

Return ``True`` if x is of type Element. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import is_Element 

sage: is_Element(2/3) 

True 

sage: is_Element(QQ^3) 

False 

""" 

return isinstance(x, Element) 

  

  

cdef class Element(SageObject): 

""" 

Generic element of a structure. All other types of elements 

(:class:`RingElement`, :class:`ModuleElement`, etc) 

derive from this type. 

  

Subtypes must either call ``__init__()`` to set ``_parent``, or may 

set ``_parent`` themselves if that would be more efficient. 

  

.. automethod:: _cmp_ 

.. automethod:: _richcmp_ 

.. automethod:: __add__ 

.. automethod:: __sub__ 

.. automethod:: __neg__ 

.. automethod:: __mul__ 

.. automethod:: __div__ 

.. automethod:: __truediv__ 

.. automethod:: __floordiv__ 

.. automethod:: __mod__ 

""" 

def __getmetaclass__(_): 

from sage.misc.inherit_comparison import InheritComparisonMetaclass 

return InheritComparisonMetaclass 

  

def __init__(self, parent): 

r""" 

INPUT: 

  

- ``parent`` - a SageObject 

""" 

self._parent = parent 

  

def _set_parent(self, parent): 

r""" 

Set the parent of ``self`` to ``parent``. 

  

INPUT: 

  

- ``parent`` -- a :class:`Parent` 

  

.. WARNING:: 

  

Changing the parent of an object is not something you 

should normally need. It is mainly meant for constructing a 

new element from scratch, when ``__new__`` or ``__init__`` 

did not set the right parent. Using this method incorrectly 

can break things badly. 

  

EXAMPLES:: 

  

sage: q = 3/5 

sage: parent(q) 

Rational Field 

sage: q._set_parent(CC) 

sage: parent(q) 

Complex Field with 53 bits of precision 

sage: q._set_parent(float) 

Traceback (most recent call last): 

... 

TypeError: Cannot convert type to sage.structure.parent.Parent 

""" 

self._parent = <Parent?>parent 

  

def __getattr__(self, name): 

""" 

Lookup a method or attribute from the category abstract classes. 

  

Let ``P`` be a parent in a category ``C``. Usually the methods 

of ``C.element_class`` are made directly available to elements 

of ``P`` via standard class inheritance. This is not the case 

any more if the elements of ``P`` are instances of an 

extension type. See :class:`Category` for details. 

  

The purpose of this method is to emulate this inheritance: for 

``e`` and element of ``P``, if an attribute or method 

``e.foo`` is not found in the super classes of ``e``, it's 

looked up manually in ``C.element_class`` and bound to ``e``. 

  

.. NOTE:: 

  

- The attribute or method is actually looked up in 

``P._abstract_element_class``. In most cases this is 

just an alias for ``C.element_class``, but some parents, 

notably homsets, customizes this to let elements also 

inherit from other abstract classes. See 

:meth:`Parent._abstract_element_class` and 

:meth:`Homset._abstract_element_class` for details. 

  

- This mechanism may also enter into action when the 

category of `P` is refined on the fly, leaving 

previously constructed elements in an outdated element 

class. 

  

See :class:`~sage.rings.polynomial.polynomial_quotient_ring.PolynomialQuotientRing_generic` 

for an example. 

  

EXAMPLES: 

  

We test that ``1`` (an instance of the extension type 

``Integer``) inherits the methods from the categories of 

``ZZ``, that is from ``CommutativeRings().element_class``:: 

  

sage: 1.is_idempotent(), 2.is_idempotent() 

(True, False) 

  

This method is actually provided by the ``Magmas()`` super 

category of ``CommutativeRings()``:: 

  

sage: 1.is_idempotent 

<bound method JoinCategory.element_class.is_idempotent of 1> 

sage: 1.is_idempotent.__module__ 

'sage.categories.magmas' 

  

TESTS:: 

  

sage: 1.blah_blah 

Traceback (most recent call last): 

... 

AttributeError: 'sage.rings.integer.Integer' object has no attribute 'blah_blah' 

sage: Semigroups().example().an_element().is_idempotent 

<bound method LeftZeroSemigroup_with_category.element_class.is_idempotent of 42> 

sage: Semigroups().example().an_element().blah_blah 

Traceback (most recent call last): 

... 

AttributeError: 'LeftZeroSemigroup_with_category.element_class' object has no attribute 'blah_blah' 

""" 

return self.getattr_from_category(name) 

  

cdef getattr_from_category(self, name): 

# Lookup a method or attribute from the category abstract classes. 

# See __getattr__ above for documentation. 

cdef Parent P = self._parent 

if P is None: 

# This is highly unlikely but we deal with it anyway... 

# Usually, this will just raise AttributeError in 

# getattr_from_other_class(). 

cls = type 

else: 

cls = P._abstract_element_class 

return getattr_from_other_class(self, cls, name) 

  

def __dir__(self): 

""" 

Let cat be the category of the parent of ``self``. This method 

emulates ``self`` being an instance of both ``Element`` and 

``cat.element_class``, in that order, for attribute directory. 

  

EXAMPLES:: 

  

sage: dir(1/2) 

['N', ..., 'is_idempotent', 'is_integer', 'is_integral', ...] 

  

Caveat: dir on Integer's and some other extension types seem to ignore __dir__:: 

  

sage: 1.__dir__() 

['N', ..., 'is_idempotent', 'is_integer', 'is_integral', ...] 

sage: dir(1) # todo: not implemented 

['N', ..., 'is_idempotent', 'is_integer', 'is_integral', ...] 

""" 

from sage.cpython.getattr import dir_with_other_class 

return dir_with_other_class(self, self.parent().category().element_class) 

  

def _repr_(self): 

return "Generic element of a structure" 

  

def __getstate__(self): 

""" 

Return a tuple describing the state of your object. 

  

This should return all information that will be required to unpickle 

the object. The functionality for unpickling is implemented in 

__setstate__(). 

  

TESTS:: 

  

sage: R.<x,y> = QQ[] 

sage: i = ideal(x^2 - y^2 + 1) 

sage: i.__getstate__() 

(Monoid of ideals of Multivariate Polynomial Ring in x, y over Rational Field, 

{'_Ideal_generic__gens': (x^2 - y^2 + 1,), 

'_Ideal_generic__ring': Multivariate Polynomial Ring in x, y over Rational Field, 

'_gb_by_ordering': {}}) 

""" 

return (self._parent, self.__dict__) 

  

def __setstate__(self, state): 

""" 

Initializes the state of the object from data saved in a pickle. 

  

During unpickling __init__ methods of classes are not called, the saved 

data is passed to the class via this function instead. 

  

TESTS:: 

  

sage: R.<x,y> = QQ[] 

sage: i = ideal(x); i 

Ideal (x) of Multivariate Polynomial Ring in x, y over Rational Field 

sage: S.<x,y,z> = ZZ[] 

sage: i.__setstate__((R,{'_Ideal_generic__ring':S,'_Ideal_generic__gens': (S(x^2 - y^2 + 1),)})) 

sage: i 

Ideal (x^2 - y^2 + 1) of Multivariate Polynomial Ring in x, y, z over Integer Ring 

""" 

self._set_parent(state[0]) 

self.__dict__ = state[1] 

  

def __copy__(self): 

""" 

Return a copy of ``self``. 

  

OUTPUT: 

  

- a new object which is a copy of ``self``. 

  

This implementation ensures that ``self.__dict__`` is properly copied 

when it exists (typically for instances of classes deriving from 

:class:`Element`). 

  

TESTS:: 

  

sage: from sage.structure.element import Element 

sage: el = Element(parent = ZZ) 

sage: el1 = copy(el) 

sage: el1 is el 

False 

  

sage: class Demo(Element): pass 

sage: el = Demo(parent = ZZ) 

sage: el.x = [1,2,3] 

sage: el1 = copy(el) 

sage: el1 is el 

False 

sage: el1.__dict__ is el.__dict__ 

False 

""" 

cls = self.__class__ 

cdef Element res = cls.__new__(cls) 

res._parent = self._parent 

try: 

D = self.__dict__ 

except AttributeError: 

return res 

for k,v in D.iteritems(): 

try: 

setattr(res, k, v) 

except AttributeError: 

pass 

return res 

  

def _im_gens_(self, codomain, im_gens): 

""" 

Return the image of ``self`` in codomain under the map that sends 

the images of the generators of the parent of ``self`` to the 

tuple of elements of im_gens. 

""" 

raise NotImplementedError 

  

cpdef base_extend(self, R): 

cdef Parent V 

V = self._parent.base_extend(R) 

return V.coerce(self) 

  

def base_ring(self): 

""" 

Return the base ring of this element's parent (if that makes sense). 

  

TESTS:: 

  

sage: QQ.base_ring() 

Rational Field 

sage: identity_matrix(3).base_ring() 

Integer Ring 

""" 

return self._parent.base_ring() 

  

def category(self): 

from sage.categories.all import Elements 

return Elements(self._parent) 

  

def _test_new(self, **options): 

""" 

Check that ``cls.__new__(cls)`` and 

``cls.__new__(cls, parent)`` do not crash Python, 

where ``cls = type(self)`` and ``parent = parent(self)``. 

  

It is perfectly legal for ``__new__`` to raise ordinary 

exceptions. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import Element 

sage: p = Parent() 

sage: e = Element(p) 

sage: e._test_new() 

""" 

cdef type cls = type(self) 

try: 

cls.__new__(cls) 

except Exception: 

pass 

try: 

cls.__new__(cls, self._parent) 

except Exception: 

pass 

  

def _test_category(self, **options): 

""" 

Run generic tests on the method :meth:`.category`. 

  

See also: :class:`TestSuite`. 

  

EXAMPLES:: 

  

sage: 3._test_category() 

  

Let us now write a broken :meth:`.category` method:: 

  

sage: from sage.categories.examples.sets_cat import PrimeNumbers 

sage: class CCls(PrimeNumbers): 

....: def an_element(self): 

....: return 18 

sage: CC = CCls() 

sage: CC._test_an_element() 

Traceback (most recent call last): 

... 

AssertionError: self.an_element() is not in self 

""" 

from sage.categories.objects import Objects 

tester = self._tester(**options) 

SageObject._test_category(self, tester = tester) 

category = self.category() 

# Tests that self inherits methods from the categories 

if can_assign_class(self): 

# For usual Python classes, that should be done with 

# standard inheritance 

tester.assertTrue(isinstance(self, self.parent().category().element_class)) 

else: 

# For extension types we just check that inheritance 

# occurs on a dummy attribute of Sets().ElementMethods 

tester.assertTrue(hasattr(self, "_dummy_attribute")) 

  

def _test_eq(self, **options): 

""" 

Test that ``self`` is equal to ``self`` and different to ``None``. 

  

See also: :class:`TestSuite`. 

  

TESTS:: 

  

sage: from sage.structure.element import Element 

sage: O = Element(Parent()) 

sage: O._test_eq() 

  

Let us now write a broken class method:: 

  

sage: class CCls(Element): 

....: def __eq__(self, other): 

....: return True 

sage: CCls(Parent())._test_eq() 

Traceback (most recent call last): 

... 

AssertionError: broken equality: Generic element of a structure == None 

  

Let us now break inequality:: 

  

sage: class CCls(Element): 

....: def __ne__(self, other): 

....: return True 

sage: CCls(Parent())._test_eq() 

Traceback (most recent call last): 

... 

AssertionError: broken non-equality: Generic element of a structure != itself 

""" 

tester = self._tester(**options) 

# We don't use assertEqual / assertNonEqual in order to be 

# 100% sure we indeed call the operators == and !=, whatever 

# the version of Python is (see #11236) 

tester.assertTrue(self == self, 

LazyFormat("broken equality: %s == itself is False")%self) 

tester.assertFalse(self == None, 

LazyFormat("broken equality: %s == None")%self) 

tester.assertFalse(self != self, 

LazyFormat("broken non-equality: %s != itself")%self) 

tester.assertTrue(self != None, 

LazyFormat("broken non-equality: %s is not != None")%self) 

  

def parent(self, x=None): 

""" 

Return the parent of this element; or, if the optional argument x is 

supplied, the result of coercing x into the parent of this element. 

""" 

if x is None: 

return self._parent 

else: 

return self._parent(x) 

  

  

def subs(self, in_dict=None, **kwds): 

""" 

Substitutes given generators with given values while not touching 

other generators. This is a generic wrapper around ``__call__``. 

The syntax is meant to be compatible with the corresponding method 

for symbolic expressions. 

  

INPUT: 

  

- ``in_dict`` - (optional) dictionary of inputs 

  

- ``**kwds`` - named parameters 

  

OUTPUT: 

  

- new object if substitution is possible, otherwise self. 

  

EXAMPLES:: 

  

sage: x, y = PolynomialRing(ZZ,2,'xy').gens() 

sage: f = x^2 + y + x^2*y^2 + 5 

sage: f((5,y)) 

25*y^2 + y + 30 

sage: f.subs({x:5}) 

25*y^2 + y + 30 

sage: f.subs(x=5) 

25*y^2 + y + 30 

sage: (1/f).subs(x=5) 

1/(25*y^2 + y + 30) 

sage: Integer(5).subs(x=4) 

5 

""" 

if not hasattr(self, '__call__'): 

return self 

parent = self._parent 

try: 

ngens = parent.ngens() 

except (AttributeError, NotImplementedError, TypeError): 

return self 

variables=[] 

# use "gen" instead of "gens" as a ParentWithGens is not 

# required to have the latter 

for i in xrange(0,ngens): 

gen=parent.gen(i) 

if str(gen) in kwds: 

variables.append(kwds[str(gen)]) 

elif in_dict and gen in in_dict: 

variables.append(in_dict[gen]) 

else: 

variables.append(gen) 

return self(*variables) 

  

def numerical_approx(self, prec=None, digits=None, algorithm=None): 

""" 

Return a numerical approximation of ``self`` with ``prec`` bits 

(or decimal ``digits``) of precision. 

  

No guarantee is made about the accuracy of the result. 

  

INPUT: 

  

- ``prec`` -- precision in bits 

  

- ``digits`` -- precision in decimal digits (only used if 

``prec`` is not given) 

  

- ``algorithm`` -- which algorithm to use to compute this 

approximation (the accepted algorithms depend on the object) 

  

If neither ``prec`` nor ``digits`` is given, the default 

precision is 53 bits (roughly 16 digits). 

  

EXAMPLES:: 

  

sage: (2/3).numerical_approx() 

0.666666666666667 

sage: pi.n(digits=10) 

3.141592654 

sage: pi.n(prec=20) 

3.1416 

  

TESTS: 

  

Check that :trac:`14778` is fixed:: 

  

sage: (0).n(algorithm='foo') 

0.000000000000000 

  

The ``.N`` method is a deprecated alias:: 

  

sage: 0.N() 

doctest:...: DeprecationWarning: N is deprecated. Please use n instead. 

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

0.000000000000000 

""" 

from sage.arith.numerical_approx import numerical_approx_generic 

if prec is None: 

prec = digits_to_bits(digits) 

return numerical_approx_generic(self, prec) 

  

def n(self, prec=None, digits=None, algorithm=None): 

""" 

Alias for :meth:`numerical_approx`. 

  

EXAMPLES:: 

  

sage: (2/3).n() 

0.666666666666667 

""" 

return self.numerical_approx(prec, digits, algorithm) 

  

N = deprecated_function_alias(13055, n) 

  

def _mpmath_(self, prec=53, rounding=None): 

""" 

Evaluates numerically and returns an mpmath number. 

Used as fallback for conversion by mpmath.mpmathify(). 

  

.. NOTE:: 

  

Currently, the rounding mode is ignored. 

  

EXAMPLES:: 

  

sage: from sage.libs.mpmath.all import mp, mpmathify 

sage: mp.dps = 30 

sage: 25._mpmath_(53) 

mpf('25.0') 

sage: mpmathify(3+4*I) 

mpc(real='3.0', imag='4.0') 

sage: mpmathify(1+pi) 

mpf('4.14159265358979323846264338327933') 

sage: (1+pi)._mpmath_(10) 

mpf('4.140625') 

sage: (1+pi)._mpmath_(mp.prec) 

mpf('4.14159265358979323846264338327933') 

""" 

return self.n(prec)._mpmath_(prec=prec) 

  

def substitute(self,in_dict=None,**kwds): 

""" 

This is an alias for self.subs(). 

  

INPUT: 

  

- ``in_dict`` - (optional) dictionary of inputs 

  

- ``**kwds`` - named parameters 

  

OUTPUT: 

  

- new object if substitution is possible, otherwise self. 

  

EXAMPLES:: 

  

sage: x, y = PolynomialRing(ZZ,2,'xy').gens() 

sage: f = x^2 + y + x^2*y^2 + 5 

sage: f((5,y)) 

25*y^2 + y + 30 

sage: f.substitute({x:5}) 

25*y^2 + y + 30 

sage: f.substitute(x=5) 

25*y^2 + y + 30 

sage: (1/f).substitute(x=5) 

1/(25*y^2 + y + 30) 

sage: Integer(5).substitute(x=4) 

5 

""" 

return self.subs(in_dict,**kwds) 

  

cpdef _act_on_(self, x, bint self_on_left): 

""" 

Use this method to implement ``self`` acting on ``x``. 

  

Return None or raise a CoercionException if no 

such action is defined here. 

""" 

return None 

  

cpdef _acted_upon_(self, x, bint self_on_left): 

""" 

Use this method to implement ``self`` acted on by x. 

  

Return None or raise a CoercionException if no 

such action is defined here. 

""" 

return None 

  

  

def __xor__(self, right): 

raise RuntimeError("Use ** for exponentiation, not '^', which means xor\n"+\ 

"in Python, and has the wrong precedence.") 

  

def __pos__(self): 

return self 

  

def _coeff_repr(self, no_space=True): 

if self._is_atomic(): 

s = repr(self) 

else: 

s = "(%s)"%repr(self) 

if no_space: 

return s.replace(' ','') 

return s 

  

def _latex_coeff_repr(self): 

try: 

s = self._latex_() 

except AttributeError: 

s = str(self) 

if self._is_atomic(): 

return s 

else: 

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

  

def _is_atomic(self): 

""" 

Return ``True`` if and only if parenthesis are not required when 

*printing* out any of `x - s`, `x + s`, `x^s` and `x/s`. 

  

EXAMPLES:: 

  

sage: n = 5; n._is_atomic() 

True 

sage: n = x+1; n._is_atomic() 

False 

""" 

if self._parent._repr_option('element_is_atomic'): 

return True 

s = str(self) 

return s.find("+") == -1 and s.find("-") == -1 and s.find(" ") == -1 

  

def __nonzero__(self): 

r""" 

Return whether this element is equal to ``self.parent()(0)``. 

  

Note that this is automatically called when converting to 

boolean, as in the conditional of an if or while statement. 

  

EXAMPLES:: 

  

sage: bool(1) # indirect doctest 

True 

  

If ``self.parent()(0)`` raises an exception (because there is no 

meaningful zero element,) then this method returns ``True``. Here, 

there is no zero morphism of rings that goes to a non-trivial ring:: 

  

sage: bool(Hom(ZZ, Zmod(2)).an_element()) 

True 

  

But there is a zero morphism to the trivial ring:: 

  

sage: bool(Hom(ZZ, Zmod(1)).an_element()) 

False 

  

TESTS: 

  

Verify that :trac:`5185` is fixed:: 

  

sage: v = vector({1: 1, 3: -1}) 

sage: w = vector({1: -1, 3: 1}) 

sage: v + w 

(0, 0, 0, 0) 

sage: (v+w).is_zero() 

True 

sage: bool(v+w) 

False 

sage: (v+w).__nonzero__() 

False 

  

""" 

try: 

zero = self._parent.zero() 

except Exception: 

return True # by convention 

  

return self != zero 

  

def is_zero(self): 

""" 

Return ``True`` if ``self`` equals ``self.parent()(0)``. 

  

The default implementation is to fall back to ``not 

self.__nonzero__``. 

  

.. WARNING:: 

  

Do not re-implement this method in your subclass but 

implement ``__nonzero__`` instead. 

""" 

return not self 

  

def _cache_key(self): 

""" 

Provide a hashable key for an element if it is not hashable 

  

EXAMPLES:: 

  

sage: a=sage.structure.element.Element(ZZ) 

sage: a._cache_key() 

(Integer Ring, 'Generic element of a structure') 

""" 

return(self.parent(),str(self)) 

  

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

# In a Cython or a Python class, you must define either _cmp_ 

# (if your subclass is totally ordered), _richcmp_ (if your subclass 

# is partially ordered), or both (if your class has both a total order 

# and a partial order, or if that gives better performance). 

# 

# Rich comparisons (like a < b) will default to using _richcmp_, 

# three-way comparisons (like cmp(a,b)) will default to using 

# _cmp_. But if you define just one of _richcmp_ and _cmp_, it will 

# be used for all kinds of comparisons. 

# 

# In the _cmp_ and _richcmp_ methods, you can assume that both 

# arguments have identical parents. 

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

def __richcmp__(self, other, int op): 

""" 

Compare ``self`` and ``other`` using the coercion framework, 

comparing according to the comparison operator ``op``. 

  

Normally, a class will not redefine ``__richcmp__`` but rely on 

this ``Element.__richcmp__`` method which uses coercion if 

needed to compare elements. After coercion (or if no coercion 

is needed), ``_richcmp_`` is called. 

  

If a class wants to implement rich comparison without coercion, 

then ``__richcmp__`` should be defined. 

See :class:`sage.numerical.linear_functions.LinearConstraint` 

for such an example. 

  

For efficiency reasons, a class can do certain "manual" 

coercions directly in ``__richcmp__``, using 

``coercion_model.richcmp()`` for the remaining cases. 

This is done for example in :class:`Integer`. 

""" 

if have_same_parent(self, other): 

# Same parents, in particular self and other must both be 

# an instance of Element. The explicit casts below make 

# Cython generate optimized code for this call. 

return (<Element>self)._richcmp_(other, op) 

else: 

return coercion_model.richcmp(self, other, op) 

  

cpdef _richcmp_(left, right, int op): 

r""" 

Default implementation of rich comparisons for elements with 

equal parents. 

  

It tries to see if ``_cmp_`` is implemented. Otherwise it does a 

comparison by id for ``==`` and ``!=``. Calling this default method 

with ``<``, ``<=``, ``>`` or ``>=`` will raise a 

``NotImplementedError``. 

  

EXAMPLES:: 

  

sage: from sage.structure.parent import Parent 

sage: from sage.structure.element import Element 

sage: P = Parent() 

sage: e1 = Element(P); e2 = Element(P) 

sage: e1 == e1 # indirect doctest 

True 

sage: e1 == e2 # indirect doctest 

False 

sage: e1 < e2 # indirect doctest 

Traceback (most recent call last): 

... 

NotImplementedError: comparison not implemented for <... 'sage.structure.element.Element'> 

  

We now create an ``Element`` class where we define ``_richcmp_`` 

and check that comparison works:: 

  

sage: cython(''' 

....: from sage.structure.richcmp cimport rich_to_bool 

....: from sage.structure.element cimport Element 

....: cdef class FloatCmp(Element): 

....: cdef float x 

....: def __init__(self, float v): 

....: self.x = v 

....: cpdef _richcmp_(self, other, int op): 

....: cdef float x1 = (<FloatCmp>self).x 

....: cdef float x2 = (<FloatCmp>other).x 

....: return rich_to_bool(op, (x1 > x2) - (x1 < x2)) 

....: ''') 

sage: a = FloatCmp(1) 

sage: b = FloatCmp(2) 

sage: a <= b, b <= a 

(True, False) 

  

This works despite ``_cmp_`` not being implemented:: 

  

sage: a._cmp_(b) 

Traceback (most recent call last): 

... 

NotImplementedError: comparison not implemented for <... '...FloatCmp'> 

""" 

# Obvious case 

if left is right: 

return rich_to_bool(op, 0) 

  

cdef int c 

try: 

c = left._cmp_(right) 

except NotImplementedError: 

# Check equality by id(), knowing that left is not right 

if op == Py_EQ: 

return False 

if op == Py_NE: 

return True 

raise 

assert -1 <= c <= 1 

return rich_to_bool(op, c) 

  

cpdef int _cmp_(left, right) except -2: 

""" 

Default three-way comparison method which only checks for a 

Python class defining ``__cmp__``. 

""" 

try: 

left_cmp = left.__cmp__ 

except AttributeError: 

pass 

else: 

return left_cmp(right) 

msg = LazyFormat("comparison not implemented for %r") % type(left) 

raise NotImplementedError(msg) 

  

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

# Arithmetic using the coercion model 

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

  

def __add__(left, right): 

""" 

Top-level addition operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _add_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e + e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e + e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 + e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e + 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) + e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for +: 'int' and 'sage.structure.element.Element' 

sage: e + int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for +: 'sage.structure.element.Element' and 'int' 

sage: None + e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for +: 'NoneType' and 'sage.structure.element.Element' 

sage: e + None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for +: 'sage.structure.element.Element' and 'NoneType' 

""" 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._add_(right) 

# Left and right are Sage elements => use coercion model 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, add) 

  

cdef long value 

cdef int err = -1 

try: 

# Special case addition with Python int 

integer_check_long_py(right, &value, &err) 

if not err: 

return (<Element>left)._add_long(value) 

integer_check_long_py(left, &value, &err) 

if not err: 

return (<Element>right)._add_long(value) 

return coercion_model.bin_op(left, right, add) 

except TypeError: 

# Either coercion failed or arithmetic is not defined. 

# 

# According to the Python convention, we should return 

# NotImplemented now. This will cause Python to try the 

# reversed addition (__radd__). 

return NotImplemented 

  

cdef _add_(self, other): 

""" 

Virtual addition method for elements with identical parents. 

  

This default Cython implementation of ``_add_`` calls the 

Python method ``self._add_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._add_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_add_' 

""" 

try: 

python_op = (<object>self)._add_ 

except AttributeError: 

raise bin_op_exception('+', self, other) 

else: 

return python_op(other) 

  

cdef _add_long(self, long n): 

""" 

Generic path for adding a C long, assumed to commute. 

  

EXAMPLES:: 

  

sage: cython( # long time 

....: ''' 

....: from sage.structure.element cimport Element 

....: cdef class MyElement(Element): 

....: cdef _add_long(self, long n): 

....: return n 

....: ''') 

sage: e = MyElement(Parent()) # long time 

sage: i = int(42) 

sage: i + e, e + i # long time 

(42, 42) 

""" 

return coercion_model.bin_op(self, n, add) 

  

def __sub__(left, right): 

""" 

Top-level subtraction operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _sub_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e - e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e - e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for -: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 - e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for -: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e - 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for -: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) - e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for -: 'int' and 'sage.structure.element.Element' 

sage: e - int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for -: 'sage.structure.element.Element' and 'int' 

sage: None - e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for -: 'NoneType' and 'sage.structure.element.Element' 

sage: e - None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for -: 'sage.structure.element.Element' and 'NoneType' 

""" 

# See __add__ for comments 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._sub_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, sub) 

  

try: 

return coercion_model.bin_op(left, right, sub) 

except TypeError: 

return NotImplemented 

  

cdef _sub_(self, other): 

""" 

Virtual subtraction method for elements with identical parents. 

  

This default Cython implementation of ``_sub_`` calls the 

Python method ``self._sub_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._sub_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_sub_' 

""" 

try: 

python_op = (<object>self)._sub_ 

except AttributeError: 

raise bin_op_exception('-', self, other) 

else: 

return python_op(other) 

  

def __neg__(self): 

""" 

Top-level negation operator for :class:`Element`. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _neg_(self): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: -e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: -e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent for unary -: '<sage.structure.parent.Parent object at ...>' 

""" 

return self._neg_() 

  

cdef _neg_(self): 

""" 

Virtual unary negation method for elements. 

  

This default Cython implementation of ``_neg_`` calls the 

Python method ``self._neg_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._neg_() 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_neg_' 

""" 

try: 

python_op = (<object>self)._neg_ 

except AttributeError: 

raise unary_op_exception('unary -', self) 

else: 

return python_op() 

  

def __mul__(left, right): 

""" 

Top-level multiplication operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _mul_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e * e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e * e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 * e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e * 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) * e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for *: 'int' and 'sage.structure.element.Element' 

sage: e * int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for *: 'sage.structure.element.Element' and 'int' 

sage: None * e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for *: 'NoneType' and 'sage.structure.element.Element' 

sage: e * None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for *: 'sage.structure.element.Element' and 'NoneType' 

  

:: 

  

sage: A = AlgebrasWithBasis(QQ).example(); A 

An example of an algebra with basis: the free algebra 

on the generators ('a', 'b', 'c') over Rational Field 

sage: x = A.an_element() 

sage: x 

B[word: ] + 2*B[word: a] + 3*B[word: b] + B[word: bab] 

sage: x.__mul__(x) 

B[word: ] + 4*B[word: a] + 4*B[word: aa] + 6*B[word: ab] 

+ 2*B[word: abab] + 6*B[word: b] + 6*B[word: ba] 

+ 2*B[word: bab] + 2*B[word: baba] + 3*B[word: babb] 

+ B[word: babbab] + 9*B[word: bb] + 3*B[word: bbab] 

""" 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._mul_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, mul) 

  

cdef long value 

cdef int err = -1 

try: 

# Special case multiplication with Python int 

integer_check_long_py(right, &value, &err) 

if not err: 

return (<Element>left)._mul_long(value) 

integer_check_long_py(left, &value, &err) 

if not err: 

return (<Element>right)._mul_long(value) 

return coercion_model.bin_op(left, right, mul) 

except TypeError: 

return NotImplemented 

  

cdef _mul_(self, other): 

""" 

Virtual multiplication method for elements with identical parents. 

  

This default Cython implementation of ``_mul_`` calls the 

Python method ``self._mul_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._mul_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_mul_' 

""" 

try: 

python_op = (<object>self)._mul_ 

except AttributeError: 

raise bin_op_exception('*', self, other) 

else: 

return python_op(other) 

  

cdef _mul_long(self, long n): 

""" 

Generic path for multiplying by a C long, assumed to commute. 

  

EXAMPLES:: 

  

sage: cython( # long time 

....: ''' 

....: from sage.structure.element cimport Element 

....: cdef class MyElement(Element): 

....: cdef _mul_long(self, long n): 

....: return n 

....: ''') 

sage: e = MyElement(Parent()) # long time 

sage: i = int(42) 

sage: i * e, e * i # long time 

(42, 42) 

""" 

return coercion_model.bin_op(self, n, mul) 

  

def __div__(left, right): 

""" 

Top-level division operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: 2 / 3 

2/3 

sage: pi / 3 

1/3*pi 

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

sage: 2 / K.ideal(i+1) 

Fractional ideal (-i + 1) 

  

:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _div_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e / e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e / e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for /: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 / e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for /: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e / 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for /: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) / e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'int' and 'sage.structure.element.Element' 

sage: e / int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'sage.structure.element.Element' and 'int' 

sage: None / e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'NoneType' and 'sage.structure.element.Element' 

sage: e / None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'sage.structure.element.Element' and 'NoneType' 

""" 

# See __add__ for comments 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._div_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, div) 

  

try: 

return coercion_model.bin_op(left, right, div) 

except TypeError: 

return NotImplemented 

  

def __truediv__(left, right): 

""" 

Top-level true division operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: operator.truediv(2, 3) 

2/3 

sage: operator.truediv(pi, 3) 

1/3*pi 

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

sage: operator.truediv(2, K.ideal(i+1)) 

Fractional ideal (-i + 1) 

  

:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _div_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: operator.truediv(e, e) 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: operator.truediv(e, e) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for /: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: operator.truediv(1, e) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for /: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: operator.truediv(e, 1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for /: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: operator.truediv(int(1), e) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'int' and 'sage.structure.element.Element' 

sage: operator.truediv(e, int(1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'sage.structure.element.Element' and 'int' 

sage: operator.truediv(None, e) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'NoneType' and 'sage.structure.element.Element' 

sage: operator.truediv(e, None) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for /: 'sage.structure.element.Element' and 'NoneType' 

""" 

# See __add__ for comments 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._div_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, truediv) 

  

try: 

return coercion_model.bin_op(left, right, truediv) 

except TypeError: 

return NotImplemented 

  

cdef _div_(self, other): 

""" 

Virtual division method for elements with identical parents. 

This is called for Python 2 division as well as true division. 

  

This default Cython implementation of ``_div_`` calls the 

Python method ``self._div_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._div_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_div_' 

""" 

try: 

python_op = (<object>self)._div_ 

except AttributeError: 

raise bin_op_exception('/', self, other) 

else: 

return python_op(other) 

  

def __floordiv__(left, right): 

""" 

Top-level floor division operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: 7 // 3 

2 

sage: 7 // int(3) 

2 

sage: int(7) // 3 

2 

  

:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _floordiv_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e // e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e // e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for //: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 // e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for //: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e // 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for //: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) // e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for //: 'int' and 'sage.structure.element.Element' 

sage: e // int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for //: 'sage.structure.element.Element' and 'int' 

sage: None // e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for //: 'NoneType' and 'sage.structure.element.Element' 

sage: e // None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for //: 'sage.structure.element.Element' and 'NoneType' 

""" 

# See __add__ for comments 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._floordiv_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, floordiv) 

  

try: 

return coercion_model.bin_op(left, right, floordiv) 

except TypeError: 

return NotImplemented 

  

cdef _floordiv_(self, other): 

""" 

Virtual floor division method for elements with identical parents. 

  

This default Cython implementation of ``_floordiv_`` calls the 

Python method ``self._floordiv_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._floordiv_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_floordiv_' 

""" 

try: 

python_op = (<object>self)._floordiv_ 

except AttributeError: 

raise bin_op_exception('//', self, other) 

else: 

return python_op(other) 

  

def __mod__(left, right): 

""" 

Top-level modulo operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: 7 % 3 

1 

sage: 7 % int(3) 

1 

sage: int(7) % 3 

1 

  

:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _mod_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e % e 

42 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e % e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for %: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 % e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for %: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e % 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for %: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) % e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for %: 'int' and 'sage.structure.element.Element' 

sage: e % int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for %: 'sage.structure.element.Element' and 'int' 

sage: None % e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for %: 'NoneType' and 'sage.structure.element.Element' 

sage: e % None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for %: 'sage.structure.element.Element' and 'NoneType' 

""" 

# See __add__ for comments 

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._mod_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, mod) 

  

try: 

return coercion_model.bin_op(left, right, mod) 

except TypeError: 

return NotImplemented 

  

cdef _mod_(self, other): 

""" 

Virtual modulo method for elements with identical parents. 

  

This default Cython implementation of ``_mod_`` calls the 

Python method ``self._mod_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._mod_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_mod_' 

""" 

try: 

python_op = (<object>self)._mod_ 

except AttributeError: 

raise bin_op_exception('%', self, other) 

else: 

return python_op(other) 

  

def __pow__(left, right, modulus): 

""" 

Top-level power operator for :class:`Element` invoking 

the coercion model. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import Element 

sage: class MyElement(Element): 

....: def _add_(self, other): 

....: return 42 

sage: e = MyElement(Parent()) 

sage: e + e 

42 

sage: a = Integers(389)['x']['y'](37) 

sage: p = sage.structure.element.RingElement.__pow__ 

sage: p(a, 2) 

202 

sage: p(a, 2, 1) 

Traceback (most recent call last): 

... 

TypeError: the 3-argument version of pow() is not supported 

  

TESTS:: 

  

sage: e = Element(Parent()) 

sage: e ^ e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for ^: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>' 

sage: 1 ^ e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for ^: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>' 

sage: e ^ 1 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for ^: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring' 

sage: int(1) ^ e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'sage.structure.element.Element' 

sage: e ^ int(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for ** or pow(): 'sage.structure.element.Element' and 'int' 

sage: None ^ e 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'sage.structure.element.Element' 

sage: e ^ None 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for ** or pow(): 'sage.structure.element.Element' and 'NoneType' 

""" 

# The coercion model does not support a modulus 

if modulus is not None: 

raise TypeError("the 3-argument version of pow() is not supported") 

  

cdef int cl = classify_elements(left, right) 

if HAVE_SAME_PARENT(cl): 

return (<Element>left)._pow_(right) 

if BOTH_ARE_ELEMENT(cl): 

return coercion_model.bin_op(left, right, pow) 

  

cdef long value 

cdef int err = -1 

try: 

# Special case powering with Python integers 

integer_check_long_py(right, &value, &err) 

if not err: 

return (<Element>left)._pow_long(value) 

return coercion_model.bin_op(left, right, pow) 

except TypeError: 

return NotImplemented 

  

cdef _pow_(self, other): 

""" 

Virtual powering method for elements with identical parents. 

  

This default Cython implementation of ``_pow_`` calls the 

Python method ``self._pow_`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._pow_(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_pow_' 

""" 

try: 

python_op = (<object>self)._pow_ 

except AttributeError: 

raise bin_op_exception('^', self, other) 

else: 

return python_op(other) 

  

cdef _pow_int(self, other): 

""" 

Virtual powering method for powering to an integer exponent. 

  

This default Cython implementation of ``_pow_int`` calls the 

Python method ``self._pow_int`` if it exists. This method may be 

defined in the ``ElementMethods`` of the category of the parent. 

If the method is not found, a ``TypeError`` is raised 

indicating that the operation is not supported. 

  

See :ref:`element_arithmetic`. 

  

EXAMPLES: 

  

This method is not visible from Python:: 

  

sage: from sage.structure.element import Element 

sage: e = Element(Parent()) 

sage: e._pow_int(e) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.structure.element.Element' object has no attribute '_pow_int' 

""" 

try: 

python_op = (<object>self)._pow_int 

except AttributeError: 

raise bin_op_exception('^', self, other) 

else: 

return python_op(other) 

  

cdef _pow_long(self, long n): 

""" 

Generic path for powering with a C long. 

""" 

return self._pow_int(n) 

  

  

def is_ModuleElement(x): 

""" 

Return ``True`` if x is of type ModuleElement. 

  

This is even faster than using isinstance inline. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import is_ModuleElement 

sage: is_ModuleElement(2/3) 

True 

sage: is_ModuleElement((QQ^3).0) 

True 

sage: is_ModuleElement('a') 

False 

""" 

return isinstance(x, ModuleElement) 

  

cdef class ElementWithCachedMethod(Element): 

r""" 

An element class that fully supports cached methods. 

  

NOTE: 

  

The :class:`~sage.misc.cachefunc.cached_method` decorator provides 

a convenient way to automatically cache the result of a computation. 

Since :trac:`11115`, the cached method decorator applied to a 

method without optional arguments is faster than a hand-written cache 

in Python, and a cached method without any arguments (except ``self``) 

is actually faster than a Python method that does nothing more but 

to return ``1``. A cached method can also be inherited from the parent 

or element class of a category. 

  

However, this holds true only if attribute assignment is supported. 

If you write an extension class in Cython that does not accept attribute 

assignment then a cached method inherited from the category will be 

slower (for :class:`~sage.structure.parent.Parent`) or the cache would 

even break (for :class:`Element`). 

  

This class should be used if you write an element class, can not provide 

it with attribute assignment, but want that it inherits a cached method 

from the category. Under these conditions, your class should inherit 

from this class rather than :class:`Element`. Then, the cache will work, 

but certainly slower than with attribute assignment. Lazy attributes 

work as well. 

  

EXAMPLES: 

  

We define three element extension classes. The first inherits from 

:class:`Element`, the second from this class, and the third simply 

is a Python class. We also define a parent class and, in Python, a 

category whose element and parent classes define cached methods. 

:: 

  

sage: cython_code = ["from sage.structure.element cimport Element, ElementWithCachedMethod", 

....: "cdef class MyBrokenElement(Element):", 

....: " cdef public object x", 

....: " def __init__(self,P,x):", 

....: " self.x=x", 

....: " Element.__init__(self,P)", 

....: " def __neg__(self):", 

....: " return MyBrokenElement(self.parent(),-self.x)", 

....: " def _repr_(self):", 

....: " return '<%s>'%self.x", 

....: " def __hash__(self):", 

....: " return hash(self.x)", 

....: " cpdef int _cmp_(left, right) except -2:", 

....: " return cmp(left.x,right.x)", 

....: " def raw_test(self):", 

....: " return -self", 

....: "cdef class MyElement(ElementWithCachedMethod):", 

....: " cdef public object x", 

....: " def __init__(self,P,x):", 

....: " self.x=x", 

....: " Element.__init__(self,P)", 

....: " def __neg__(self):", 

....: " return MyElement(self.parent(),-self.x)", 

....: " def _repr_(self):", 

....: " return '<%s>'%self.x", 

....: " def __hash__(self):", 

....: " return hash(self.x)", 

....: " cpdef int _cmp_(left, right) except -2:", 

....: " return cmp(left.x,right.x)", 

....: " def raw_test(self):", 

....: " return -self", 

....: "class MyPythonElement(MyBrokenElement): pass", 

....: "from sage.structure.parent cimport Parent", 

....: "cdef class MyParent(Parent):", 

....: " Element = MyElement"] 

sage: cython('\n'.join(cython_code)) 

sage: cython_code = ["from sage.all import cached_method, cached_in_parent_method, Category, Objects", 

....: "class MyCategory(Category):", 

....: " @cached_method", 

....: " def super_categories(self):", 

....: " return [Objects()]", 

....: " class ElementMethods:", 

....: " @cached_method", 

....: " def element_cache_test(self):", 

....: " return -self", 

....: " @cached_in_parent_method", 

....: " def element_via_parent_test(self):", 

....: " return -self", 

....: " class ParentMethods:", 

....: " @cached_method", 

....: " def one(self):", 

....: " return self.element_class(self,1)", 

....: " @cached_method", 

....: " def invert(self, x):", 

....: " return -x"] 

sage: cython('\n'.join(cython_code)) 

sage: C = MyCategory() 

sage: P = MyParent(category=C) 

sage: ebroken = MyBrokenElement(P,5) 

sage: e = MyElement(P,5) 

  

The cached methods inherited by ``MyElement`` works:: 

  

sage: e.element_cache_test() 

<-5> 

sage: e.element_cache_test() is e.element_cache_test() 

True 

sage: e.element_via_parent_test() 

<-5> 

sage: e.element_via_parent_test() is e.element_via_parent_test() 

True 

  

The other element class can only inherit a 

``cached_in_parent_method``, since the cache is stored in the 

parent. In fact, equal elements share the cache, even if they are 

of different types:: 

  

sage: e == ebroken 

True 

sage: type(e) == type(ebroken) 

False 

sage: ebroken.element_via_parent_test() is e.element_via_parent_test() 

True 

  

However, the cache of the other inherited method breaks, although the method 

as such works:: 

  

sage: ebroken.element_cache_test() 

<-5> 

sage: ebroken.element_cache_test() is ebroken.element_cache_test() 

False 

  

Since ``e`` and ``ebroken`` share the cache, when we empty it for one element 

it is empty for the other as well:: 

  

sage: b = ebroken.element_via_parent_test() 

sage: e.element_via_parent_test.clear_cache() 

sage: b is ebroken.element_via_parent_test() 

False 

  

Note that the cache only breaks for elements that do no allow attribute assignment. 

A Python version of ``MyBrokenElement`` therefore allows for cached methods:: 

  

sage: epython = MyPythonElement(P,5) 

sage: epython.element_cache_test() 

<-5> 

sage: epython.element_cache_test() is epython.element_cache_test() 

True 

  

""" 

cdef getattr_from_category(self, name): 

""" 

This getattr method ensures that cached methods and lazy attributes 

can be inherited from the element class of a category. 

  

.. NOTE:: 

  

The use of cached methods is demonstrated in the main doc 

string of this class. Here, we demonstrate lazy 

attributes. 

  

EXAMPLES:: 

  

sage: cython(''' 

....: from sage.structure.element cimport ElementWithCachedMethod 

....: cdef class MyElement(ElementWithCachedMethod): 

....: cdef public object x 

....: def __init__(self, P, x): 

....: self.x = x 

....: ElementWithCachedMethod.__init__(self,P) 

....: def _repr_(self): 

....: return '<%s>'%self.x 

....: from sage.structure.parent cimport Parent 

....: cdef class MyParent(Parent): 

....: Element = MyElement 

....: from sage.all import cached_method, lazy_attribute, Category, Objects 

....: class MyCategory(Category): 

....: @cached_method 

....: def super_categories(self): 

....: return [Objects()] 

....: class ElementMethods: 

....: @lazy_attribute 

....: def my_lazy_attr(self): 

....: return 'lazy attribute of <%s>'%self.x 

....: ''') 

sage: C = MyCategory() 

sage: P = MyParent(category=C) 

sage: e = MyElement(P,5) 

sage: e.my_lazy_attr 

'lazy attribute of <5>' 

sage: e.my_lazy_attr is e.my_lazy_attr 

True 

""" 

try: 

return self.__cached_methods[name] 

except KeyError: 

attr = getattr_from_other_class(self, 

self._parent.category().element_class, 

name) 

self.__cached_methods[name] = attr 

return attr 

except TypeError: 

attr = getattr_from_other_class(self, 

self._parent.category().element_class, 

name) 

self.__cached_methods = {name : attr} 

return attr 

  

  

cdef class ModuleElement(Element): 

""" 

Generic element of a module. 

""" 

cpdef _add_(self, other): 

""" 

Abstract addition method 

  

TESTS:: 

  

sage: from sage.structure.element import ModuleElement 

sage: e = ModuleElement(Parent()) 

sage: e + e 

Traceback (most recent call last): 

... 

NotImplementedError: addition not implemented for <sage.structure.parent.Parent object at ...> 

""" 

raise NotImplementedError(f"addition not implemented for {self._parent}") 

  

cdef _add_long(self, long n): 

""" 

Generic path for adding a C long, assumed to commute. 

""" 

if n == 0: 

return self 

return coercion_model.bin_op(self, n, add) 

  

cpdef _sub_(self, other): 

""" 

Default implementation of subtraction using addition and 

negation. 

""" 

return self + (-other) 

  

cpdef _neg_(self): 

""" 

Default implementation of negation using multiplication 

with -1. 

""" 

return self._mul_long(-1) 

  

cdef _mul_long(self, long n): 

""" 

Generic path for multiplying by a C long, assumed to commute. 

""" 

if n == 1: 

return self 

return coercion_model.bin_op(self, n, mul) 

  

# rmul -- left * self 

cpdef _rmul_(self, Element left): 

""" 

Reversed scalar multiplication for module elements with the 

module element on the right and the scalar on the left. 

  

By default, we assume commutativity and reverse the arguments. 

""" 

return self._lmul_(left) 

  

# lmul -- self * right 

cpdef _lmul_(self, Element right): 

""" 

Scalar multiplication for module elements with the module 

element on the left and the scalar on the right. 

  

Returning None indicates that this action is not implemented here. 

""" 

return None 

  

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

# Other properties 

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

def order(self): ### DO NOT OVERRIDE THIS!!! Instead, override additive_order. 

""" 

Return the additive order of self. 

""" 

return self.additive_order() 

  

def additive_order(self): 

""" 

Return the additive order of self. 

""" 

raise NotImplementedError 

  

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

# Monoid 

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

  

def is_MonoidElement(x): 

""" 

Return ``True`` if x is of type MonoidElement. 

""" 

return isinstance(x, MonoidElement) 

  

cdef class MonoidElement(Element): 

""" 

Generic element of a monoid. 

""" 

  

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

# Other generic functions that should be available to 

# any monoid element. 

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

def order(self): 

""" 

Return the multiplicative order of self. 

""" 

return self.multiplicative_order() 

  

def multiplicative_order(self): 

""" 

Return the multiplicative order of self. 

""" 

raise NotImplementedError 

  

cpdef _pow_int(self, n): 

""" 

Return the (integral) power of self. 

""" 

return arith_generic_power(self, n) 

  

def powers(self, n): 

r""" 

Return the list `[x^0, x^1, \ldots, x^{n-1}]`. 

  

EXAMPLES:: 

  

sage: G = SymmetricGroup(4) 

sage: g = G([2, 3, 4, 1]) 

sage: g.powers(4) 

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

""" 

if n < 0: 

raise ValueError("negative number of powers requested") 

elif n == 0: 

return [] 

x = self._parent.one() 

l = [x] 

for i in xrange(n - 1): 

x = x * self 

l.append(x) 

return l 

  

def __nonzero__(self): 

return True 

  

  

def is_AdditiveGroupElement(x): 

""" 

Return ``True`` if x is of type AdditiveGroupElement. 

""" 

return isinstance(x, AdditiveGroupElement) 

  

cdef class AdditiveGroupElement(ModuleElement): 

""" 

Generic element of an additive group. 

""" 

def order(self): 

""" 

Return additive order of element 

""" 

return self.additive_order() 

  

def __invert__(self): 

raise NotImplementedError("multiplicative inverse not defined for additive group elements") 

  

  

def is_MultiplicativeGroupElement(x): 

""" 

Return ``True`` if x is of type MultiplicativeGroupElement. 

""" 

return isinstance(x, MultiplicativeGroupElement) 

  

cdef class MultiplicativeGroupElement(MonoidElement): 

""" 

Generic element of a multiplicative group. 

""" 

def order(self): 

""" 

Return the multiplicative order of self. 

""" 

return self.multiplicative_order() 

  

cpdef _div_(self, right): 

""" 

Default implementation of division using multiplication by 

the inverse. 

""" 

return self * ~right 

  

def __invert__(self): 

r""" 

Return the inverse of ``self``. 

""" 

return self._parent.one() / self 

  

  

def is_RingElement(x): 

""" 

Return ``True`` if x is of type RingElement. 

""" 

return isinstance(x, RingElement) 

  

cdef class RingElement(ModuleElement): 

cpdef _mul_(self, other): 

""" 

Abstract multiplication method 

  

TESTS:: 

  

sage: from sage.structure.element import RingElement 

sage: e = RingElement(Parent()) 

sage: e * e 

Traceback (most recent call last): 

... 

NotImplementedError: multiplication not implemented for <sage.structure.parent.Parent object at ...> 

""" 

raise NotImplementedError(f"multiplication not implemented for {self._parent}") 

  

def is_one(self): 

return self == self._parent.one() 

  

cpdef _pow_int(self, n): 

""" 

Return the (integral) power of self. 

  

EXAMPLES:: 

  

sage: a = Integers(389)['x']['y'](37) 

sage: p = sage.structure.element.RingElement.__pow__ 

sage: p(a,2) 

202 

sage: p(a,2,1) 

Traceback (most recent call last): 

... 

TypeError: the 3-argument version of pow() is not supported 

sage: p(a,388) 

1 

sage: p(a,2^120) 

81 

sage: p(a,0) 

1 

sage: p(a,1) == a 

True 

sage: p(a,2) * p(a,3) == p(a,5) 

True 

sage: p(a,3)^2 == p(a,6) 

True 

sage: p(a,57) * p(a,43) == p(a,100) 

True 

sage: p(a,-1) == 1/a 

True 

sage: p(a,200) * p(a,-64) == p(a,136) 

True 

sage: p(2, 1/2) 

sqrt(2) 

  

TESTS:: 

  

These aren't testing this code, but they are probably good to have around:: 

  

sage: 2r**(SR(2)-1-1r) 

1 

sage: 2r^(1/2) 

sqrt(2) 

  

Exponent overflow should throw an OverflowError (:trac:`2956`):: 

  

sage: K.<x,y> = AA[] 

sage: x^(2^64 + 12345) 

Traceback (most recent call last): 

... 

OverflowError: exponent overflow (2147483648) 

  

Another example from :trac:`2956` which always overflows 

with Singular 4:: 

  

sage: K.<x,y> = ZZ[] 

sage: (x^12345)^54321 

Traceback (most recent call last): 

... 

OverflowError: exponent overflow (670592745) 

""" 

return arith_generic_power(self, n) 

  

def powers(self, n): 

r""" 

Return the list `[x^0, x^1, \ldots, x^{n-1}]`. 

  

EXAMPLES:: 

  

sage: 5.powers(3) 

[1, 5, 25] 

""" 

if n < 0: 

raise ValueError("negative number of powers requested") 

elif n == 0: 

return [] 

x = self._parent.one() 

l = [x] 

for i in xrange(n - 1): 

x = x * self 

l.append(x) 

return l 

  

cpdef _div_(self, other): 

""" 

Default implementation of division using the fraction field. 

""" 

try: 

frac = self._parent.fraction_field() 

except AttributeError: 

raise bin_op_exception('/', self, other) 

return frac(self, other) 

  

def __invert__(self): 

return self._parent.one() / self 

  

def additive_order(self): 

""" 

Return the additive order of ``self``. 

""" 

raise NotImplementedError 

  

def multiplicative_order(self): 

r""" 

Return the multiplicative order of ``self``, if ``self`` is a unit, 

or raise ``ArithmeticError`` otherwise. 

""" 

if not self.is_unit(): 

raise ArithmeticError("self (=%s) must be a unit to have a multiplicative order.") 

raise NotImplementedError 

  

def is_nilpotent(self): 

""" 

Return ``True`` if ``self`` is nilpotent, i.e., some power of ``self`` 

is 0. 

  

TESTS:: 

  

sage: a = QQ(2) 

sage: a.is_nilpotent() 

False 

sage: a = QQ(0) 

sage: a.is_nilpotent() 

True 

sage: m = matrix(QQ,3,[[3,2,3],[9,0,3],[-9,0,-3]]) 

sage: m.is_nilpotent() 

Traceback (most recent call last): 

... 

AttributeError: ... object has no attribute 'is_nilpotent' 

""" 

if self.is_unit(): 

return False 

if self.is_zero(): 

return True 

raise NotImplementedError 

  

def abs(self): 

""" 

Return the absolute value of ``self``. (This just calls the ``__abs__`` 

method, so it is equivalent to the ``abs()`` built-in function.) 

  

EXAMPLES:: 

  

sage: RR(-1).abs() 

1.00000000000000 

sage: ZZ(-1).abs() 

1 

sage: CC(I).abs() 

1.00000000000000 

sage: Mod(-15, 37).abs() 

Traceback (most recent call last): 

... 

ArithmeticError: absolute valued not defined on integers modulo n. 

""" 

return abs(self) 

  

def is_prime(self): 

""" 

Is ``self`` a prime element? 

  

A *prime* element is a non-zero, non-unit element `p` such that, 

whenever `p` divides `ab` for some `a` and `b`, then `p` 

divides `a` or `p` divides `b`. 

  

EXAMPLES: 

  

For polynomial rings, prime is the same as irreducible:: 

  

sage: R.<x,y> = QQ[] 

sage: x.is_prime() 

True 

sage: (x^2 + y^3).is_prime() 

True 

sage: (x^2 - y^2).is_prime() 

False 

sage: R(0).is_prime() 

False 

sage: R(2).is_prime() 

False 

  

For the Gaussian integers:: 

  

sage: K.<i> = QuadraticField(-1) 

sage: ZI = K.ring_of_integers() 

sage: ZI(3).is_prime() 

True 

sage: ZI(5).is_prime() 

False 

sage: ZI(2+i).is_prime() 

True 

sage: ZI(0).is_prime() 

False 

sage: ZI(1).is_prime() 

False 

  

In fields, an element is never prime:: 

  

sage: RR(0).is_prime() 

False 

sage: RR(2).is_prime() 

False 

  

For integers, prime numbers are redefined to be positive:: 

  

sage: RingElement.is_prime(-2) 

True 

sage: Integer.is_prime(-2) 

False 

""" 

if not self: # We exclude the 0 element 

return False 

return self._parent.ideal(self).is_prime() 

  

  

def is_CommutativeRingElement(x): 

""" 

Return ``True`` if x is of type CommutativeRingElement. 

  

TESTS:: 

  

sage: from sage.structure.element import is_CommutativeRingElement 

sage: is_CommutativeRingElement(oo) 

False 

  

sage: is_CommutativeRingElement(1) 

True 

""" 

return isinstance(x, CommutativeRingElement) 

  

cdef class CommutativeRingElement(RingElement): 

""" 

Base class for elements of commutative rings. 

""" 

def inverse_mod(self, I): 

r""" 

Return an inverse of ``self`` modulo the ideal `I`, if defined, 

i.e., if `I` and ``self`` together generate the unit ideal. 

""" 

raise NotImplementedError 

  

def divides(self, x): 

""" 

Return ``True`` if ``self`` divides x. 

  

EXAMPLES:: 

  

sage: P.<x> = PolynomialRing(QQ) 

sage: x.divides(x^2) 

True 

sage: x.divides(x^2+2) 

False 

sage: (x^2+2).divides(x) 

False 

sage: P.<x> = PolynomialRing(ZZ) 

sage: x.divides(x^2) 

True 

sage: x.divides(x^2+2) 

False 

sage: (x^2+2).divides(x) 

False 

  

:trac:`5347` has been fixed:: 

  

sage: K = GF(7) 

sage: K(3).divides(1) 

True 

sage: K(3).divides(K(1)) 

True 

  

:: 

  

sage: R = Integers(128) 

sage: R(0).divides(1) 

False 

sage: R(0).divides(0) 

True 

sage: R(0).divides(R(0)) 

True 

sage: R(1).divides(0) 

True 

sage: R(121).divides(R(120)) 

True 

sage: R(120).divides(R(121)) 

Traceback (most recent call last): 

... 

ArithmeticError: reduction modulo 120 not defined 

  

If ``x`` has different parent than ``self``, they are first coerced to a 

common parent if possible. If this coercion fails, it returns a 

TypeError. This fixes :trac:`5759`. :: 

  

sage: Zmod(2)(0).divides(Zmod(2)(0)) 

True 

sage: Zmod(2)(0).divides(Zmod(2)(1)) 

False 

sage: Zmod(5)(1).divides(Zmod(2)(1)) 

Traceback (most recent call last): 

... 

TypeError: no common canonical parent for objects with parents: 'Ring of integers modulo 5' and 'Ring of integers modulo 2' 

sage: Zmod(35)(4).divides(Zmod(7)(1)) 

True 

sage: Zmod(35)(7).divides(Zmod(7)(1)) 

False 

""" 

if have_same_parent(self, x): 

# First we test some generic conditions: 

try: 

if x.is_zero(): 

return True # everything divides 0 

except (AttributeError, NotImplementedError): 

pass 

  

try: 

if self.is_zero(): 

return False # 0 divides nothing else 

except (AttributeError, NotImplementedError): 

pass 

  

try: 

if self.is_unit(): 

return True # units divide everything 

except (AttributeError, NotImplementedError): 

pass 

  

try: 

if self.is_one(): 

return True # 1 divides everything 

# (is_unit() may not be implemented) 

except (AttributeError, NotImplementedError): 

pass 

  

return (x % self) == 0 

  

else: 

#Different parents, use coercion 

a, b = coercion_model.canonical_coercion(self, x) 

return a.divides(b) 

  

def mod(self, I): 

r""" 

Return a representative for ``self`` modulo the ideal I (or the ideal 

generated by the elements of I if I is not an ideal.) 

  

EXAMPLES: Integers 

Reduction of 5 modulo an ideal:: 

  

sage: n = 5 

sage: n.mod(3*ZZ) 

2 

  

Reduction of 5 modulo the ideal generated by 3:: 

  

sage: n.mod(3) 

2 

  

Reduction of 5 modulo the ideal generated by 15 and 6, which is `(3)`. 

  

:: 

  

sage: n.mod([15,6]) 

2 

  

  

EXAMPLES: Univariate polynomials 

  

:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: f = x^3 + x + 1 

sage: f.mod(x + 1) 

-1 

  

Reduction for `\ZZ[x]`:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: f = x^3 + x + 1 

sage: f.mod(x + 1) 

-1 

  

When little is implemented about a given ring, then mod may 

return simply return `f`. 

  

EXAMPLES: Multivariate polynomials 

We reduce a polynomial in two variables modulo a polynomial 

and an ideal:: 

  

sage: R.<x,y,z> = PolynomialRing(QQ, 3) 

sage: (x^2 + y^2 + z^2).mod(x+y+z) 

2*y^2 + 2*y*z + 2*z^2 

  

Notice above that `x` is eliminated. In the next example, 

both `y` and `z` are eliminated:: 

  

sage: (x^2 + y^2 + z^2).mod( (x - y, y - z) ) 

3*z^2 

sage: f = (x^2 + y^2 + z^2)^2; f 

x^4 + 2*x^2*y^2 + y^4 + 2*x^2*z^2 + 2*y^2*z^2 + z^4 

sage: f.mod( (x - y, y - z) ) 

9*z^4 

  

In this example `y` is eliminated:: 

  

sage: (x^2 + y^2 + z^2).mod( (x^3, y - z) ) 

x^2 + 2*z^2 

""" 

from sage.rings.ideal import is_Ideal 

if not is_Ideal(I) or not I.ring() is self._parent: 

I = self._parent.ideal(I) 

#raise TypeError, "I = %s must be an ideal in %s"%(I, self.parent()) 

return I.reduce(self) 

  

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

# square roots 

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

  

def is_square(self, root=False): 

""" 

Return whether or not the ring element ``self`` is a square. 

  

If the optional argument root is ``True``, then also return 

the square root (or ``None``, if it is not a square). 

  

INPUT: 

  

- ``root`` - whether or not to also return a square 

root (default: ``False``) 

  

OUTPUT: 

  

- ``bool`` -- whether or not a square 

  

- ``object`` -- (optional) an actual square root if 

found, and ``None`` otherwise. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: f = 12*(x+1)^2 * (x+3)^2 

sage: f.is_square() 

False 

sage: f.is_square(root=True) 

(False, None) 

sage: h = f/3 

sage: h.is_square() 

True 

sage: h.is_square(root=True) 

(True, 2*x^2 + 8*x + 6) 

  

.. NOTE:: 

  

This is the is_square implementation for general 

commutative ring elements. It's implementation is to raise 

a NotImplementedError. The function definition is here to 

show what functionality is expected and provide a general 

framework. 

""" 

raise NotImplementedError("is_square() not implemented for elements of %s" % self.parent()) 

  

def sqrt(self, extend=True, all=False, name=None): 

""" 

It computes the square root. 

  

INPUT: 

  

- ``extend`` - Whether to make a ring extension containing a square root if ``self`` is not a square (default: ``True``) 

  

- ``all`` - Whether to return a list of all square roots or just a square root (default: False) 

  

- ``name`` - Required when ``extend=True`` and ``self`` is not a square. This will be the name of the generator extension. 

  

OUTPUT: 

  

- if ``all=False`` it returns a square root. (throws an error if ``extend=False`` and ``self`` is not a square) 

  

- if ``all=True`` it returns a list of all the square roots (could be empty if ``extend=False`` and ``self`` is not a square) 

  

ALGORITHM: 

  

It uses ``is_square(root=true)`` for the hard part of the work, the rest is just wrapper code. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: (x^2).sqrt() 

x 

sage: f=x^2-4*x+4; f.sqrt(all=True) 

[x - 2, -x + 2] 

sage: sqrtx=x.sqrt(name="y"); sqrtx 

y 

sage: sqrtx^2 

x 

sage: x.sqrt(all=true,name="y") 

[y, -y] 

sage: x.sqrt(extend=False,all=True) 

[] 

sage: x.sqrt() 

Traceback (most recent call last): 

... 

TypeError: Polynomial is not a square. You must specify the name of the square root when using the default extend = True 

sage: x.sqrt(extend=False) 

Traceback (most recent call last): 

... 

ValueError: trying to take square root of non-square x with extend = False 

  

TESTS:: 

  

sage: f = (x+3)^2; f.sqrt() 

x + 3 

sage: f = (x+3)^2; f.sqrt(all=True) 

[x + 3, -x - 3] 

sage: f = (x^2 - x + 3)^2; f.sqrt() 

x^2 - x + 3 

sage: f = (x^2 - x + 3)^6; f.sqrt() 

x^6 - 3*x^5 + 12*x^4 - 19*x^3 + 36*x^2 - 27*x + 27 

sage: g = (R.random_element(15))^2 

sage: g.sqrt()^2 == g 

True 

  

sage: R.<x> = GF(250037)[] 

sage: f = x^2/(x+1)^2; f.sqrt() 

x/(x + 1) 

sage: f = 9 * x^4 / (x+1)^2; f.sqrt() 

3*x^2/(x + 1) 

sage: f = 9 * x^4 / (x+1)^2; f.sqrt(all=True) 

[3*x^2/(x + 1), 250034*x^2/(x + 1)] 

  

sage: R.<x> = QQ[] 

sage: a = 2*(x+1)^2 / (2*(x-1)^2); a.sqrt() 

(2*x + 2)/(2*x - 2) 

sage: sqrtx=(1/x).sqrt(name="y"); sqrtx 

y 

sage: sqrtx^2 

1/x 

sage: (1/x).sqrt(all=true,name="y") 

[y, -y] 

sage: (1/x).sqrt(extend=False,all=True) 

[] 

sage: (1/(x^2-1)).sqrt() 

Traceback (most recent call last): 

... 

TypeError: Polynomial is not a square. You must specify the name of the square root when using the default extend = True 

sage: (1/(x^2-3)).sqrt(extend=False) 

Traceback (most recent call last): 

... 

ValueError: trying to take square root of non-square 1/(x^2 - 3) with extend = False 

""" 

#This code is very general, it works for all integral domains that have the 

#is_square(root = True) option 

  

from sage.rings.ring import IntegralDomain 

P = self._parent 

is_sqr, sq_rt = self.is_square(root=True) 

if is_sqr: 

if all: 

if not isinstance(P, IntegralDomain): 

raise NotImplementedError('sqrt() with all=True is only implemented for integral domains, not for %s' % P) 

if P.characteristic()==2 or sq_rt==0: 

#0 has only one square root, and in characteristic 2 everything also has only 1 root 

return [ sq_rt ] 

return [ sq_rt, -sq_rt ] 

return sq_rt 

#from now on we know that self is not a square 

if not isinstance(P, IntegralDomain): 

raise NotImplementedError('sqrt() of non squares is only implemented for integral domains, not for %s' % P) 

if not extend: 

#all square roots of a non-square should be an empty list 

if all: 

return [] 

raise ValueError('trying to take square root of non-square %s with extend = False' % self) 

  

if name is None: 

raise TypeError("Polynomial is not a square. You must specify the name of the square root when using the default extend = True") 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

PY = PolynomialRing(P, 'y') 

y = PY.gen() 

sq_rt = PY.quotient(y**2-self, names = name)(y) 

if all: 

if P.characteristic() == 2: 

return [ sq_rt ] 

return [ sq_rt, -sq_rt ] 

return sq_rt 

  

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

  

cdef class Vector(ModuleElement): 

cdef bint is_sparse_c(self): 

raise NotImplementedError 

  

cdef bint is_dense_c(self): 

raise NotImplementedError 

  

def __mul__(left, right): 

""" 

Multiplication of vector by vector, matrix, or scalar 

  

AUTHOR: 

  

- Gonzalo Tornaria (2007-06-21) - write test cases and fix them 

  

.. NOTE:: 

  

scalar * vector is implemented (and tested) in class RingElement 

matrix * vector is implemented (and tested) in class Matrix 

  

TESTS: 

  

Here we test (vector * vector) multiplication:: 

  

sage: parent(vector(ZZ,[1,2])*vector(ZZ,[1,2])) 

Integer Ring 

sage: parent(vector(ZZ,[1,2])*vector(QQ,[1,2])) 

Rational Field 

sage: parent(vector(QQ,[1,2])*vector(ZZ,[1,2])) 

Rational Field 

sage: parent(vector(QQ,[1,2])*vector(QQ,[1,2])) 

Rational Field 

  

sage: parent(vector(QQ,[1,2,3,4])*vector(ZZ['x'],[1,2,3,4])) 

Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x'],[1,2,3,4])*vector(QQ,[1,2,3,4])) 

Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ,[1,2,3,4])*vector(ZZ['x']['y'],[1,2,3,4])) 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2,3,4])*vector(QQ,[1,2,3,4])) 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ['x'],[1,2,3,4])*vector(ZZ['x']['y'],[1,2,3,4])) 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2,3,4])*vector(QQ['x'],[1,2,3,4])) 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ['y'],[1,2,3,4])*vector(ZZ['x']['y'],[1,2,3,4])) 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2,3,4])*vector(QQ['y'],[1,2,3,4])) 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(ZZ['x'],[1,2,3,4])*vector(ZZ['y'],[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(vector(ZZ['x'],[1,2,3,4])*vector(QQ['y'],[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field' 

sage: parent(vector(QQ['x'],[1,2,3,4])*vector(ZZ['y'],[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(vector(QQ['x'],[1,2,3,4])*vector(QQ['y'],[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field' 

  

Here we test (vector * matrix) multiplication:: 

  

sage: parent(vector(ZZ,[1,2])*matrix(ZZ,2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the principal ideal domain Integer Ring 

sage: parent(vector(QQ,[1,2])*matrix(ZZ,2,2,[1,2,3,4])) 

Vector space of dimension 2 over Rational Field 

sage: parent(vector(ZZ,[1,2])*matrix(QQ,2,2,[1,2,3,4])) 

Vector space of dimension 2 over Rational Field 

sage: parent(vector(QQ,[1,2])*matrix(QQ,2,2,[1,2,3,4])) 

Vector space of dimension 2 over Rational Field 

  

sage: parent(vector(QQ,[1,2])*matrix(ZZ['x'],2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x'],[1,2])*matrix(QQ,2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ,[1,2])*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2])*matrix(QQ,2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ['x'],[1,2])*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2])*matrix(QQ['x'],2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ['y'],[1,2])*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2])*matrix(QQ['y'],2,2,[1,2,3,4])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(ZZ['x'],[1,2])*matrix(ZZ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(vector(ZZ['x'],[1,2])*matrix(QQ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field' 

sage: parent(vector(QQ['x'],[1,2])*matrix(ZZ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(vector(QQ['x'],[1,2])*matrix(QQ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field' 

  

Here we test (vector * scalar) multiplication:: 

  

sage: parent(vector(ZZ,[1,2])*ZZ(1)) 

Ambient free module of rank 2 over the principal ideal domain Integer Ring 

sage: parent(vector(QQ,[1,2])*ZZ(1)) 

Vector space of dimension 2 over Rational Field 

sage: parent(vector(ZZ,[1,2])*QQ(1)) 

Vector space of dimension 2 over Rational Field 

sage: parent(vector(QQ,[1,2])*QQ(1)) 

Vector space of dimension 2 over Rational Field 

  

sage: parent(vector(QQ,[1,2])*ZZ['x'](1)) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x'],[1,2])*QQ(1)) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ,[1,2])*ZZ['x']['y'](1)) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2])*QQ(1)) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ['x'],[1,2])*ZZ['x']['y'](1)) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2])*QQ['x'](1)) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(QQ['y'],[1,2])*ZZ['x']['y'](1)) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(vector(ZZ['x']['y'],[1,2])*QQ['y'](1)) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(vector(ZZ['x'],[1,2])*ZZ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(vector(ZZ['x'],[1,2])*QQ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Rational Field' 

sage: parent(vector(QQ['x'],[1,2])*ZZ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(vector(QQ['x'],[1,2])*QQ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Rational Field' 

  

Here we test (scalar * vector) multiplication:: 

  

sage: parent(ZZ(1)*vector(ZZ,[1,2])) 

Ambient free module of rank 2 over the principal ideal domain Integer Ring 

sage: parent(QQ(1)*vector(ZZ,[1,2])) 

Vector space of dimension 2 over Rational Field 

sage: parent(ZZ(1)*vector(QQ,[1,2])) 

Vector space of dimension 2 over Rational Field 

sage: parent(QQ(1)*vector(QQ,[1,2])) 

Vector space of dimension 2 over Rational Field 

  

sage: parent(QQ(1)*vector(ZZ['x'],[1,2])) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x'](1)*vector(QQ,[1,2])) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(QQ(1)*vector(ZZ['x']['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x']['y'](1)*vector(QQ,[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(QQ['x'](1)*vector(ZZ['x']['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x']['y'](1)*vector(QQ['x'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(QQ['y'](1)*vector(ZZ['x']['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x']['y'](1)*vector(QQ['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(ZZ['x'](1)*vector(ZZ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(ZZ['x'](1)*vector(QQ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field' 

sage: parent(QQ['x'](1)*vector(ZZ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(QQ['x'](1)*vector(QQ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field' 

""" 

if have_same_parent(left, right): 

return (<Vector>left)._dot_product_(<Vector>right) 

return coercion_model.bin_op(left, right, mul) 

  

cpdef _dot_product_(Vector left, Vector right): 

return left._dot_product_coerce_(right) 

  

cpdef _dot_product_coerce_(Vector left, Vector right): 

raise bin_op_exception('*', left, right) 

  

cpdef _pairwise_product_(Vector left, Vector right): 

raise TypeError("unsupported operation for '%s' and '%s'"%(parent(left), parent(right))) 

  

def __div__(self, other): 

return self / other 

  

def __truediv__(self, right): 

right = py_scalar_to_element(right) 

if isinstance(right, RingElement): 

# Let __mul__ do the job 

return self * ~right 

if isinstance(right, Vector): 

try: 

W = (<Vector>right)._parent.submodule([right]) 

return W.coordinates(self)[0] / W.coordinates(right)[0] 

except ArithmeticError: 

if right.is_zero(): 

raise ZeroDivisionError("division by zero vector") 

else: 

raise ArithmeticError("vector is not in free module") 

raise bin_op_exception('/', self, right) 

  

def _magma_init_(self, magma): 

""" 

Return string that evaluates in Magma to something equivalent 

to this vector. 

  

EXAMPLES:: 

  

sage: v = vector([1,2,3]) 

sage: v._magma_init_(magma) # optional - magma 

'_sage_[...]![1,2,3]' 

sage: mv = magma(v); mv # optional - magma 

(1 2 3) 

sage: mv.Type() # optional - magma 

ModTupRngElt 

sage: mv.Parent() # optional - magma 

Full RSpace of degree 3 over Integer Ring 

  

sage: v = vector(QQ, [1/2, 3/4, 5/6]) 

sage: mv = magma(v); mv # optional - magma 

(1/2 3/4 5/6) 

sage: mv.Type() # optional - magma 

ModTupFldElt 

sage: mv.Parent() # optional - magma 

Full Vector space of degree 3 over Rational Field 

  

A more demanding example:: 

  

sage: R.<x,y,z> = QQ[] 

sage: v = vector([x^3, y, 2/3*z + x/y]) 

sage: magma(v) # optional - magma 

( x^3 y (2/3*y*z + x)/y) 

sage: magma(v).Parent() # optional - magma 

Full Vector space of degree 3 over Multivariate rational function field of rank 3 over Rational Field 

""" 

V = magma(self._parent) 

v = [x._magma_init_(magma) for x in self.list()] 

return '%s![%s]'%(V.name(), ','.join(v)) 

  

def is_Vector(x): 

return isinstance(x, Vector) 

  

cdef class Matrix(ModuleElement): 

  

cdef bint is_sparse_c(self): 

raise NotImplementedError 

  

cdef bint is_dense_c(self): 

raise NotImplementedError 

  

def __mul__(left, right): 

""" 

Multiplication of matrix by matrix, vector, or scalar 

  

AUTHOR: 

  

- Gonzalo Tornaria (2007-06-25) - write test cases and fix them 

  

.. NOTE:: 

  

scalar * matrix is implemented (and tested) in class RingElement 

vector * matrix is implemented (and tested) in class Vector 

  

TESTS: 

  

Here we test (matrix * matrix) multiplication:: 

  

sage: parent(matrix(ZZ,2,2,[1,2,3,4])*matrix(ZZ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Integer Ring 

sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(ZZ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: parent(matrix(ZZ,2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

  

sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(ZZ['x'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*matrix(QQ['x'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ['y'],2,2,[1,2,3,4])*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*matrix(QQ['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*matrix(ZZ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*matrix(QQ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field' 

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*matrix(ZZ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*matrix(QQ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field' 

  

Here we test (matrix * vector) multiplication:: 

  

sage: parent(matrix(ZZ,2,2,[1,2,3,4])*vector(ZZ,[1,2])) 

Ambient free module of rank 2 over the principal ideal domain Integer Ring 

sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(ZZ,[1,2])) 

Vector space of dimension 2 over Rational Field 

sage: parent(matrix(ZZ,2,2,[1,2,3,4])*vector(QQ,[1,2])) 

Vector space of dimension 2 over Rational Field 

sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(QQ,[1,2])) 

Vector space of dimension 2 over Rational Field 

  

sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(ZZ['x'],[1,2])) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*vector(QQ,[1,2])) 

Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(ZZ['x']['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*vector(QQ,[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*vector(ZZ['x']['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*vector(QQ['x'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ['y'],2,2,[1,2,3,4])*vector(ZZ['x']['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*vector(QQ['y'],[1,2])) 

Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*vector(ZZ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*vector(QQ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field' 

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*vector(ZZ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*vector(QQ['y'],[1,2])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field' 

  

Here we test (matrix * scalar) multiplication:: 

  

sage: parent(matrix(ZZ,2,2,[1,2,3,4])*ZZ(1)) 

Full MatrixSpace of 2 by 2 dense matrices over Integer Ring 

sage: parent(matrix(QQ,2,2,[1,2,3,4])*ZZ(1)) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: parent(matrix(ZZ,2,2,[1,2,3,4])*QQ(1)) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: parent(matrix(QQ,2,2,[1,2,3,4])*QQ(1)) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

  

sage: parent(matrix(QQ,2,2,[1,2,3,4])*ZZ['x'](1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*QQ(1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ,2,2,[1,2,3,4])*ZZ['x']['y'](1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*QQ(1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*ZZ['x']['y'](1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*QQ['x'](1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(QQ['y'],2,2,[1,2,3,4])*ZZ['x']['y'](1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(matrix(ZZ['x']['y'],2,2,[1,2,3,4])*QQ['y'](1)) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*ZZ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(matrix(ZZ['x'],2,2,[1,2,3,4])*QQ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Rational Field' 

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*ZZ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(matrix(QQ['x'],2,2,[1,2,3,4])*QQ['y'](1)) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Rational Field' 

  

Here we test (scalar * matrix) multiplication:: 

  

sage: parent(ZZ(1)*matrix(ZZ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Integer Ring 

sage: parent(QQ(1)*matrix(ZZ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: parent(ZZ(1)*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: parent(QQ(1)*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

  

sage: parent(QQ(1)*matrix(ZZ['x'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x'](1)*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(QQ(1)*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x']['y'](1)*matrix(QQ,2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(QQ['x'](1)*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x']['y'](1)*matrix(QQ['x'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(QQ['y'](1)*matrix(ZZ['x']['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: parent(ZZ['x']['y'](1)*matrix(QQ['y'],2,2,[1,2,3,4])) 

Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

  

sage: parent(ZZ['x'](1)*matrix(ZZ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(ZZ['x'](1)*matrix(QQ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field' 

sage: parent(QQ['x'](1)*matrix(ZZ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring' 

sage: parent(QQ['x'](1)*matrix(QQ['y'],2,2,[1,2,3,4])) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for *: 'Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field' 

  

Examples with matrices having matrix coefficients:: 

  

sage: m = matrix 

sage: a = m([[m([[1,2],[3,4]]),m([[5,6],[7,8]])],[m([[9,10],[11,12]]),m([[13,14],[15,16]])]]) 

sage: 3*a 

[[ 3 6] 

[ 9 12] [15 18] 

[21 24]] 

[[27 30] 

[33 36] [39 42] 

[45 48]] 

  

sage: m = matrix 

sage: a = m([[m([[1,2],[3,4]]),m([[5,6],[7,8]])],[m([[9,10],[11,12]]),m([[13,14],[15,16]])]]) 

sage: a*3 

[[ 3 6] 

[ 9 12] [15 18] 

[21 24]] 

[[27 30] 

[33 36] [39 42] 

[45 48]] 

""" 

if have_same_parent(left, right): 

return (<Matrix>left)._matrix_times_matrix_(<Matrix>right) 

return coercion_model.bin_op(left, right, mul) 

  

def __truediv__(left, right): 

""" 

Division of the matrix ``left`` by the matrix or scalar 

``right``. 

  

EXAMPLES:: 

  

sage: a = matrix(ZZ, 2, range(4)) 

sage: operator.truediv(a, 5) 

[ 0 1/5] 

[2/5 3/5] 

sage: a = matrix(ZZ, 2, range(4)) 

sage: b = matrix(ZZ, 2, [1,1,0,5]) 

sage: operator.truediv(a, b) 

[ 0 1/5] 

[ 2 1/5] 

sage: c = matrix(QQ, 2, [3,2,5,7]) 

sage: operator.truediv(c, a) 

[-5/2 3/2] 

[-1/2 5/2] 

""" 

if have_same_parent(left, right): 

return left * ~right 

return coercion_model.bin_op(left, right, truediv) 

  

def __div__(left, right): 

""" 

Division of the matrix ``left`` by the matrix or scalar ``right``. 

  

EXAMPLES:: 

  

sage: a = matrix(ZZ, 2, range(4)) 

sage: a / 5 

[ 0 1/5] 

[2/5 3/5] 

sage: a = matrix(ZZ, 2, range(4)) 

sage: b = matrix(ZZ, 2, [1,1,0,5]) 

sage: a / b 

[ 0 1/5] 

[ 2 1/5] 

sage: c = matrix(QQ, 2, [3,2,5,7]) 

sage: c / a 

[-5/2 3/2] 

[-1/2 5/2] 

sage: a / c 

[-5/11 3/11] 

[-1/11 5/11] 

sage: a / 7 

[ 0 1/7] 

[2/7 3/7] 

  

Other rings work just as well:: 

  

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

sage: b = matrix(ZZ,2,2,[4,6,1,2]) 

sage: a / b 

[1 2] 

[2 0] 

sage: c = matrix(GF(3),2,2,[1,2,1,1]) 

sage: a / c 

[1 2] 

[1 1] 

sage: a = matrix(RDF,2,2,[.1,-.4,1.2,-.6]) 

sage: b = matrix(RDF,2,2,[.3,.1,-.5,1.3]) 

sage: a / b # rel tol 1e-10 

[-0.15909090909090906 -0.29545454545454547] 

[ 2.863636363636364 -0.6818181818181817] 

sage: R.<t> = ZZ['t'] 

sage: a = matrix(R,2,2,[t^2,t+1,-t,t+2]) 

sage: b = matrix(R,2,2,[t^3-1,t,-t+3,t^2]) 

sage: a / b 

[ (t^4 + t^2 - 2*t - 3)/(t^5 - 3*t) (t^4 - t - 1)/(t^5 - 3*t)] 

[ (-t^3 + t^2 - t - 6)/(t^5 - 3*t) (t^4 + 2*t^3 + t^2 - t - 2)/(t^5 - 3*t)] 

""" 

if have_same_parent(left, right): 

return left * ~right 

return coercion_model.bin_op(left, right, div) 

  

cdef _vector_times_matrix_(matrix_right, Vector vector_left): 

raise TypeError 

  

cdef _matrix_times_vector_(matrix_left, Vector vector_right): 

raise TypeError 

  

cdef _matrix_times_matrix_(left, Matrix right): 

raise TypeError 

  

  

  

def is_Matrix(x): 

return isinstance(x, Matrix) 

  

def is_IntegralDomainElement(x): 

""" 

Return ``True`` if x is of type IntegralDomainElement. 

""" 

return isinstance(x, IntegralDomainElement) 

  

cdef class IntegralDomainElement(CommutativeRingElement): 

def is_nilpotent(self): 

return self.is_zero() 

  

  

def is_DedekindDomainElement(x): 

""" 

Return ``True`` if x is of type DedekindDomainElement. 

""" 

return isinstance(x, DedekindDomainElement) 

  

cdef class DedekindDomainElement(IntegralDomainElement): 

pass 

  

def is_PrincipalIdealDomainElement(x): 

""" 

Return ``True`` if x is of type PrincipalIdealDomainElement. 

""" 

return isinstance(x, PrincipalIdealDomainElement) 

  

cdef class PrincipalIdealDomainElement(DedekindDomainElement): 

def lcm(self, right): 

""" 

Return the least common multiple of ``self`` and ``right``. 

""" 

if not isinstance(right, Element) or not ((<Element>right)._parent is self._parent): 

from sage.arith.all import lcm 

return coercion_model.bin_op(self, right, lcm) 

return self._lcm(right) 

  

  

# This is pretty nasty low level stuff. The idea is to speed up construction 

# of EuclideanDomainElements (in particular Integers) by skipping some tp_new 

# calls up the inheritance tree. 

PY_SET_TP_NEW(EuclideanDomainElement, Element) 

  

def is_EuclideanDomainElement(x): 

""" 

Return ``True`` if x is of type EuclideanDomainElement. 

""" 

return isinstance(x, EuclideanDomainElement) 

  

cdef class EuclideanDomainElement(PrincipalIdealDomainElement): 

  

def degree(self): 

raise NotImplementedError 

  

def leading_coefficient(self): 

raise NotImplementedError 

  

def quo_rem(self, other): 

raise NotImplementedError 

  

def __divmod__(self, other): 

""" 

Return the quotient and remainder of ``self`` divided by ``other``. 

  

EXAMPLES:: 

  

sage: divmod(5,3) 

(1, 2) 

sage: divmod(25r,12) 

(2, 1) 

sage: divmod(25,12r) 

(2, 1) 

  

""" 

if isinstance(self, Element): 

return self.quo_rem(other) 

else: 

x, y = canonical_coercion(self, other) 

return x.quo_rem(y) 

  

cpdef _floordiv_(self, right): 

""" 

Quotient of division of ``self`` by other. This is denoted //. 

  

This default implementation assumes that ``quo_rem`` has been 

implemented. 

  

EXAMPLES:: 

  

sage: cython(''' 

....: from sage.structure.element cimport EuclideanDomainElement 

....: cdef class MyElt(EuclideanDomainElement): 

....: def quo_rem(self, other): 

....: return self._parent.var('quo,rem') 

....: ''') 

sage: e = MyElt(SR) 

sage: e // e 

quo 

""" 

Q, _ = self.quo_rem(right) 

return Q 

  

cpdef _mod_(self, other): 

""" 

Remainder of division of ``self`` by other. 

  

This default implementation assumes that ``quo_rem`` has been 

implemented. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: x % (x+1) 

-1 

sage: (x^3 + x - 1) % (x^2 - 1) 

2*x - 1 

  

:: 

  

sage: cython(''' 

....: from sage.structure.element cimport EuclideanDomainElement 

....: cdef class MyElt(EuclideanDomainElement): 

....: def quo_rem(self, other): 

....: return self._parent.var('quo,rem') 

....: ''') 

sage: e = MyElt(SR) 

sage: e % e 

rem 

""" 

_, R = self.quo_rem(other) 

return R 

  

  

def is_FieldElement(x): 

""" 

Return ``True`` if x is of type FieldElement. 

""" 

return isinstance(x, FieldElement) 

  

cdef class FieldElement(CommutativeRingElement): 

cpdef _floordiv_(self, right): 

""" 

Return the quotient of self and other. Since these are field 

elements, the floor division is exactly the same as usual division. 

  

EXAMPLES:: 

  

sage: K.<b> = NumberField(x^4 + x^2 + 2/3) 

sage: c = (1+b) // (1-b); c 

3/4*b^3 + 3/4*b^2 + 3/2*b + 1/2 

sage: (1+b) / (1-b) == c 

True 

sage: c * (1-b) 

b + 1 

""" 

return self._div_(right) 

  

def is_unit(self): 

r""" 

Return ``True`` if ``self`` is a unit in its parent ring. 

  

EXAMPLES:: 

  

sage: a = 2/3; a.is_unit() 

True 

  

On the other hand, 2 is not a unit, since its parent is `\ZZ`. 

  

:: 

  

sage: a = 2; a.is_unit() 

False 

sage: parent(a) 

Integer Ring 

  

However, a is a unit when viewed as an element of QQ:: 

  

sage: a = QQ(2); a.is_unit() 

True 

""" 

return not not self 

  

def _lcm(self, FieldElement other): 

""" 

Return the least common multiple of ``self`` and other. 

""" 

if self.is_zero() and other.is_zero(): 

return self 

else: 

return self._parent(1) 

  

def quo_rem(self, right): 

r""" 

Return the quotient and remainder obtained by dividing ``self`` by 

``right``. Since this element lives in a field, the remainder is always 

zero and the quotient is ``self/right``. 

  

TESTS: 

  

Test if :trac:`8671` is fixed:: 

  

sage: R.<x,y> = QQ[] 

sage: S.<a,b> = R.quo(y^2 + 1) 

sage: S.is_field = lambda : False 

sage: F = Frac(S); u = F.one() 

sage: u.quo_rem(u) 

(1, 0) 

""" 

if not isinstance(right, FieldElement) or not (parent(right) is self._parent): 

right = self.parent()(right) 

return self/right, 0 

  

def divides(self, FieldElement other): 

r""" 

Check whether ``self`` divides other, for field elements. 

  

Since this is a field, all values divide all other values, 

except that zero does not divide any non-zero values. 

  

EXAMPLES:: 

  

sage: K.<rt3> = QQ[sqrt(3)] 

sage: K(0).divides(rt3) 

False 

sage: rt3.divides(K(17)) 

True 

sage: K(0).divides(K(0)) 

True 

sage: rt3.divides(K(0)) 

True 

""" 

if not (other._parent is self._parent): 

other = self.parent()(other) 

return bool(self) or other.is_zero() 

  

def is_AlgebraElement(x): 

""" 

Return ``True`` if x is of type AlgebraElement. 

  

TESTS:: 

  

sage: from sage.structure.element import is_AlgebraElement 

sage: R.<x,y> = FreeAlgebra(QQ,2) 

sage: is_AlgebraElement(x*y) 

True 

  

sage: is_AlgebraElement(1) 

False 

""" 

return isinstance(x, AlgebraElement) 

  

cdef class AlgebraElement(RingElement): 

pass 

  

def is_CommutativeAlgebraElement(x): 

""" 

Return ``True`` if x is of type CommutativeAlgebraElement. 

""" 

return isinstance(x, CommutativeAlgebraElement) 

  

cdef class CommutativeAlgebraElement(CommutativeRingElement): 

pass 

  

def is_InfinityElement(x): 

""" 

Return ``True`` if x is of type InfinityElement. 

  

TESTS:: 

  

sage: from sage.structure.element import is_InfinityElement 

sage: is_InfinityElement(1) 

False 

  

sage: is_InfinityElement(oo) 

True 

""" 

return isinstance(x, InfinityElement) 

  

cdef class InfinityElement(RingElement): 

def __invert__(self): 

from sage.rings.all import ZZ 

return ZZ(0) 

  

  

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

# 

# Coercion of elements 

# 

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

  

cpdef canonical_coercion(x, y): 

""" 

``canonical_coercion(x,y)`` is what is called before doing an 

arithmetic operation between ``x`` and ``y``. It returns a pair ``(z,w)`` 

such that ``z`` is got from ``x`` and ``w`` from ``y`` via canonical coercion and 

the parents of ``z`` and ``w`` are identical. 

  

EXAMPLES:: 

  

sage: A = Matrix([[0, 1], [1, 0]]) 

sage: canonical_coercion(A, 1) 

( 

[0 1] [1 0] 

[1 0], [0 1] 

) 

""" 

return coercion_model.canonical_coercion(x,y) 

  

cpdef bin_op(x, y, op): 

return coercion_model.bin_op(x,y,op) 

  

  

def coerce(Parent p, x): 

try: 

return p._coerce_c(x) 

except AttributeError: 

return p(x) 

  

# We define this base class here to avoid circular cimports. 

cdef class CoercionModel: 

""" 

Most basic coercion scheme. If it doesn't already match, throw an error. 

""" 

cpdef canonical_coercion(self, x, y): 

if parent(x) is parent(y): 

return x,y 

raise TypeError("no common canonical parent for objects with parents: '%s' and '%s'"%(parent(x), parent(y))) 

  

cpdef bin_op(self, x, y, op): 

if parent(x) is parent(y): 

return op(x,y) 

raise bin_op_exception(op, x, y) 

  

cpdef richcmp(self, x, y, int op): 

x, y = self.canonical_coercion(x, y) 

return PyObject_RichCompare(x, y, op) 

  

  

from . import coerce 

cdef CoercionModel coercion_model = coerce.CoercionModel_cache_maps() 

  

# Make this accessible as Python object 

globals()["coercion_model"] = coercion_model 

  

  

def get_coercion_model(): 

""" 

Return the global coercion model. 

  

EXAMPLES:: 

  

sage: import sage.structure.element as e 

sage: cm = e.get_coercion_model() 

sage: cm 

<sage.structure.coerce.CoercionModel_cache_maps object at ...> 

sage: cm is coercion_model 

True 

""" 

return coercion_model 

  

  

def coercion_traceback(dump=True): 

r""" 

This function is very helpful in debugging coercion errors. It prints 

the tracebacks of all the errors caught in the coercion detection. Note 

that failure is cached, so some errors may be omitted the second time 

around (as it remembers not to retry failed paths for speed reasons. 

  

For performance and caching reasons, exception recording must be 

explicitly enabled before using this function. 

  

EXAMPLES:: 

  

sage: cm = sage.structure.element.get_coercion_model() 

sage: cm.record_exceptions() 

sage: 1 + 1/5 

6/5 

sage: coercion_traceback() # Should be empty, as all went well. 

sage: 1/5 + GF(5).gen() 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: 'Rational Field' and 'Finite Field of size 5' 

sage: coercion_traceback() 

Traceback (most recent call last): 

... 

TypeError: no common canonical parent for objects with parents: 'Rational Field' and 'Finite Field of size 5' 

""" 

if dump: 

for traceback in coercion_model.exception_stack(): 

print(traceback) 

else: 

return coercion_model.exception_stack() 

  

  

def coerce_binop(method): 

r""" 

Decorator for a binary operator method for applying coercion to the 

arguments before calling the method. 

  

Consider a parent class in the category framework, `S`, whose element class 

expose a method `binop`. If `a` and `b` are elements of `S`, then 

`a.binop(b)` behaves as expected. If `a` and `b` are not elements of `S`, 

but rather have a common parent `T` whose element class also exposes 

`binop`, we would rather expect `a.binop(b)` to compute `aa.binop(bb)`, 

where `aa = T(a)` and `bb = T(b)`. This decorator ensures that behaviour 

without having to otherwise modify the implementation of `binop` on the 

element class of `A`. 

  

Since coercion will be attempted on the arguments of the decorated method, a 

`TypeError` will be thrown if there is no common parent between the 

elements. An `AttributeError` or `NotImplementedError` or similar will be 

thrown if there is a common parent of the arguments, but its element class 

does not implement a method of the same name as the decorated method. 

  

EXAMPLES: 

  

Sparse polynomial rings uses `@coerce_binop` on `gcd`:: 

  

sage: S.<x> = PolynomialRing(ZZ,sparse=True) 

sage: f = x^2 

sage: g = x 

sage: f.gcd(g) #indirect doctest 

x 

sage: T = PolynomialRing(QQ, name='x', sparse=True) 

sage: h = 1/2*T(x) 

sage: u = f.gcd(h); u #indirect doctest 

x 

sage: u.parent() == T 

True 

  

Another real example:: 

  

sage: R1=QQ['x,y'] 

sage: R2=QQ['x,y,z'] 

sage: f=R1(1) 

sage: g=R1(2) 

sage: h=R2(1) 

sage: f.gcd(g) 

1 

sage: f.gcd(g,algorithm='modular') 

1 

sage: f.gcd(h) 

1 

sage: f.gcd(h,algorithm='modular') 

1 

sage: h.gcd(f) 

1 

sage: h.gcd(f,'modular') 

1 

  

We demonstrate a small class using `@coerce_binop` on a method:: 

  

sage: from sage.structure.element import coerce_binop 

sage: class MyRational(Rational): 

....: def __init__(self,value): 

....: self.v = value 

....: @coerce_binop 

....: def test_add(self, other, keyword='z'): 

....: return (self.v, other, keyword) 

  

Calls func directly if the two arguments have the same parent:: 

  

sage: x = MyRational(1) 

sage: x.test_add(1/2) 

(1, 1/2, 'z') 

sage: x.test_add(1/2, keyword=3) 

(1, 1/2, 3) 

  

Passes through coercion and does a method lookup if the left operand is not 

the same. If the common parent's element class does not have a method of the 

same name, an exception is raised:: 

  

sage: x.test_add(2) 

(1, 2, 'z') 

sage: x.test_add(2, keyword=3) 

(1, 2, 3) 

sage: x.test_add(CC(2)) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.rings.complex_number.ComplexNumber' object has no attribute 'test_add' 

  

TESTS: 

  

Test that additional arguments given to the method do not override 

the ``self`` argument, see :trac:`21322`:: 

  

sage: f.gcd(g, 1) 

Traceback (most recent call last): 

... 

TypeError: algorithm 1 not supported 

""" 

@sage_wraps(method) 

def new_method(self, other, *args, **kwargs): 

if have_same_parent(self, other): 

return method(self, other, *args, **kwargs) 

else: 

a, b = coercion_model.canonical_coercion(self, other) 

if a is self: 

return method(a, b, *args, **kwargs) 

else: 

return getattr(a, method.__name__)(b, *args, **kwargs) 

return new_method 

  

  

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

  

def generic_power(a, n, one=None): 

""" 

Computes `a^n`, where `n` is an integer, and `a` is an object which 

supports multiplication. Optionally an additional argument, 

which is used in the case that ``n == 0``: 

  

- ``one`` - the "unit" element, returned directly (can be anything) 

  

If this is not supplied, ``int(1)`` is returned. 

  

EXAMPLES:: 

  

sage: from sage.structure.element import generic_power 

sage: generic_power(int(12),int(0)) 

doctest:...: DeprecationWarning: import 'generic_power' from sage.arith.power instead 

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

1 

sage: generic_power(int(0),int(100)) 

0 

sage: generic_power(Integer(10),Integer(0)) 

1 

sage: generic_power(Integer(0),Integer(23)) 

0 

sage: sum([generic_power(2,i) for i in range(17)]) #test all 4-bit combinations 

131071 

sage: F = Zmod(5) 

sage: a = generic_power(F(2), 5); a 

2 

sage: a.parent() is F 

True 

sage: a = generic_power(F(1), 2) 

sage: a.parent() is F 

True 

  

sage: generic_power(int(5), 0) 

1 

""" 

from sage.misc.superseded import deprecation 

deprecation(24256, "import 'generic_power' from sage.arith.power instead") 

if one is not None: 

# Special cases not handled by sage.arith.power 

if not n: 

return one 

if n < 0: 

return ~arith_generic_power(a, -n) 

return arith_generic_power(a, n)