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

r""" 

Sets 

""" 

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

# Copyright (C) 2005 David Kohel <kohel@maths.usyd.edu> 

# William Stein <wstein@math.ucsd.edu> 

# 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr> 

# 2008-2014 Nicolas M. Thiery <nthiery at users.sf.net> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

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

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

from __future__ import print_function, absolute_import 

from six.moves import range 

 

from sage.misc.cachefunc import cached_method 

from sage.misc.sage_unittest import TestSuite 

from sage.misc.abstract_method import abstract_method 

from sage.misc.lazy_attribute import lazy_attribute 

from sage.misc.lazy_import import lazy_import, LazyImport 

from sage.misc.lazy_format import LazyFormat 

from sage.misc.superseded import deprecated_function_alias 

from sage.categories.category import Category 

from sage.categories.category_singleton import Category_singleton 

# Do not use sage.categories.all here to avoid initialization loop 

from sage.categories.morphism import SetMorphism 

from sage.categories.sets_with_partial_maps import SetsWithPartialMaps 

from sage.categories.subquotients import SubquotientsCategory 

from sage.categories.quotients import QuotientsCategory 

from sage.categories.subobjects import SubobjectsCategory 

from sage.categories.isomorphic_objects import IsomorphicObjectsCategory 

from sage.categories.algebra_functor import AlgebrasCategory 

from sage.categories.cartesian_product import CartesianProductsCategory, CartesianProductFunctor 

from sage.categories.realizations import RealizationsCategory, Category_realization_of_parent 

from sage.categories.with_realizations import WithRealizationsCategory 

from sage.categories.category_with_axiom import CategoryWithAxiom 

lazy_import('sage.sets.cartesian_product', 'CartesianProduct') 

 

def print_compare(x, y): 

""" 

Helper method used in 

:meth:`Sets.ParentMethods._test_elements_eq_symmetric`, 

:meth:`Sets.ParentMethods._test_elements_eq_tranisitive`. 

 

INPUT: 

 

- ``x`` -- an element 

 

- ``y`` -- an element 

 

EXAMPLES:: 

 

sage: from sage.categories.sets_cat import print_compare 

sage: print_compare(1,2) 

1 != 2 

sage: print_compare(1,1) 

1 == 1 

 

""" 

if x == y: 

return LazyFormat("%s == %s")%(x, y) 

else: 

return LazyFormat("%s != %s")%(x, y) 

 

class EmptySetError(ValueError): 

""" 

Exception raised when some operation can't be performed on the empty set. 

 

EXAMPLES:: 

 

sage: def first_element(st): 

....: if not st: raise EmptySetError("no elements") 

....: else: return st[0] 

sage: first_element(Set((1,2,3))) 

1 

sage: first_element(Set([])) 

Traceback (most recent call last): 

... 

EmptySetError: no elements 

""" 

pass 

 

class Sets(Category_singleton): 

r""" 

The category of sets. 

 

The base category for collections of elements with = (equality). 

 

This is also the category whose objects are all parents. 

 

EXAMPLES:: 

 

sage: Sets() 

Category of sets 

sage: Sets().super_categories() 

[Category of sets with partial maps] 

sage: Sets().all_super_categories() 

[Category of sets, Category of sets with partial maps, Category of objects] 

 

Let us consider an example of set:: 

 

sage: P = Sets().example("inherits") 

sage: P 

Set of prime numbers 

 

See ``P??`` for the code. 

 

 

P is in the category of sets:: 

 

sage: P.category() 

Category of sets 

 

and therefore gets its methods from the following classes:: 

 

sage: for cl in P.__class__.mro(): print(cl) 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category'> 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits'> 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Abstract'> 

<class 'sage.structure.unique_representation.UniqueRepresentation'> 

<class 'sage.structure.unique_representation.CachedRepresentation'> 

<type 'sage.misc.fast_methods.WithEqualityById'> 

<type 'sage.structure.parent.Parent'> 

<type 'sage.structure.category_object.CategoryObject'> 

<type 'sage.structure.sage_object.SageObject'> 

<class 'sage.categories.sets_cat.Sets.parent_class'> 

<class 'sage.categories.sets_with_partial_maps.SetsWithPartialMaps.parent_class'> 

<class 'sage.categories.objects.Objects.parent_class'> 

<... 'object'> 

 

We run some generic checks on P:: 

 

sage: TestSuite(P).run(verbose=True) 

running ._test_an_element() . . . pass 

running ._test_cardinality() . . . pass 

running ._test_category() . . . pass 

running ._test_elements() . . . 

Running the test suite of self.an_element() 

running ._test_category() . . . pass 

running ._test_eq() . . . pass 

running ._test_new() . . . pass 

running ._test_not_implemented_methods() . . . pass 

running ._test_pickling() . . . pass 

pass 

running ._test_elements_eq_reflexive() . . . pass 

running ._test_elements_eq_symmetric() . . . pass 

running ._test_elements_eq_transitive() . . . pass 

running ._test_elements_neq() . . . pass 

running ._test_eq() . . . pass 

running ._test_new() . . . pass 

running ._test_not_implemented_methods() . . . pass 

running ._test_pickling() . . . pass 

running ._test_some_elements() . . . pass 

 

Now, we manipulate some elements of P:: 

 

sage: P.an_element() 

47 

sage: x = P(3) 

sage: x.parent() 

Set of prime numbers 

sage: x in P, 4 in P 

(True, False) 

sage: x.is_prime() 

True 

 

They get their methods from the following classes:: 

 

sage: for cl in x.__class__.mro(): print(cl) 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class'> 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits.Element'> 

<type 'sage.rings.integer.IntegerWrapper'> 

<type 'sage.rings.integer.Integer'> 

<type 'sage.structure.element.EuclideanDomainElement'> 

<type 'sage.structure.element.PrincipalIdealDomainElement'> 

<type 'sage.structure.element.DedekindDomainElement'> 

<type 'sage.structure.element.IntegralDomainElement'> 

<type 'sage.structure.element.CommutativeRingElement'> 

<type 'sage.structure.element.RingElement'> 

<type 'sage.structure.element.ModuleElement'> 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Abstract.Element'> 

<type 'sage.structure.element.Element'> 

<type 'sage.structure.sage_object.SageObject'> 

<class 'sage.categories.sets_cat.Sets.element_class'> 

<class 'sage.categories.sets_with_partial_maps.SetsWithPartialMaps.element_class'> 

<class 'sage.categories.objects.Objects.element_class'> 

<... 'object'> 

 

FIXME: Objects.element_class is not very meaningful ... 

 

 

TESTS:: 

 

sage: TestSuite(Sets()).run() 

 

""" 

 

def super_categories(self): 

r""" 

We include SetsWithPartialMaps between Sets and Objects so that we 

can define morphisms between sets that are only partially defined. 

This is also to have the Homset constructor not complain that 

SetsWithPartialMaps is not a supercategory of Fields, for example. 

 

EXAMPLES:: 

 

sage: Sets().super_categories() 

[Category of sets with partial maps] 

""" 

return [SetsWithPartialMaps()] 

 

def _call_(self, X, enumerated_set=False): 

r""" 

Construct an object in this category from the data ``X``. 

 

INPUT: 

 

- ``X`` -- an object to be converted into a set 

 

- ``enumerated_set`` -- if set to ``True`` and the input is either a 

Python tuple or a Python list then the output will be a finite 

enumerated set. 

 

EXAMPLES:: 

 

sage: Sets()(ZZ) 

Integer Ring 

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

{1, 2, 3} 

 

sage: S = Sets()([1, 2, 3]); S.category() 

Category of finite sets 

sage: S = Sets()([1, 2, 3], enumerated_set=True); S.category() 

Category of facade finite enumerated sets 

 

.. NOTE:: 

 

Using ``Sets()(A)`` used to implement some sort of forgetful functor 

into the ``Sets()`` category. This feature has been removed, because 

it was not consistent with the semantic of :meth:`Category.__call__`. 

Proper forgetful functors will eventually be implemented, with 

another syntax. 

""" 

if enumerated_set and type(X) in (tuple,list,range): 

from sage.categories.enumerated_sets import EnumeratedSets 

return EnumeratedSets()(X) 

from sage.sets.set import Set 

return Set(X) 

 

def example(self, choice = None): 

""" 

Returns examples of objects of ``Sets()``, as per 

:meth:`Category.example() 

<sage.categories.category.Category.example>`. 

 

EXAMPLES:: 

 

sage: Sets().example() 

Set of prime numbers (basic implementation) 

 

sage: Sets().example("inherits") 

Set of prime numbers 

 

sage: Sets().example("facade") 

Set of prime numbers (facade implementation) 

 

sage: Sets().example("wrapper") 

Set of prime numbers (wrapper implementation) 

""" 

if choice is None: 

from sage.categories.examples.sets_cat import PrimeNumbers 

return PrimeNumbers() 

elif choice == "inherits": 

from sage.categories.examples.sets_cat import PrimeNumbers_Inherits 

return PrimeNumbers_Inherits() 

elif choice == "facade": 

from sage.categories.examples.sets_cat import PrimeNumbers_Facade 

return PrimeNumbers_Facade() 

elif choice == "wrapper": 

from sage.categories.examples.sets_cat import PrimeNumbers_Wrapper 

return PrimeNumbers_Wrapper() 

else: 

raise ValueError("Unkown choice") 

 

class SubcategoryMethods: 

 

@cached_method 

def CartesianProducts(self): 

r""" 

Return the full subcategory of the objects of ``self`` 

constructed as Cartesian products. 

 

.. SEEALSO:: 

 

- :class:`.cartesian_product.CartesianProductFunctor` 

- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction` 

 

EXAMPLES:: 

 

sage: Sets().CartesianProducts() 

Category of Cartesian products of sets 

sage: Semigroups().CartesianProducts() 

Category of Cartesian products of semigroups 

sage: EuclideanDomains().CartesianProducts() 

Category of Cartesian products of commutative rings 

""" 

return CartesianProductsCategory.category_of(self) 

 

@cached_method 

def Subquotients(self): 

r""" 

Return the full subcategory of the objects of ``self`` 

constructed as subquotients. 

 

Given a concrete category ``self == As()`` (i.e. a subcategory 

of ``Sets()``), ``As().Subquotients()`` returns the category 

of objects of ``As()`` endowed with a distinguished 

description as subquotient of some other object of ``As()``. 

 

EXAMPLES:: 

 

sage: Monoids().Subquotients() 

Category of subquotients of monoids 

 

A parent `A` in ``As()`` is further in 

``As().Subquotients()`` if there is a distinguished parent 

`B` in ``As()``, called the *ambient set*, a subobject 

`B'` of `B`, and a pair of maps: 

 

.. MATH:: 

 

l: A \to B' \text{ and } r: B' \to A 

 

called respectively the *lifting map* and *retract map* 

such that `r \circ l` is the identity of `A` and `r` is a 

morphism in ``As()``. 

 

.. TODO:: Draw the typical commutative diagram. 

 

It follows that, for each operation `op` of the category, 

we have some property like: 

 

.. MATH:: 

 

op_A(e) = r(op_B(l(e))), \text{ for all } e\in A 

 

This allows for implementing the operations on `A` from 

those on `B`. 

 

The two most common use cases are: 

 

- *homomorphic images* (or *quotients*), when `B'=B`, 

`r` is an homomorphism from `B` to `A` (typically a 

canonical quotient map), and `l` a section of it (not 

necessarily a homomorphism); see :meth:`Quotients`; 

 

- *subobjects* (up to an isomorphism), when `l` is an 

embedding from `A` into `B`; in this case, `B'` is 

typically isomorphic to `A` through the inverse 

isomorphisms `r` and `l`; see :meth:`Subobjects`; 

 

.. NOTE:: 

 

- The usual definition of "subquotient" 

(:wikipedia:`Subquotient`) does not involve the 

lifting map `l`. This map is required in Sage's 

context to make the definition constructive. It is 

only used in computations and does not affect their 

results. This is relatively harmless since the 

category is a concrete category (i.e., its objects 

are sets and its morphisms are set maps). 

 

- In mathematics, especially in the context of 

quotients, the retract map `r` is often referred to 

as a *projection map* instead. 

 

- Since `B'` is not specified explicitly, it is 

possible to abuse the framework with situations 

where `B'` is not quite a subobject and `r` not 

quite a morphism, as long as the lifting and retract 

maps can be used as above to compute all the 

operations in `A`. Use at your own risk! 

 

Assumptions: 

 

- For any category ``As()``, ``As().Subquotients()`` is a 

subcategory of ``As()``. 

 

Example: a subquotient of a group is a group (e.g., a left 

or right quotient of a group by a non-normal subgroup is 

not in this category). 

 

- This construction is covariant: if ``As()`` is a 

subcategory of ``Bs()``, then ``As().Subquotients()`` is a 

subcategory of ``Bs().Subquotients()``. 

 

Example: if `A` is a subquotient of `B` in the category of 

groups, then it is also a subquotient of `B` in the category 

of monoids. 

 

- If the user (or a program) calls ``As().Subquotients()``, 

then it is assumed that subquotients are well defined in 

this category. This is not checked, and probably never will 

be. Note that, if a category ``As()`` does not specify 

anything about its subquotients, then its subquotient 

category looks like this:: 

 

sage: EuclideanDomains().Subquotients() 

Join of Category of euclidean domains 

and Category of subquotients of monoids 

 

Interface: the ambient set `B` of `A` is given by 

``A.ambient()``. The subset `B'` needs not be specified, so 

the retract map is handled as a partial map from `B` to `A`. 

 

The lifting and retract map are implemented 

respectively as methods ``A.lift(a)`` and ``A.retract(b)``. 

As a shorthand for the former, one can use alternatively 

``a.lift()``:: 

 

sage: S = Semigroups().Subquotients().example(); S 

An example of a (sub)quotient semigroup: a quotient of the left zero semigroup 

sage: S.ambient() 

An example of a semigroup: the left zero semigroup 

sage: S(3).lift().parent() 

An example of a semigroup: the left zero semigroup 

sage: S(3) * S(1) == S.retract( S(3).lift() * S(1).lift() ) 

True 

 

See ``S?`` for more. 

 

.. TODO:: use a more interesting example, like `\ZZ/n\ZZ`. 

 

.. SEEALSO:: 

 

- :meth:`Quotients`, :meth:`Subobjects`, :meth:`IsomorphicObjects` 

- :class:`.subquotients.SubquotientsCategory` 

- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction` 

 

TESTS:: 

 

sage: TestSuite(Sets().Subquotients()).run() 

""" 

return SubquotientsCategory.category_of(self) 

 

@cached_method 

def Quotients(self): 

r""" 

Return the full subcategory of the objects of ``self`` 

constructed as quotients. 

 

Given a concrete category ``As()`` (i.e. a subcategory of 

``Sets()``), ``As().Quotients()`` returns the category of 

objects of ``As()`` endowed with a distinguished 

description as quotient (in fact homomorphic image) of 

some other object of ``As()``. 

 

Implementing an object of ``As().Quotients()`` is done in 

the same way as for ``As().Subquotients()``; namely by 

providing an ambient space and a lift and a retract 

map. See :meth:`Subquotients` for detailed instructions. 

 

.. SEEALSO:: 

 

- :meth:`Subquotients` for background 

- :class:`.quotients.QuotientsCategory` 

- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction` 

 

EXAMPLES:: 

 

sage: C = Semigroups().Quotients(); C 

Category of quotients of semigroups 

sage: C.super_categories() 

[Category of subquotients of semigroups, Category of quotients of sets] 

sage: C.all_super_categories() 

[Category of quotients of semigroups, 

Category of subquotients of semigroups, 

Category of semigroups, 

Category of subquotients of magmas, 

Category of magmas, 

Category of quotients of sets, 

Category of subquotients of sets, 

Category of sets, 

Category of sets with partial maps, 

Category of objects] 

 

The caller is responsible for checking that the given category 

admits a well defined category of quotients:: 

 

sage: EuclideanDomains().Quotients() 

Join of Category of euclidean domains 

and Category of subquotients of monoids 

and Category of quotients of semigroups 

 

TESTS:: 

 

sage: TestSuite(C).run() 

""" 

return QuotientsCategory.category_of(self) 

 

@cached_method 

def Subobjects(self): 

r""" 

Return the full subcategory of the objects of ``self`` 

constructed as subobjects. 

 

Given a concrete category ``As()`` (i.e. a subcategory of 

``Sets()``), ``As().Subobjects()`` returns the category of 

objects of ``As()`` endowed with a distinguished embedding 

into some other object of ``As()``. 

 

Implementing an object of ``As().Subobjects()`` is done in 

the same way as for ``As().Subquotients()``; namely by 

providing an ambient space and a lift and a retract 

map. In the case of a trivial embedding, the two maps will 

typically be identity maps that just change the parent of 

their argument. See :meth:`Subquotients` for detailed 

instructions. 

 

.. SEEALSO:: 

 

- :meth:`Subquotients` for background 

- :class:`.subobjects.SubobjectsCategory` 

- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction` 

 

EXAMPLES:: 

 

sage: C = Sets().Subobjects(); C 

Category of subobjects of sets 

 

sage: C.super_categories() 

[Category of subquotients of sets] 

 

sage: C.all_super_categories() 

[Category of subobjects of sets, 

Category of subquotients of sets, 

Category of sets, 

Category of sets with partial maps, 

Category of objects] 

 

Unless something specific about subobjects is implemented for this 

category, one actually gets an optimized super category:: 

 

sage: C = Semigroups().Subobjects(); C 

Join of Category of subquotients of semigroups 

and Category of subobjects of sets 

 

The caller is responsible for checking that the given category 

admits a well defined category of subobjects. 

 

TESTS:: 

 

sage: Semigroups().Subobjects().is_subcategory(Semigroups().Subquotients()) 

True 

sage: TestSuite(C).run() 

 

""" 

return SubobjectsCategory.category_of(self) 

 

@cached_method 

def IsomorphicObjects(self): 

r""" 

Return the full subcategory of the objects of ``self`` 

constructed by isomorphism. 

 

Given a concrete category ``As()`` (i.e. a subcategory of 

``Sets()``), ``As().IsomorphicObjects()`` returns the category of 

objects of ``As()`` endowed with a distinguished description as 

the image of some other object of ``As()`` by an isomorphism in 

this category. 

 

See :meth:`Subquotients` for background. 

 

EXAMPLES: 

 

In the following example, `A` is defined as the image by `x\mapsto 

x^2` of the finite set `B = \{1,2,3\}`:: 

 

sage: A = FiniteEnumeratedSets().IsomorphicObjects().example(); A 

The image by some isomorphism of An example of a finite enumerated set: {1,2,3} 

 

Since `B` is a finite enumerated set, so is `A`:: 

 

sage: A in FiniteEnumeratedSets() 

True 

sage: A.cardinality() 

3 

sage: A.list() 

[1, 4, 9] 

 

The isomorphism from `B` to `A` is available as:: 

 

sage: A.retract(3) 

9 

 

and its inverse as:: 

 

sage: A.lift(9) 

3 

 

It often is natural to declare those morphisms as coercions so 

that one can do ``A(b)`` and ``B(a)`` to go back and forth between 

`A` and `B` (TODO: refer to a category example where the maps are 

declared as a coercion). This is not done by default. Indeed, in 

many cases one only wants to transport part of the structure of 

`B` to `A`. Assume for example, that one wants to construct the 

set of integers `B=ZZ`, endowed with ``max`` as addition, and 

``+`` as multiplication instead of the usual ``+`` and ``*``. One 

can construct `A` as isomorphic to `B` as an infinite enumerated 

set. However `A` is *not* isomorphic to `B` as a ring; for 

example, for `a\in A` and `a\in B`, the expressions `a+A(b)` and 

`B(a)+b` give completely different results; hence we would not want 

the expression `a+b` to be implicitly resolved to any one of above 

two, as the coercion mechanism would do. 

 

Coercions also cannot be used with facade parents (see 

:class:`Sets.Facade`) like in the example above. 

 

 

We now look at a category of isomorphic objects:: 

 

sage: C = Sets().IsomorphicObjects(); C 

Category of isomorphic objects of sets 

 

sage: C.super_categories() 

[Category of subobjects of sets, Category of quotients of sets] 

 

sage: C.all_super_categories() 

[Category of isomorphic objects of sets, 

Category of subobjects of sets, 

Category of quotients of sets, 

Category of subquotients of sets, 

Category of sets, 

Category of sets with partial maps, 

Category of objects] 

 

Unless something specific about isomorphic objects is implemented 

for this category, one actually get an optimized super category:: 

 

sage: C = Semigroups().IsomorphicObjects(); C 

Join of Category of quotients of semigroups 

and Category of isomorphic objects of sets 

 

.. SEEALSO:: 

 

- :meth:`Subquotients` for background 

- :class:`.isomorphic_objects.IsomorphicObjectsCategory` 

- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction` 

 

TESTS:: 

 

sage: TestSuite(Sets().IsomorphicObjects()).run() 

""" 

return IsomorphicObjectsCategory.category_of(self) 

 

@cached_method 

def Topological(self): 

""" 

Return the subcategory of the topological objects of ``self``. 

 

TESTS:: 

 

sage: TestSuite(Sets().Topological()).run() 

""" 

from sage.categories.topological_spaces import TopologicalSpacesCategory 

return TopologicalSpacesCategory.category_of(self) 

 

@cached_method 

def Metric(self): 

""" 

Return the subcategory of the metric objects of ``self``. 

 

TESTS:: 

 

sage: TestSuite(Sets().Metric()).run() 

""" 

from sage.categories.metric_spaces import MetricSpacesCategory 

return MetricSpacesCategory.category_of(self) 

 

@cached_method 

def Algebras(self, base_ring): 

""" 

Return the category of objects constructed as algebras of 

objects of ``self`` over ``base_ring``. 

 

INPUT: 

 

- ``base_ring`` -- a ring 

 

See :meth:`Sets.ParentMethods.algebra` for the precise 

meaning in Sage of the *algebra of an object*. 

 

EXAMPLES:: 

 

sage: Monoids().Algebras(QQ) 

Category of monoid algebras over Rational Field 

 

sage: Groups().Algebras(QQ) 

Category of group algebras over Rational Field 

 

sage: AdditiveMagmas().AdditiveAssociative().Algebras(QQ) 

Category of additive semigroup algebras over Rational Field 

 

sage: Monoids().Algebras(Rings()) 

Category of monoid algebras over Category of rings 

 

.. SEEALSO:: 

 

- :class:`.algebra_functor.AlgebrasCategory` 

- :class:`~.covariant_functorial_construction.CovariantFunctorialConstruction` 

 

TESTS:: 

 

sage: TestSuite(Groups().Finite().Algebras(QQ)).run() 

""" 

from sage.categories.rings import Rings 

assert base_ring in Rings or (isinstance(base_ring, Category) 

and base_ring.is_subcategory(Rings())) 

return AlgebrasCategory.category_of(self, base_ring) 

 

@cached_method 

def Finite(self): 

""" 

Return the full subcategory of the finite objects of ``self``. 

 

EXAMPLES:: 

 

sage: Sets().Finite() 

Category of finite sets 

sage: Rings().Finite() 

Category of finite rings 

 

TESTS:: 

 

sage: TestSuite(Sets().Finite()).run() 

sage: Rings().Finite.__module__ 

'sage.categories.sets_cat' 

""" 

return self._with_axiom('Finite') 

 

@cached_method 

def Infinite(self): 

""" 

Return the full subcategory of the infinite objects of ``self``. 

 

EXAMPLES:: 

 

sage: Sets().Infinite() 

Category of infinite sets 

sage: Rings().Infinite() 

Category of infinite rings 

 

TESTS:: 

 

sage: TestSuite(Sets().Infinite()).run() 

sage: Rings().Infinite.__module__ 

'sage.categories.sets_cat' 

""" 

return self._with_axiom('Infinite') 

 

@cached_method 

def Enumerated(self): 

""" 

Return the full subcategory of the enumerated objects of ``self``. 

 

An enumerated object can be iterated to get its elements. 

 

EXAMPLES:: 

 

sage: Sets().Enumerated() 

Category of enumerated sets 

sage: Rings().Finite().Enumerated() 

Category of finite enumerated rings 

sage: Rings().Infinite().Enumerated() 

Category of infinite enumerated rings 

 

TESTS:: 

 

sage: TestSuite(Sets().Enumerated()).run() 

sage: Rings().Enumerated.__module__ 

'sage.categories.sets_cat' 

""" 

return self._with_axiom('Enumerated') 

 

def Facade(self): 

r""" 

Return the full subcategory of the facade objects of ``self``. 

 

.. _facade-sets: 

 

.. RUBRIC:: What is a facade set? 

 

Recall that, in Sage, :ref:`sets are modelled by *parents* 

<category-primer-parents-elements-categories>`, and their 

elements know which distinguished set they belong to. For 

example, the ring of integers `\ZZ` is modelled by the 

parent :obj:`ZZ`, and integers know that they belong to 

this set:: 

 

sage: ZZ 

Integer Ring 

sage: 42.parent() 

Integer Ring 

 

Sometimes, it is convenient to represent the elements of a 

parent ``P`` by elements of some other parent. For 

example, the elements of the set of prime numbers are 

represented by plain integers:: 

 

sage: Primes() 

Set of all prime numbers: 2, 3, 5, 7, ... 

sage: p = Primes().an_element(); p 

43 

sage: p.parent() 

Integer Ring 

 

In this case, ``P`` is called a *facade set*. 

 

This feature is advertised through the category of `P`:: 

 

sage: Primes().category() 

Category of facade infinite enumerated sets 

sage: Sets().Facade() 

Category of facade sets 

 

Typical use cases include modeling a subset of an existing 

parent:: 

 

sage: Set([4,6,9]) # random 

{4, 6, 9} 

sage: Sets().Facade().example() 

An example of facade set: the monoid of positive integers 

 

or the union of several parents:: 

 

sage: Sets().Facade().example("union") 

An example of a facade set: the integers completed by +-infinity 

 

or endowing an existing parent with more (or less!) 

structure:: 

 

sage: Posets().example("facade") 

An example of a facade poset: the positive integers ordered by divisibility 

 

Let us investigate in detail a close variant of this last 

example: let `P` be set of divisors of `12` partially 

ordered by divisibility. There are two options for 

representing its elements: 

 

1. as plain integers:: 

 

sage: P = Poset((divisors(12), attrcall("divides")), facade=True) 

 

2. as integers, modified to be aware that their parent is `P`:: 

 

sage: Q = Poset((divisors(12), attrcall("divides")), facade=False) 

 

The advantage of option 1. is that one needs not do 

conversions back and forth between `P` and `\ZZ`. The 

disadvantage is that this introduces an ambiguity when 

writing `2 < 3`: does this compare `2` and `3` w.r.t. the 

natural order on integers or w.r.t. divisibility?:: 

 

sage: 2 < 3 

True 

 

To raise this ambiguity, one needs to explicitly specify 

the underlying poset as in `2 <_P 3`:: 

 

sage: P = Posets().example("facade") 

sage: P.lt(2,3) 

False 

 

On the other hand, with option 2. and once constructed, 

the elements know unambiguously how to compare 

themselves:: 

 

sage: Q(2) < Q(3) 

False 

sage: Q(2) < Q(6) 

True 

 

Beware that ``P(2)`` is still the integer `2`. Therefore 

``P(2) < P(3)`` still compares `2` and `3` as integers!:: 

 

sage: P(2) < P(3) 

True 

 

In short `P` being a facade parent is one of the programmatic 

counterparts (with e.g. coercions) of the usual mathematical idiom: 

"for ease of notation, we identify an element of `P` with the 

corresponding integer". Too many identifications lead to 

confusion; the lack thereof leads to heavy, if not obfuscated, 

notations. Finding the right balance is an art, and even though 

there are common guidelines, it is ultimately up to the writer to 

choose which identifications to do. This is no different in code. 

 

.. SEEALSO:: 

 

The following examples illustrate various ways to 

implement subsets like the set of prime numbers; look 

at their code for details:: 

 

sage: Sets().example("facade") 

Set of prime numbers (facade implementation) 

sage: Sets().example("inherits") 

Set of prime numbers 

sage: Sets().example("wrapper") 

Set of prime numbers (wrapper implementation) 

 

.. RUBRIC:: Specifications 

 

A parent which is a facade must either: 

 

- call :meth:`Parent.__init__` using the ``facade`` parameter to 

specify a parent, or tuple thereof. 

- overload the method :meth:`~Sets.Facade.ParentMethods.facade_for`. 

 

.. NOTE:: 

 

The concept of facade parents was originally introduced 

in the computer algebra system MuPAD. 

 

TESTS: 

 

Check that multiple categories initialisation 

works (:trac:`13801`):: 

 

sage: class A(Parent): 

....: def __init__(self): 

....: Parent.__init__(self, category=(FiniteEnumeratedSets(),Monoids()), facade=True) 

sage: a = A() 

 

sage: Posets().Facade() 

Category of facade posets 

sage: Posets().Facade().Finite() is Posets().Finite().Facade() 

True 

""" 

return self._with_axiom('Facade') 

 

Facades = deprecated_function_alias(17073, Facade) 

 

class ParentMethods: 

# TODO: simplify the _element_constructor_ definition logic 

# TODO: find a nicer mantra for conditionally defined methods 

@lazy_attribute 

def _element_constructor_(self): 

r""" 

TESTS:: 

 

sage: S = Sets().example() 

sage: S._element_constructor_(17) 

17 

sage: S(17) # indirect doctest 

17 

 

sage: A = FreeModule(QQ, 3) 

sage: A.element_class 

<type 'sage.modules.vector_rational_dense.Vector_rational_dense'> 

sage: A._element_constructor_ 

<bound method FreeModule_ambient_field_with_category._element_constructor_ of Vector space of dimension 3 over Rational Field> 

 

sage: B = SymmetricGroup(3).algebra(ZZ) 

sage: B.element_class 

<...SymmetricGroupAlgebra_n_with_category.element_class'> 

sage: B._element_constructor_ 

<bound method SymmetricGroupAlgebra_n_with_category._element_constructor_ 

of Symmetric group algebra of order 3 over Integer Ring> 

""" 

if hasattr(self, "element_class"): 

return self._element_constructor_from_element_class 

else: 

return NotImplemented 

 

def _element_constructor_from_element_class(self, *args, **keywords): 

""" 

The default constructor for elements of this parent ``self``. 

 

Among other things, it is called upon ``self(data)`` when 

the coercion model did not find a way to coerce ``data`` into 

this parent. 

 

This default implementation for 

:meth:`_element_constructor_` calls the constructor of the 

element class, passing ``self`` as first argument. 

 

EXAMPLES:: 

 

sage: S = Sets().example("inherits") 

sage: s = S._element_constructor_from_element_class(17); s 

17 

sage: type(s) 

<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class'> 

""" 

return self.element_class(self, *args, **keywords) 

 

def is_parent_of(self, element): 

""" 

Return whether ``self`` is the parent of ``element``. 

 

INPUT: 

 

- ``element`` -- any object 

 

EXAMPLES:: 

 

sage: S = ZZ 

sage: S.is_parent_of(1) 

True 

sage: S.is_parent_of(2/1) 

False 

 

This method differs from :meth:`__contains__` because it 

does not attempt any coercion:: 

 

sage: 2/1 in S, S.is_parent_of(2/1) 

(True, False) 

sage: int(1) in S, S.is_parent_of(int(1)) 

(True, False) 

""" 

from sage.structure.element import parent 

return parent(element) == self 

 

@abstract_method 

def __contains__(self, x): 

""" 

Test whether the set ``self`` contains the object ``x``. 

 

All parents in the category ``Sets()`` should implement this method. 

 

EXAMPLES:: 

 

sage: P = Sets().example(); P 

Set of prime numbers (basic implementation) 

sage: 12 in P 

False 

sage: P(5) in P 

True 

""" 

 

@cached_method 

def an_element(self): 

r""" 

Return a (preferably typical) element of this parent. 

 

This is used both for illustration and testing purposes. If the 

set ``self`` is empty, :meth:`an_element` should raise the exception 

:class:`EmptySetError`. 

 

This default implementation calls :meth:`_an_element_` and 

caches the result. Any parent should implement either 

:meth:`an_element` or :meth:`_an_element_`. 

 

EXAMPLES:: 

 

sage: CDF.an_element() 

1.0*I 

sage: ZZ[['t']].an_element() 

t 

""" 

return self._an_element_() 

 

def _test_an_element(self, **options): 

""" 

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

 

See also: :class:`TestSuite`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_an_element() 

 

Let us now write a broken :meth:`.an_element` 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 

 

TESTS:: 

 

sage: FiniteEnumeratedSet([])._test_an_element() 

""" 

tester = self._tester(**options) 

try: 

an_element = self.an_element() 

except EmptySetError: 

return 

tester.assertTrue(an_element in self, "self.an_element() is not in self") 

# tester.assertTrue(self.is_parent_of(an_element), "self is not the parent of self.an_element()") 

# tester.assertEqual(self(an_element), an_element, "element construction is not idempotent") 

if self.is_parent_of(an_element): 

tester.assertEqual(self(an_element), an_element, "element construction is not idempotent") 

else: # Allows self(an_element) to fails for facade parent. 

try: 

rebuilt_element = self(an_element) 

except NotImplementedError: 

tester.info("\n The set doesn't seems to implement __call__; skipping test of construction idempotency") 

pass 

else: 

tester.assertEqual(rebuilt_element, an_element, "element construction is not idempotent") 

 

 

def _test_elements(self, tester = None, **options): 

""" 

Run generic tests on element(s) of ``self``. 

 

See also: :class:`TestSuite`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_elements(verbose = True) 

<BLANKLINE> 

Running the test suite of self.an_element() 

running ._test_category() . . . pass 

running ._test_eq() . . . pass 

running ._test_new() . . . pass 

running ._test_nonzero_equal() . . . pass 

running ._test_not_implemented_methods() . . . pass 

running ._test_pickling() . . . pass 

<BLANKLINE> 

 

Debugging tip: in case of failure of this test, run instead:: 

 

sage: TestSuite(C.an_element()).run() 

 

Let us now implement a parent whose elements cannot be pickled:: 

 

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

sage: class Bla(SageObject): pass 

sage: class CCls(PrimeNumbers): 

....: def an_element(self): 

....: return Bla() 

sage: CC = CCls() 

sage: CC._test_elements() 

Failure in _test_pickling: 

... 

PicklingError: Can't pickle <class '__main__.Bla'>: attribute lookup __main__.Bla failed 

... 

The following tests failed: _test_pickling 

""" 

# TODO: add native support for nested test suites to TestSuite 

 

# The intention is to raise an exception only if this is 

# run as a sub-testsuite of a larger testsuite. 

is_sub_testsuite = (tester is not None) 

tester = self._tester(tester = tester, **options) 

# Or do we want to run the test on some_elements? 

try: 

an_element = self.an_element() 

except EmptySetError: 

return 

tester.info("\n Running the test suite of self.an_element()") 

TestSuite(an_element).run(verbose = tester._verbose, prefix = tester._prefix+" ", 

raise_on_failure = is_sub_testsuite) 

tester.info(tester._prefix+" ", newline = False) 

 

def _test_elements_eq_reflexive(self, **options): 

""" 

Run generic tests on the equality of elements. 

 

Test that ``==`` is reflexive. 

 

See also: :class:`TestSuite`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_elements_eq_reflexive() 

 

We try a non-reflexive equality:: 

 

sage: P = Sets().example("wrapper") 

sage: P._test_elements_eq_reflexive() 

sage: eq = P.element_class.__eq__ 

 

sage: P.element_class.__eq__ = (lambda x, y: 

....: False if eq(x, P(47)) and eq(y, P(47)) else eq(x, y)) 

sage: P._test_elements_eq_reflexive() 

Traceback (most recent call last): 

... 

AssertionError: 47 != 47 

 

We restore ``P.element_class`` in a proper state for further tests:: 

 

sage: P.element_class.__eq__ = eq 

 

""" 

tester = self._tester(**options) 

S = list(tester.some_elements()) + [None, 0] 

for x in S: 

tester.assertEqual(x, x) 

 

def _test_elements_eq_symmetric(self, **options): 

""" 

Run generic tests on the equality of elements. 

 

This tests that ``==`` is symmetric. 

 

See also: :class:`TestSuite`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_elements_eq_symmetric() 

 

We test a non symmetric equality:: 

 

sage: P = Sets().example("wrapper") 

sage: P._test_elements_eq_symmetric() 

sage: eq = P.element_class.__eq__ 

 

sage: def non_sym_eq(x, y): 

....: if not y in P: return False 

....: elif eq(x, P(47)) and eq(y, P(53)): return True 

....: else: return eq(x, y) 

sage: P.element_class.__eq__ = non_sym_eq 

sage: P._test_elements_eq_symmetric() 

Traceback (most recent call last): 

... 

AssertionError: non symmetric equality: 47 == 53 but 53 != 47 

 

We restore ``P.element_class`` in a proper state for further tests:: 

 

sage: P.element_class.__eq__ = eq 

 

""" 

tester = self._tester(**options) 

S = list(tester.some_elements()) + [None, 0] 

n = tester._max_runs 

from sage.misc.misc import some_tuples 

for x,y in some_tuples(S, 2, tester._max_runs): 

tester.assertEqual(x==y, y==x, 

LazyFormat("non symmetric equality: %s but %s")%( 

print_compare(x, y), print_compare(y, x))) 

 

def _test_elements_eq_transitive(self, **options): 

""" 

Run generic tests on the equality of elements. 

 

Test that ``==`` is transitive. 

 

See also: :class:`TestSuite`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_elements_eq_transitive() 

 

We test a non transitive equality:: 

 

sage: R = Zp(3) 

sage: Sets().ParentMethods._test_elements_eq_transitive.__func__(R,elements=[R(3,2),R(3,1),R(0)]) 

Traceback (most recent call last): 

... 

AssertionError: non transitive equality: 

3 + O(3^2) == O(3) and O(3) == 0 but 3 + O(3^2) != 0 

 

""" 

tester = self._tester(**options) 

S = list(tester.some_elements()) 

n = tester._max_runs 

if (len(S)+2)**3 <= n: 

S = list(S) + [None, 0] 

else: 

from random import sample 

from sage.rings.integer import Integer 

S = sample(S, Integer(n).nth_root(3,truncate_mode=1)[0] - 2) + [None, 0] 

 

for x in S: 

for y in S: 

if not x == y: continue 

for z in S: 

if not y == z: continue 

tester.assertTrue(x == z, 

LazyFormat("non transitive equality:\n" 

"%s and %s but %s")%( 

print_compare(x, y), 

print_compare(y, z), 

print_compare(x, z))) 

 

def _test_elements_neq(self, **options): 

""" 

Run generic tests on the equality of elements. 

 

Test that ``==`` and ``!=`` are consistent. 

 

See also: :class:`TestSuite`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_elements_neq() 

 

We try a broken inequality:: 

 

sage: P = Sets().example("wrapper") 

sage: P._test_elements_neq() 

sage: ne = P.element_class.__ne__ 

sage: eq = P.element_class.__eq__ 

 

sage: P.element_class.__ne__ = lambda x, y: False 

sage: P._test_elements_neq() 

Traceback (most recent call last): 

... 

AssertionError: __eq__ and __ne__ inconsistency: 

47 == 53 returns False but 47 != 53 returns False 

 

sage: P.element_class.__ne__ = lambda x, y: not(x == y) 

 

We restore ``P.element_class`` in a proper state for further tests:: 

 

sage: P.element_class.__ne__ = ne 

sage: P.element_class.__eq__ = eq 

""" 

tester = self._tester(**options) 

S = list(tester.some_elements()) + [None, 0] 

 

from sage.misc.misc import some_tuples 

for x,y in some_tuples(S, 2, tester._max_runs): 

tester.assertNotEqual(x == y, x != y, 

LazyFormat("__eq__ and __ne__ inconsistency:\n" 

" %s == %s returns %s but %s != %s returns %s")%( 

x, y, (x == y), x, y, (x != y))) 

 

def some_elements(self): 

""" 

Return a list (or iterable) of elements of ``self``. 

 

This is typically used for running generic tests 

(see :class:`TestSuite`). 

 

This default implementation calls :meth:`.an_element`. 

 

EXAMPLES:: 

 

sage: S = Sets().example(); S 

Set of prime numbers (basic implementation) 

sage: S.an_element() 

47 

sage: S.some_elements() 

[47] 

sage: S = Set([]) 

sage: S.some_elements() 

[] 

 

This method should return an iterable, *not* an iterator. 

""" 

try: 

return [self.an_element()] 

except EmptySetError: 

return [] 

 

def _test_some_elements(self, **options): 

""" 

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

 

.. SEEALSO:: :class:`TestSuite` 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_some_elements() 

 

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

 

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

sage: class CCls(PrimeNumbers): 

....: def some_elements(self): 

....: return [self(17), 32] 

sage: CC = CCls() 

sage: CC._test_some_elements() 

Traceback (most recent call last): 

... 

AssertionError: the object 32 in self.some_elements() is not in self 

""" 

tester = self._tester(**options) 

elements = self.some_elements() 

# Todo: enable this once 

#tester.assertTrue(elements != iter(elements), 

# "self.some_elements() should return an iterable, not an iterator") 

for x in elements: 

tester.assertTrue(x in self, LazyFormat( 

"the object %s in self.some_elements() is not in self")%(x,)) 

 

#Note: the four methods 'cardinality', 'is_finite_, 'is_empty' and 

# 'random_element' might or might not be implemented in the parent 

# objects. Most of the time a default implementation will be provided by 

# a subcategory of Sets. We do not declare them as optional abstract 

# methods to not pollute the namespace. 

 

# def cardinality(self) 

# def is_finite(self) 

# def is_empty(self) 

# def random_element(self): 

 

def _test_cardinality(self, **options): 

r""" 

Run generic test on the method :meth:`.cardinality`. 

 

EXAMPLES:: 

 

sage: C = Sets().example() 

sage: C._test_cardinality() 

 

Let us now write a broken :meth:`cardinality` method:: 

 

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

sage: class CCls(PrimeNumbers): 

....: def cardinality(self): 

....: return int(5) 

sage: CC = CCls() 

sage: CC._test_cardinality() 

Traceback (most recent call last): 

... 

AssertionError: the output of the method cardinality must either 

be a Sage integer or infinity. Not <... 'int'>. 

""" 

try: 

cardinality = self.cardinality() 

except (AttributeError,NotImplementedError): 

return 

from sage.structure.element import parent 

from sage.rings.infinity import Infinity 

from sage.rings.integer_ring import ZZ 

tester = self._tester(**options) 

tester.assertTrue(cardinality is Infinity or parent(cardinality) is ZZ, 

"the output of the method cardinality must either be a Sage integer or infinity. Not {}.".format(type(cardinality))) 

 

# Functorial constructions 

 

def construction(self): 

""" 

Return a pair ``(functor, parent)`` such that 

``functor(parent)`` returns ``self``. If ``self`` does 

not have a functorial construction, return ``None``. 

 

EXAMPLES:: 

 

sage: QQ.construction() 

(FractionField, Integer Ring) 

sage: f, R = QQ['x'].construction() 

sage: f 

Poly[x] 

sage: R 

Rational Field 

sage: f(R) 

Univariate Polynomial Ring in x over Rational Field 

""" 

return None 

 

CartesianProduct = CartesianProduct 

def cartesian_product(*parents, **kwargs): 

""" 

Return the Cartesian product of the parents. 

 

INPUT: 

 

- ``parents`` -- a list (or other iterable) of parents. 

 

- ``category`` -- (default: ``None``) the category the 

Cartesian product belongs to. If ``None`` is passed, 

then 

:meth:`~sage.categories.covariant_functorial_construction.CovariantFactorialConstruction.category_from_parents` 

is used to determine the category. 

 

- ``extra_category`` -- (default: ``None``) a category 

that is added to the Cartesian product in addition 

to the categories obtained from the parents. 

 

- other keyword arguments will passed on to the class used 

for this Cartesian product (see also 

:class:`~sage.sets.cartesian_product.CartesianProduct`). 

 

OUTPUT: 

 

The Cartesian product. 

 

EXAMPLES:: 

 

sage: C = AlgebrasWithBasis(QQ) 

sage: A = C.example(); A.rename("A") 

sage: A.cartesian_product(A,A) 

A (+) A (+) A 

sage: ZZ.cartesian_product(GF(2), FiniteEnumeratedSet([1,2,3])) 

The Cartesian product of (Integer Ring, Finite Field of size 2, {1, 2, 3}) 

 

sage: C = ZZ.cartesian_product(A); C 

The Cartesian product of (Integer Ring, A) 

 

TESTS:: 

 

sage: type(C) 

<class 'sage.sets.cartesian_product.CartesianProduct_with_category'> 

sage: C.category() 

Join of Category of rings and ... 

and Category of Cartesian products of commutative additive groups 

 

:: 

 

sage: cartesian_product([ZZ, ZZ], category=Sets()).category() 

Category of sets 

sage: cartesian_product([ZZ, ZZ]).category() 

Join of 

Category of Cartesian products of commutative rings and 

Category of Cartesian products of enumerated sets 

sage: cartesian_product([ZZ, ZZ], extra_category=Posets()).category() 

Join of 

Category of Cartesian products of commutative rings and 

Category of posets and 

Category of Cartesian products of enumerated sets 

""" 

category = kwargs.pop('category', None) 

extra_category = kwargs.pop('extra_category', None) 

 

category = category or cartesian_product.category_from_parents(parents) 

if extra_category: 

if isinstance(category, (list, tuple)): 

category = tuple(category) + (extra_category,) 

else: 

category = category & extra_category 

return parents[0].CartesianProduct(parents, category=category, **kwargs) 

 

def algebra(self, base_ring, category=None, **kwds): 

""" 

Return the algebra of ``self`` over ``base_ring``. 

 

INPUT: 

 

- ``self`` -- a parent `S` 

- ``base_ring`` -- a ring `K` 

- ``category`` -- a super category of the category 

of `S`, or ``None`` 

 

This returns the space of formal linear combinations of 

elements of `G` with coefficients in `R`, endowed with 

whatever structure can be induced from that of `S`. 

See the documentation of 

:mod:`sage.categories.algebra_functor` for details. 

 

EXAMPLES: 

 

If `S` is a :class:`group <Groups>`, the result is its 

group algebra `KS`:: 

 

sage: S = DihedralGroup(4); S 

Dihedral group of order 8 as a permutation group 

sage: A = S.algebra(QQ); A 

Algebra of Dihedral group of order 8 as a permutation group 

over Rational Field 

sage: A.category() 

Category of finite group algebras over Rational Field 

sage: a = A.an_element(); a 

() + 4*(1,2,3,4) + 2*(1,4)(2,3) 

 

This space is endowed with an algebra structure, obtained 

by extending by bilinearity the multiplication of `G` to a 

multiplication on `RG`:: 

 

sage: a * a 

5*() + 8*(2,4) + 8*(1,2,3,4) + 8*(1,3) + 16*(1,3)(2,4) + 4*(1,4)(2,3) 

 

If `S` is a :class:`monoid <Monoids>`, the result is its 

monoid algebra `KS`:: 

 

sage: S = Monoids().example(); S 

An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd') 

sage: A = S.algebra(QQ); A 

Algebra of An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd') 

over Rational Field 

sage: A.category() 

Category of monoid algebras over Rational Field 

 

Similarly, we can construct algebras for additive magmas, 

monoids, and groups. 

 

One may specify for which category one takes the algebra; 

here we build the algebra of the additive group `GF_3`:: 

 

sage: from sage.categories.additive_groups import AdditiveGroups 

sage: S = GF(7) 

sage: A = S.algebra(QQ, category=AdditiveGroups()); A 

Algebra of Finite Field of size 7 over Rational Field 

sage: A.category() 

Category of finite dimensional additive group algebras 

over Rational Field 

 

sage: a = A(S(1)) 

sage: a 

1 

sage: 1 + a * a * a 

0 + 3 

 

Note that the ``category`` keyword needs to be fed with 

the structure on `S` to be used, not the induced structure 

on the result. 

""" 

if category is None: 

category = self.category() 

from sage.categories.semigroups import Semigroups 

from sage.categories.commutative_additive_semigroups import CommutativeAdditiveSemigroups 

if category.is_subcategory(Semigroups()) and category.is_subcategory(CommutativeAdditiveSemigroups()): 

raise TypeError( 

""" `S = {}` is both an additive and a multiplicative semigroup. 

Constructing its algebra is ambiguous. 

Please use, e.g., S.algebra(QQ, category=Semigroups())""".format(self)) 

from sage.categories.groups import Groups 

from sage.categories.additive_groups import AdditiveGroups 

from sage.algebras.group_algebra import GroupAlgebra_class 

algebra_category = category.Algebras(base_ring) 

if (category.is_subcategory(Groups()) 

or category.is_subcategory(AdditiveGroups())): 

# Somewhat dirty hack to wrap non-atomic objects 

from sage.categories.modules_with_basis import ModulesWithBasis 

if self not in ModulesWithBasis: 

if 'prefix' not in kwds: 

kwds['prefix'] = '' 

if 'bracket' not in kwds: 

kwds['bracket'] = False 

result = GroupAlgebra_class(base_ring, self, 

category=algebra_category, **kwds) 

result.__doc__ = Sets.ParentMethods.algebra.__doc__ 

return result 

 

class ElementMethods: 

## Should eventually contain the basic operations which are no math 

## latex, hash, ... 

##def equal(x,y): 

##def =(x,y): 

 

# Used by Element._test_category 

_dummy_attribute = None 

 

def cartesian_product(*elements): 

""" 

Return the Cartesian product of its arguments, as an element of 

the Cartesian product of the parents of those elements. 

 

EXAMPLES:: 

 

sage: C = AlgebrasWithBasis(QQ) 

sage: A = C.example() 

sage: (a,b,c) = A.algebra_generators() 

sage: a.cartesian_product(b, c) 

B[(0, word: a)] + B[(1, word: b)] + B[(2, word: c)] 

 

FIXME: is this a policy that we want to enforce on all parents? 

""" 

from sage.structure.element import parent, Element 

assert all(isinstance(element, Element) for element in elements) 

parents = [parent(element) for element in elements] 

return cartesian_product(parents)._cartesian_product_of_elements(elements) # good name??? 

 

class MorphismMethods: 

@abstract_method(optional=True) 

def __invert__(self): 

r""" 

Return the inverse morphism, or raise an error. 

 

The error may either state that the morphism is not 

invertible, or that Sage cannot invert it. 

 

EXAMPLES:: 

 

sage: i = End(QQ).identity(); i 

Identity endomorphism of Rational Field 

sage: i.__invert__() 

Identity endomorphism of Rational Field 

 

This method is meant to be used with the Python inversion 

operator `~`:: 

 

sage: ~i 

Identity endomorphism of Rational Field 

 

We now try to inverse a couple of morphisms defined by a matrix:: 

 

sage: H = End(QQ^2) 

sage: phi = H(matrix([[1,1],[0,1]])); phi 

Vector space morphism represented by the matrix: 

[1 1] 

[0 1] 

Domain: Vector space of dimension 2 over Rational Field 

Codomain: Vector space of dimension 2 over Rational Field 

sage: ~phi 

Vector space morphism represented by the matrix: 

[ 1 -1] 

[ 0 1] 

Domain: Vector space of dimension 2 over Rational Field 

Codomain: Vector space of dimension 2 over Rational Field 

 

sage: phi = H(matrix([[1,1],[1,1]])) 

sage: ~phi 

Traceback (most recent call last): 

... 

ZeroDivisionError: matrix morphism not invertible 

 

.. NOTE:: 

 

This is an optional method. A default implementation 

raising ``NotImplementedError`` could be provided instead. 

""" 

 

def is_injective(self): 

r""" 

Return whether this map is injective. 

 

EXAMPLES:: 

 

sage: f = ZZ.hom(GF(3)); f 

Natural morphism: 

From: Integer Ring 

To: Finite Field of size 3 

sage: f.is_injective() 

False 

 

Note that many maps do not implement this method:: 

 

sage: R.<x> = ZZ[] 

sage: f = R.hom([x]) 

sage: f.is_injective() 

Traceback (most recent call last): 

... 

NotImplementedError 

 

""" 

if self.domain().cardinality() <= 1: 

return True 

if self.domain().cardinality() > self.codomain().cardinality(): 

return False 

raise NotImplementedError 

 

Enumerated = LazyImport('sage.categories.enumerated_sets', 'EnumeratedSets', at_startup=True) 

Facade = LazyImport('sage.categories.facade_sets', 'FacadeSets') 

Finite = LazyImport('sage.categories.finite_sets', 'FiniteSets', at_startup=True) 

Topological = LazyImport('sage.categories.topological_spaces', 

'TopologicalSpaces', 'Topological', at_startup=True) 

Metric = LazyImport('sage.categories.metric_spaces', 'MetricSpaces', 

'Mertic', at_startup=True) 

 

class Infinite(CategoryWithAxiom): 

 

class ParentMethods: 

 

def is_finite(self): 

""" 

Return whether this set is finite. 

 

Since this set is infinite this always returns ``False``. 

 

EXAMPLES:: 

 

sage: C = InfiniteEnumeratedSets().example() 

sage: C.is_finite() 

False 

 

TESTS:: 

 

sage: from six import get_method_function as gmf 

sage: gmf(C.is_finite) is gmf(sage.categories.sets_cat.Sets.Infinite.ParentMethods.is_finite) 

True 

""" 

return False 

 

def is_empty(self): 

r""" 

Return whether this set is empty. 

 

Since this set is infinite this always returns ``False``. 

 

EXAMPLES:: 

 

sage: C = InfiniteEnumeratedSets().example() 

sage: C.is_empty() 

False 

""" 

return False 

 

def cardinality(self): 

""" 

Count the elements of the enumerated set. 

 

EXAMPLES:: 

 

sage: NN = InfiniteEnumeratedSets().example() 

sage: NN.cardinality() 

+Infinity 

""" 

from sage.rings.infinity import infinity 

return infinity 

 

class Subquotients(SubquotientsCategory): 

""" 

A category for subquotients of sets. 

 

.. SEEALSO:: :meth:`Sets().Subquotients` 

 

EXAMPLES:: 

 

sage: Sets().Subquotients() 

Category of subquotients of sets 

sage: Sets().Subquotients().all_super_categories() 

[Category of subquotients of sets, Category of sets, 

Category of sets with partial maps, 

Category of objects] 

""" 

 

class ParentMethods: 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: from sage.categories.examples.semigroups import IncompleteSubquotientSemigroup 

sage: S = IncompleteSubquotientSemigroup() 

sage: S._repr_() 

'A subquotient of An example of a semigroup: the left zero semigroup' 

""" 

return "A subquotient of %s"%(self.ambient()) 

 

@abstract_method 

def ambient(self): 

""" 

Return the ambient space for ``self``. 

 

EXAMPLES:: 

 

sage: Semigroups().Subquotients().example().ambient() 

An example of a semigroup: the left zero semigroup 

 

.. SEEALSO:: 

 

:meth:`Sets.SubcategoryMethods.Subquotients` for the 

specifications and :meth:`.lift` and :meth:`.retract`. 

""" 

 

# Should lift and retract be declared as conversions to the coercion mechanism ? 

# Compatibility issue: in IntegerModRing, lift is a method returning the actual 

# lifting morphism:: 

# 

# sage: F = IntegerModRing(3) 

# sage: F.lift() 

# Set-theoretic ring morphism: 

# From: Ring of integers modulo 3 

# To: Integer Ring 

# Defn: Choice of lifting map 

@abstract_method 

def lift(self, x): 

""" 

Lift `x` to the ambient space for ``self``. 

 

INPUT: 

 

- ``x`` -- an element of ``self`` 

 

EXAMPLES:: 

 

sage: S = Semigroups().Subquotients().example() 

sage: s = S.an_element() 

sage: s, s.parent() 

(42, An example of a (sub)quotient semigroup: a quotient of the left zero semigroup) 

sage: S.lift(s), S.lift(s).parent() 

(42, An example of a semigroup: the left zero semigroup) 

sage: s.lift(), s.lift().parent() 

(42, An example of a semigroup: the left zero semigroup) 

 

.. SEEALSO:: 

 

:class:`Sets.SubcategoryMethods.Subquotients` for 

the specifications, :meth:`.ambient`, :meth:`.retract`, 

and also :meth:`Sets.Subquotients.ElementMethods.lift`. 

""" 

 

@abstract_method 

def retract(self, x): 

""" 

Retract ``x`` to ``self``. 

 

INPUT: 

 

- ``x`` -- an element of the ambient space for ``self`` 

 

.. SEEALSO:: 

 

:class:`Sets.SubcategoryMethods.Subquotients` for 

the specifications, :meth:`.ambient`, :meth:`.retract`, 

and also :meth:`Sets.Subquotients.ElementMethods.retract`. 

 

EXAMPLES:: 

 

sage: S = Semigroups().Subquotients().example() 

sage: s = S.ambient().an_element() 

sage: s, s.parent() 

(42, An example of a semigroup: the left zero semigroup) 

sage: S.retract(s), S.retract(s).parent() 

(42, An example of a (sub)quotient semigroup: a quotient of the left zero semigroup) 

""" 

 

class ElementMethods: 

 

def lift(self): 

""" 

Lift ``self`` to the ambient space for its parent. 

 

EXAMPLES:: 

 

sage: S = Semigroups().Subquotients().example() 

sage: s = S.an_element() 

sage: s, s.parent() 

(42, An example of a (sub)quotient semigroup: a quotient of the left zero semigroup) 

sage: S.lift(s), S.lift(s).parent() 

(42, An example of a semigroup: the left zero semigroup) 

sage: s.lift(), s.lift().parent() 

(42, An example of a semigroup: the left zero semigroup) 

""" 

return self.parent().lift(self) 

 

class Quotients(QuotientsCategory): 

""" 

A category for quotients of sets. 

 

.. SEEALSO:: :meth:`Sets().Quotients` 

 

EXAMPLES:: 

 

sage: Sets().Quotients() 

Category of quotients of sets 

sage: Sets().Quotients().all_super_categories() 

[Category of quotients of sets, 

Category of subquotients of sets, 

Category of sets, 

Category of sets with partial maps, 

Category of objects] 

""" 

 

class ParentMethods: 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: from sage.categories.examples.semigroups import IncompleteSubquotientSemigroup 

sage: S = IncompleteSubquotientSemigroup(category=Semigroups().Quotients()) 

sage: S._repr_() 

'A quotient of An example of a semigroup: the left zero semigroup' 

""" 

return "A quotient of {}".format(self.ambient()) 

 

def _an_element_(self): 

""" 

Return an element of ``self``, as per 

:meth:`Sets.ParentMethods.an_element` 

 

EXAMPLES:: 

 

sage: S = FiniteEnumeratedSets().IsomorphicObjects().example() 

sage: S.an_element() # indirect doctest 

1 

""" 

return self.retract(self.ambient().an_element()) 

 

class Subobjects(SubobjectsCategory): 

""" 

A category for subobjects of sets. 

 

.. SEEALSO:: :meth:`Sets().Subobjects` 

 

EXAMPLES:: 

 

sage: Sets().Subobjects() 

Category of subobjects of sets 

sage: Sets().Subobjects().all_super_categories() 

[Category of subobjects of sets, 

Category of subquotients of sets, 

Category of sets, 

Category of sets with partial maps, 

Category of objects] 

""" 

 

class ParentMethods: 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: from sage.categories.examples.semigroups import IncompleteSubquotientSemigroup 

sage: S = IncompleteSubquotientSemigroup(category = Semigroups().Subobjects()) 

sage: S._repr_() 

'A subobject of An example of a semigroup: the left zero semigroup' 

""" 

return "A subobject of {}".format(self.ambient()) 

 

class IsomorphicObjects(IsomorphicObjectsCategory): 

""" 

A category for isomorphic objects of sets. 

 

EXAMPLES:: 

 

sage: Sets().IsomorphicObjects() 

Category of isomorphic objects of sets 

sage: Sets().IsomorphicObjects().all_super_categories() 

[Category of isomorphic objects of sets, 

Category of subobjects of sets, Category of quotients of sets, 

Category of subquotients of sets, 

Category of sets, 

Category of sets with partial maps, 

Category of objects] 

""" 

 

class ParentMethods: 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: S = FiniteEnumeratedSets().IsomorphicObjects().example() 

sage: S._repr_() 

'The image by some isomorphism of An example of a finite enumerated set: {1,2,3}' 

""" 

return "The image by some isomorphism of %s"%(self.ambient()) 

 

class CartesianProducts(CartesianProductsCategory): 

""" 

EXAMPLES:: 

 

sage: C = Sets().CartesianProducts().example() 

sage: C 

The Cartesian product of (Set of prime numbers (basic implementation), 

An example of an infinite enumerated set: the non negative integers, 

An example of a finite enumerated set: {1,2,3}) 

sage: C.category() 

Category of Cartesian products of sets 

sage: C.categories() 

[Category of Cartesian products of sets, Category of sets, 

Category of sets with partial maps, 

Category of objects] 

sage: TestSuite(C).run() 

""" 

 

def extra_super_categories(self): 

""" 

A Cartesian product of sets is a set. 

 

EXAMPLES:: 

 

sage: Sets().CartesianProducts().extra_super_categories() 

[Category of sets] 

sage: Sets().CartesianProducts().super_categories() 

[Category of sets] 

""" 

return [Sets()] 

 

def example(self): 

""" 

EXAMPLES:: 

 

sage: Sets().CartesianProducts().example() 

The Cartesian product of (Set of prime numbers (basic implementation), 

An example of an infinite enumerated set: the non negative integers, 

An example of a finite enumerated set: {1,2,3}) 

""" 

from .finite_enumerated_sets import FiniteEnumeratedSets 

from .infinite_enumerated_sets import InfiniteEnumeratedSets 

from .cartesian_product import cartesian_product 

S1 = Sets().example() 

S2 = InfiniteEnumeratedSets().example() 

S3 = FiniteEnumeratedSets().example() 

return cartesian_product([S1, S2, S3]) 

 

 

class ParentMethods: 

def __iter__(self): 

r""" 

Return a lexicographic iterator for the elements of this Cartesian product. 

 

EXAMPLES:: 

 

sage: for x,y in cartesian_product([Set([1,2]), Set(['a','b'])]): 

....: print((x, y)) 

(1, 'a') 

(1, 'b') 

(2, 'a') 

(2, 'b') 

 

sage: A = FiniteEnumeratedSets()(["a", "b"]) 

sage: B = FiniteEnumeratedSets().example(); B 

An example of a finite enumerated set: {1,2,3} 

sage: C = cartesian_product([A, B, A]); C 

The Cartesian product of ({'a', 'b'}, An example of a finite enumerated set: {1,2,3}, {'a', 'b'}) 

sage: C in FiniteEnumeratedSets() 

True 

sage: list(C) 

[('a', 1, 'a'), ('a', 1, 'b'), ('a', 2, 'a'), ('a', 2, 'b'), ('a', 3, 'a'), ('a', 3, 'b'), 

('b', 1, 'a'), ('b', 1, 'b'), ('b', 2, 'a'), ('b', 2, 'b'), ('b', 3, 'a'), ('b', 3, 'b')] 

sage: C.__iter__.__module__ 

'sage.categories.sets_cat' 

 

sage: F22 = GF(2).cartesian_product(GF(2)) 

sage: list(F22) 

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

 

sage: C = cartesian_product([Permutations(10)]*4) 

sage: it = iter(C) 

sage: next(it) 

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

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

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

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

sage: next(it) 

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

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

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

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

 

.. WARNING:: 

 

The elements are returned in lexicographic order, 

which gives a valid enumeration only if all 

factors, but possibly the first one, are 

finite. So the following one is fine:: 

 

sage: it = iter(cartesian_product([ZZ, GF(2)])) 

sage: [next(it) for _ in range(10)] 

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

(-1, 0), (-1, 1), (2, 0), (2, 1), 

(-2, 0), (-2, 1)] 

 

But this one is not:: 

 

sage: it = iter(cartesian_product([GF(2), ZZ])) 

sage: [next(it) for _ in range(10)] 

doctest:...: UserWarning: Sage is not able to determine 

whether the factors of this Cartesian product are 

finite. The lexicographic ordering might not go through 

all elements. 

[(0, 0), (0, 1), (0, -1), (0, 2), (0, -2), 

(0, 3), (0, -3), (0, 4), (0, -4), (0, 5)] 

 

.. NOTE:: 

 

Here it would be faster to use :func:`itertools.product` for sets 

of small size. But the latter expands all factor in memory! 

So we can not reasonably use it in general. 

 

ALGORITHM: 

 

Recipe 19.9 in the Python Cookbook by Alex Martelli 

and David Ascher. 

""" 

if any(f not in Sets().Finite() for f in self.cartesian_factors()[1:]): 

from warnings import warn 

warn("Sage is not able to determine whether the factors of " 

"this Cartesian product are finite. The lexicographic " 

"ordering might not go through all elements.") 

 

# visualize an odometer, with "wheels" displaying "digits"...: 

factors = list(self.cartesian_factors()) 

wheels = map(iter, factors) 

digits = [next(it) for it in wheels] 

while True: 

yield self._cartesian_product_of_elements(digits) 

for i in range(len(digits)-1, -1, -1): 

try: 

digits[i] = next(wheels[i]) 

break 

except StopIteration: 

wheels[i] = iter(factors[i]) 

digits[i] = next(wheels[i]) 

else: 

break 

 

@cached_method 

def an_element(self): 

""" 

EXAMPLES:: 

 

sage: C = Sets().CartesianProducts().example(); C 

The Cartesian product of (Set of prime numbers (basic implementation), 

An example of an infinite enumerated set: the non negative integers, 

An example of a finite enumerated set: {1,2,3}) 

sage: C.an_element() 

(47, 42, 1) 

""" 

return self._cartesian_product_of_elements(s.an_element() for s in self._sets) 

 

def is_empty(self): 

r""" 

Return whether this set is empty. 

 

EXAMPLES:: 

 

 

sage: S1 = FiniteEnumeratedSet([1,2,3]) 

sage: S2 = Set([]) 

sage: cartesian_product([S1,ZZ]).is_empty() 

False 

sage: cartesian_product([S1,S2,S1]).is_empty() 

True 

""" 

return any(c.is_empty() for c in self.cartesian_factors()) 

 

def is_finite(self): 

r""" 

Return whether this set is finite. 

 

EXAMPLES:: 

 

sage: E = FiniteEnumeratedSet([1,2,3]) 

sage: C = cartesian_product([E, SymmetricGroup(4)]) 

sage: C.is_finite() 

True 

 

sage: cartesian_product([ZZ,ZZ]).is_finite() 

False 

sage: cartesian_product([ZZ, Set(), ZZ]).is_finite() 

True 

""" 

f = self.cartesian_factors() 

try: 

# Note: some parent might not implement "is_empty". So we 

# carefully isolate this test. 

test = any(c.is_empty() for c in f) 

except (AttributeError, NotImplementedError): 

pass 

else: 

if test: return test 

return all(c.is_finite() for c in f) 

 

def cardinality(self): 

r""" 

Return the cardinality of self. 

 

EXAMPLES:: 

 

sage: E = FiniteEnumeratedSet([1,2,3]) 

sage: C = cartesian_product([E,SymmetricGroup(4)]) 

sage: C.cardinality() 

72 

 

sage: E = FiniteEnumeratedSet([]) 

sage: C = cartesian_product([E, ZZ, QQ]) 

sage: C.cardinality() 

0 

 

sage: C = cartesian_product([ZZ, QQ]) 

sage: C.cardinality() 

+Infinity 

 

sage: cartesian_product([GF(5), Permutations(10)]).cardinality() 

18144000 

sage: cartesian_product([GF(71)]*20).cardinality() == 71**20 

True 

""" 

f = self.cartesian_factors() 

 

try: 

# Note: some parent might not implement "is_empty". So we 

# carefully isolate this test. 

is_empty = any(c.is_empty() for c in f) 

except (AttributeError,NotImplementedError): 

pass 

else: 

if is_empty: 

from sage.rings.integer_ring import ZZ 

return ZZ.zero() 

elif any(c in Sets().Infinite() for c in f): 

from sage.rings.infinity import Infinity 

return Infinity 

 

from sage.misc.misc_c import prod 

return prod(c.cardinality() for c in f) 

 

def random_element(self, *args): 

r""" 

Return a random element of this Cartesian product. 

 

The extra arguments are passed down to each of the 

factors of the Cartesian product. 

 

EXAMPLES:: 

 

sage: C = cartesian_product([Permutations(10)]*5) 

sage: C.random_element() # random 

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

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

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

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

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

 

sage: C = cartesian_product([ZZ]*10) 

sage: c1 = C.random_element() 

sage: c1 # random 

(3, 1, 4, 1, 1, -3, 0, -4, -17, 2) 

sage: c2 = C.random_element(4,7) 

sage: c2 # random 

(6, 5, 6, 4, 5, 6, 6, 4, 5, 5) 

sage: all(4 <= i < 7 for i in c2) 

True 

""" 

return self._cartesian_product_of_elements( 

c.random_element(*args) for c in self.cartesian_factors()) 

 

@abstract_method 

def _sets_keys(self): 

""" 

Return the indices of the Cartesian factors of ``self``. 

 

EXAMPLES:: 

 

sage: cartesian_product([QQ, ZZ, ZZ])._sets_keys() 

{0, 1, 2} 

""" 

 

@abstract_method 

def cartesian_factors(self): 

""" 

Return the Cartesian factors of ``self``. 

 

EXAMPLES:: 

 

sage: cartesian_product([QQ, ZZ, ZZ]).cartesian_factors() 

(Rational Field, Integer Ring, Integer Ring) 

""" 

 

@abstract_method 

def cartesian_projection(self, i): 

""" 

Return the natural projection onto the `i`-th 

Cartesian factor of ``self``. 

 

INPUT: 

 

- ``i`` -- the index of a Cartesian factor of ``self`` 

 

EXAMPLES:: 

 

sage: C = Sets().CartesianProducts().example(); C 

The Cartesian product of (Set of prime numbers (basic implementation), 

An example of an infinite enumerated set: the non negative integers, 

An example of a finite enumerated set: {1,2,3}) 

sage: x = C.an_element(); x 

(47, 42, 1) 

sage: pi = C.cartesian_projection(1) 

sage: pi(x) 

42 

""" 

 

@abstract_method 

def _cartesian_product_of_elements(self, elements): 

""" 

Return the Cartesian product of the given ``elements``. 

 

This method should accept any iterable. 

 

INPUT: 

 

- ``elements`` -- an iterable (e.g. a tuple or a list) of 

elements of each Cartesian factor of ``self`` 

 

EXAMPLES:: 

 

sage: S1 = Sets().example() 

sage: S2 = InfiniteEnumeratedSets().example() 

sage: X = [S2, S1, S2] 

sage: C = cartesian_product(X) 

sage: C._cartesian_product_of_elements([S.an_element() for S in X]) 

(42, 47, 42) 

sage: C._cartesian_product_of_elements(S.an_element() for S in X) 

(42, 47, 42) 

""" 

 

class ElementMethods: 

 

def cartesian_projection(self, i): 

""" 

Return the projection of ``self`` onto the `i`-th 

factor of the Cartesian product. 

 

INPUT: 

 

- ``i`` -- the index of a factor of the Cartesian product 

 

EXAMPLES:: 

 

sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.__custom_name = "F" 

sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.__custom_name = "G" 

sage: S = cartesian_product([F, G]) 

sage: x = S.monomial((0,4)) + 2 * S.monomial((0,5)) + 3 * S.monomial((1,6)) 

sage: x.cartesian_projection(0) 

B[4] + 2*B[5] 

sage: x.cartesian_projection(1) 

3*B[6] 

""" 

return self.parent().cartesian_projection(i)(self) 

 

summand_projection = deprecated_function_alias(10963, cartesian_projection) 

 

def cartesian_factors(self): 

""" 

Return the Cartesian factors of ``self``. 

 

EXAMPLES:: 

 

sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.__custom_name = "F" 

sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.__custom_name = "G" 

sage: H = CombinatorialFreeModule(ZZ, [4,7]); H.__custom_name = "H" 

sage: S = cartesian_product([F, G, H]) 

sage: x = S.monomial((0,4)) + 2 * S.monomial((0,5)) + 3 * S.monomial((1,6)) + 4 * S.monomial((2,4)) + 5 * S.monomial((2,7)) 

sage: x.cartesian_factors() 

(B[4] + 2*B[5], 3*B[6], 4*B[4] + 5*B[7]) 

sage: [s.parent() for s in x.cartesian_factors()] 

[F, G, H] 

sage: S.zero().cartesian_factors() 

(0, 0, 0) 

sage: [s.parent() for s in S.zero().cartesian_factors()] 

[F, G, H] 

""" 

# TODO: optimize 

return tuple(self.cartesian_projection(i) 

for i in self.parent()._sets_keys()) 

#return Family(self._sets.keys(), self.projection) 

 

summand_split = deprecated_function_alias(10963, cartesian_factors) 

 

class Algebras(AlgebrasCategory): 

 

def extra_super_categories(self): 

""" 

EXAMPLES:: 

 

sage: Sets().Algebras(ZZ).super_categories() 

[Category of modules with basis over Integer Ring] 

 

sage: Sets().Algebras(QQ).extra_super_categories() 

[Category of vector spaces with basis over Rational Field] 

 

sage: Sets().example().algebra(ZZ).categories() 

[Category of set algebras over Integer Ring, 

Category of modules with basis over Integer Ring, 

... 

Category of objects] 

 

""" 

from sage.categories.modules_with_basis import ModulesWithBasis 

return [ModulesWithBasis(self.base_ring())] 

 

class ParentMethods: 

def construction(self): 

r""" 

Return the functorial construction of ``self``. 

 

EXAMPLES:: 

 

sage: A = GroupAlgebra(KleinFourGroup(), QQ) 

sage: A.construction() 

(GroupAlgebraFunctor, Rational Field) 

""" 

from sage.categories.algebra_functor import GroupAlgebraFunctor 

return GroupAlgebraFunctor(self.group()), self.base_ring() 

 

def _repr_(self): 

r""" 

Return the string representation of `self`. 

 

EXAMPLES:: 

 

sage: A = Groups().example().algebra(QQ); A 

Algebra of General Linear Group of degree 4 over Rational Field 

over Rational Field 

sage: A._name = "foo" 

sage: A 

foo over Rational Field 

sage: A = KleinFourGroup().algebra(ZZ) 

sage: A 

Algebra of The Klein 4 group of order 4, as a permutation group 

over Integer Ring 

""" 

if hasattr(self, "_name"): 

return self._name + " over {}".format(self.base_ring()) 

else: 

return 'Algebra of {} over {}'.format(self.basis().keys(), 

self.base_ring()) 

 

class WithRealizations(WithRealizationsCategory): 

 

def extra_super_categories(self): 

""" 

A set with multiple realizations is a facade parent. 

 

EXAMPLES:: 

 

sage: Sets().WithRealizations().extra_super_categories() 

[Category of facade sets] 

sage: Sets().WithRealizations().super_categories() 

[Category of facade sets] 

""" 

return [Sets().Facade()] 

 

def example(self, base_ring = None, set = None): 

r""" 

Return an example of set with multiple realizations, as 

per :meth:`Category.example`. 

 

EXAMPLES:: 

 

sage: Sets().WithRealizations().example() 

The subset algebra of {1, 2, 3} over Rational Field 

 

sage: Sets().WithRealizations().example(ZZ, Set([1,2])) 

The subset algebra of {1, 2} over Integer Ring 

""" 

from sage.rings.rational_field import QQ 

from sage.sets.set import Set 

if base_ring is None: 

base_ring = QQ 

if set is None: 

set = Set([1,2,3]) 

from sage.categories.examples.with_realizations import SubsetAlgebra 

return SubsetAlgebra(base_ring, set) 

 

 

class ParentMethods: 

 

def _test_with_realizations(self, **options): 

r""" 

Test that this parent with realizations is 

properly implemented. 

 

INPUT: 

 

- ``options`` -- any keyword arguments accepted 

by :meth:`_tester` 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example() 

sage: A._test_with_realizations() 

 

See the documentation for :class:`TestSuite` 

for more information. 

""" 

tester = self._tester(**options) 

for R in self.realizations(): 

tester.assertTrue(R in self.Realizations()) 

# Could check that there are coerce maps between any two realizations 

 

@lazy_attribute 

def _realizations(self): 

""" 

This lazily initializes the attribute 

``_realizations`` the first time it is needed. 

 

TESTS:: 

 

sage: class MyParent(Parent): 

....: pass 

sage: P = MyParent(category = Sets().WithRealizations()) 

sage: P._realizations 

[] 

""" 

return [] 

 

def _register_realization(self, realization): 

""" 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(QQ['x']); A 

The subset algebra of {1, 2, 3} over Univariate Polynomial Ring in x over Rational Field 

sage: class ANewRealizationOfA(CombinatorialFreeModule): 

....: pass 

sage: category = A.Realizations() & Algebras(QQ[x]).WithBasis() 

sage: R = ANewRealizationOfA(A.base_ring(), A.F().basis().keys(), category = category) 

sage: R in A.realizations() # indirect doctest 

True 

 

Note: the test above uses ``QQ[x]`` to not interfer 

with other tests. 

""" 

assert realization.realization_of() is self 

self._realizations.append(realization) 

 

def inject_shorthands(self, shorthands=None, verbose=True): 

""" 

Import standard shorthands into the global namespace. 

 

INPUT: 

 

- ``shorthands`` -- a list (or iterable) of strings (default: ``self._shorthands``) 

or ``"all"`` (for ``self._shorthands_all``) 

- ``verbose`` -- boolean (default ``True``); 

whether to print the defined shorthands 

 

EXAMPLES: 

 

When computing with a set with multiple realizations, 

like :class:`SymmetricFunctions` or 

:class:`~sage.categories.examples.with_realizations.SubsetAlgebra`, 

it is convenient to define shorthands for the various 

realizations, but cumbersome to do it by hand:: 

 

sage: S = SymmetricFunctions(ZZ); S 

Symmetric Functions over Integer Ring 

sage: s = S.s(); s 

Symmetric Functions over Integer Ring in the Schur basis 

sage: e = S.e(); e 

Symmetric Functions over Integer Ring in the elementary basis 

 

This method automatizes the process:: 

 

sage: S.inject_shorthands() 

Defining e as shorthand for Symmetric Functions over Integer Ring in the elementary basis 

Defining f as shorthand for Symmetric Functions over Integer Ring in the forgotten basis 

Defining h as shorthand for Symmetric Functions over Integer Ring in the homogeneous basis 

Defining m as shorthand for Symmetric Functions over Integer Ring in the monomial basis 

Defining p as shorthand for Symmetric Functions over Integer Ring in the powersum basis 

Defining s as shorthand for Symmetric Functions over Integer Ring in the Schur basis 

sage: s[1] + e[2] * p[1,1] + 2*h[3] + m[2,1] 

s[1] - 2*s[1, 1, 1] + s[1, 1, 1, 1] + s[2, 1] + 2*s[2, 1, 1] + s[2, 2] + 2*s[3] + s[3, 1] 

 

sage: e 

Symmetric Functions over Integer Ring in the elementary basis 

sage: p 

Symmetric Functions over Integer Ring in the powersum basis 

sage: s 

Symmetric Functions over Integer Ring in the Schur basis 

 

Sometimes, like for symmetric functions, one can 

request for all shorthands to be defined, including 

less common ones:: 

 

sage: S.inject_shorthands("all") 

Defining e as shorthand for Symmetric Functions over Integer Ring in the elementary basis 

Defining f as shorthand for Symmetric Functions over Integer Ring in the forgotten basis 

Defining h as shorthand for Symmetric Functions over Integer Ring in the homogeneous basis 

Defining ht as shorthand for Symmetric Functions over Integer Ring in the induced trivial character basis 

Defining m as shorthand for Symmetric Functions over Integer Ring in the monomial basis 

Defining o as shorthand for Symmetric Functions over Integer Ring in the orthogonal basis 

Defining p as shorthand for Symmetric Functions over Integer Ring in the powersum basis 

Defining s as shorthand for Symmetric Functions over Integer Ring in the Schur basis 

Defining sp as shorthand for Symmetric Functions over Integer Ring in the symplectic basis 

Defining st as shorthand for Symmetric Functions over Integer Ring in the irreducible symmetric group character basis 

Defining w as shorthand for Symmetric Functions over Integer Ring in the Witt basis 

 

The messages can be silenced by setting ``verbose=False``:: 

 

sage: Q = QuasiSymmetricFunctions(ZZ) 

sage: Q.inject_shorthands(verbose=False) 

 

sage: F[1,2,1] + 5*M[1,3] + F[2]^2 

5*F[1, 1, 1, 1] - 5*F[1, 1, 2] - 3*F[1, 2, 1] + 6*F[1, 3] + 

2*F[2, 2] + F[3, 1] + F[4] 

 

sage: F 

Quasisymmetric functions over the Integer Ring in the 

Fundamental basis 

sage: M 

Quasisymmetric functions over the Integer Ring in the 

Monomial basis 

 

One can also just import a subset of the shorthands:: 

 

sage: SQ = SymmetricFunctions(QQ) 

sage: SQ.inject_shorthands(['p', 's'], verbose=False) 

sage: p 

Symmetric Functions over Rational Field in the powersum basis 

sage: s 

Symmetric Functions over Rational Field in the Schur basis 

 

Note that ``e`` is left unchanged:: 

 

sage: e 

Symmetric Functions over Integer Ring in the elementary basis 

 

TESTS:: 

 

sage: e == S.e(), h == S.h(), m == S.m(), p == SQ.p(), s == SQ.s() 

(True, True, True, True, True) 

""" 

from sage.misc.misc import inject_variable 

if shorthands == 'all': 

shorthands = getattr(self, '_shorthands_all', None) 

if shorthands is None: 

shorthands = getattr(self, '_shorthands', None) 

if shorthands is None: 

raise NotImplementedError("no shorthands defined for {}".format(self)) 

for shorthand in shorthands: 

realization = getattr(self, shorthand)() 

if verbose: 

print('Defining {} as shorthand for {}'.format(shorthand, realization)) 

inject_variable(shorthand, realization, warn=False) 

 

@abstract_method(optional=True) 

def a_realization(self): 

""" 

Return a realization of ``self``. 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: A.a_realization() 

The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis 

""" 

 

def realizations(self): 

""" 

Return all the realizations of ``self`` that ``self`` 

is aware of. 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: A.realizations() 

[The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis, The subset algebra of {1, 2, 3} over Rational Field in the In basis, The subset algebra of {1, 2, 3} over Rational Field in the Out basis] 

 

.. NOTE:: 

 

Constructing a parent ``P`` in the category 

``A.Realizations()`` automatically adds ``P`` to 

this list by calling ``A._register_realization(A)`` 

""" 

return self._realizations 

 

def facade_for(self): 

""" 

Return the parents ``self`` is a facade for, that is 

the realizations of ``self`` 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: A.facade_for() 

[The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis, The subset algebra of {1, 2, 3} over Rational Field in the In basis, The subset algebra of {1, 2, 3} over Rational Field in the Out basis] 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: f = A.F().an_element(); f 

F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}] 

sage: i = A.In().an_element(); i 

In[{}] + 2*In[{1}] + 3*In[{2}] + In[{1, 2}] 

sage: o = A.Out().an_element(); o 

Out[{}] + 2*Out[{1}] + 3*Out[{2}] + Out[{1, 2}] 

sage: f in A, i in A, o in A 

(True, True, True) 

""" 

return self.realizations() 

 

# Do we really want this feature? 

class Realizations(Category_realization_of_parent): 

 

def super_categories(self): 

""" 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: A.Realizations().super_categories() 

[Category of realizations of sets] 

""" 

return [Sets().Realizations()] 

 

def _an_element_(self): 

""" 

Return an element of some realization of ``self``. 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: A.an_element() # indirect doctest 

F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}] 

 

TESTS: 

 

Check that we are consistent no matter which basis is 

created first:: 

 

sage: M = posets.BooleanLattice(4).moebius_algebra(QQ) 

sage: I = M.I() 

sage: M._an_element_() 

2*E[0] + 2*E[1] + 3*E[2] 

""" 

return self.a_realization().an_element() 

 

# TODO: maybe this could be taken care of by Sets.Facade()? 

def __contains__(self, x): 

r""" 

Test whether ``x`` is in ``self``, that is if it is an 

element of some realization of ``self``. 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: A.an_element() in A 

True 

sage: A.In().an_element() in A 

True 

sage: A.F().an_element() in A 

True 

sage: A.Out().an_element() in A 

True 

sage: 1 in A 

True 

sage: QQ['x'].an_element() in A 

False 

""" 

return any(x in realization for realization in self.realizations()) 

 

class Realizations(RealizationsCategory): 

 

class ParentMethods: 

 

def __init_extra__(self): 

""" 

Register ``self`` as a realization of ``self.realization_of``. 

 

TESTS:: 

 

sage: A = Sets().WithRealizations().example() 

sage: A.realizations() # indirect doctest 

[The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis, 

The subset algebra of {1, 2, 3} over Rational Field in the In basis, 

The subset algebra of {1, 2, 3} over Rational Field in the Out basis] 

""" 

self.realization_of()._register_realization(self) 

 

@cached_method 

def realization_of(self): 

""" 

Return the parent this is a realization of. 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: In = A.In(); In 

The subset algebra of {1, 2, 3} over Rational Field in the In basis 

sage: In.realization_of() 

The subset algebra of {1, 2, 3} over Rational Field 

""" 

for category in self.categories(): 

if isinstance(category, Category_realization_of_parent): 

return category.base() 

 

def _realization_name(self): 

""" 

Return the name of this realization. 

 

In this default implementation, this is guessed from 

the name of its class. 

 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: In = A.In(); In 

The subset algebra of {1, 2, 3} over Rational Field in the In basis 

sage: In._realization_name() 

'In' 

""" 

# The __base__ gets rid of the with_category 

# The split adds support for nested classes 

return self.__class__.__base__.__name__.split('.')[-1] 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: A = Sets().WithRealizations().example(); A 

The subset algebra of {1, 2, 3} over Rational Field 

sage: In = A.In(); In 

The subset algebra of {1, 2, 3} over Rational Field in the In basis 

 

In the example above, :meth:`repr` was overriden by 

the category ``A.Realizations()``. We now add a new 

(fake) realization which is not in 

``A.Realizations()`` to actually exercise this 

method:: 

 

sage: from sage.categories.realizations import Realizations 

sage: class Blah(Parent): 

....: pass 

sage: P = Blah(category = Sets.WithRealizations.ParentMethods.Realizations(A)) 

sage: P # indirect doctest 

The subset algebra of {1, 2, 3} over Rational Field in the realization Blah 

""" 

return "{} in the realization {}".format(self.realization_of(), self._realization_name()) 

 

# Moved from sage.categories.cartesian_product to avoid circular import errors 

cartesian_product = CartesianProductFunctor()