Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

5093

5094

5095

5096

5097

5098

5099

5100

# -*- coding: utf-8 -*- 

r""" 

Generic structures for linear codes 

 

Linear Codes 

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

 

Let `F = \GF{q}` be a finite field. A rank `k` linear subspace of the vector 

space `F^n` is called an `[n, k]`-linear code, `n` being the length of the 

code and `k` its dimension. Elements of a code `C` are called codewords. 

 

A linear map from `F^k` to an `[n,k]` code `C` is called an "encoding", and it 

can be represented as a `k \times n` matrix, called a generator matrix. 

Alternatively, `C` can be represented by its orthogonal complement in `F^n`, 

i.e. the `n-k`-dimensional vector space `C^\perp` such that the inner product 

of any element from `C` and any element from `C^\perp` is zero. `C^\perp` 

is called the dual code of `C`, and any generator matrix for `C^\perp` is called 

a parity check matrix for `C`. 

 

We commonly endow `F^n` with the Hamming metric, i.e. the weight of a vector is 

the number of non-zero elements in it. The central operation of a linear code is 

then "decoding": given a linear code `C \subset F^n` and a "received word" `r 

\in F^n` , retrieve the codeword `c \in C` such that the Hamming distance 

between `r` and `c` is minimal. 

 

 

Families or Generic codes 

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

 

Linear codes are either studied as generic vector spaces without any known 

structure, or as particular sub-families with special properties. 

 

The class :class:`sage.coding.linear_code.LinearCode` is used to represent the 

former. 

 

For the latter, these will be represented by specialised classes; for instance, 

the family of Hamming codes are represented by the class 

:class:`sage.coding.hamming_code.HammingCode`. Type ``codes.<tab>`` for a list 

of all code families known to Sage. Such code family classes should inherit from 

the abstract base class :class:`sage.coding.linear_code.AbstractLinearCode`. 

 

``AbstractLinearCode`` 

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

 

This is a base class designed to contain methods, features and parameters 

shared by every linear code. For instance, generic algorithms for computing the 

minimum distance, the covering radius, etc. Many of these algorithms are slow, 

e.g. exponential in the code length. For specific subfamilies, better algorithms 

or even closed formulas might be known, in which case the respective method 

should be overridden. 

 

``AbstractLinearCode`` is an abstract class for linear codes, so any linear code 

class should inherit from this class. Also ``AbstractLinearCode`` should never 

itself be instantiated. 

 

See :class:`sage.coding.linear_code.AbstractLinearCode` for details and 

examples. 

 

``LinearCode`` 

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

 

This class is used to represent arbitrary and unstructured linear codes. 

It mostly rely directly on generic methods provided by ``AbstractLinearCode``, which 

means that basic operations on the code (e.g. computation of the minimum 

distance) will use slow algorithms. 

 

A ``LinearCode`` is instantiated by providing a generator matrix:: 

 

sage: M = matrix(GF(2), [[1, 0, 0, 1, 0],\ 

[0, 1, 0, 1, 1],\ 

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

sage: C = codes.LinearCode(M) 

sage: C 

[5, 3] linear code over GF(2) 

sage: C.generator_matrix() 

[1 0 0 1 0] 

[0 1 0 1 1] 

[0 0 1 1 1] 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.basis() 

[ 

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

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

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

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

] 

sage: c = C.basis()[1] 

sage: c in C 

True 

sage: c.nonzero_positions() 

[0, 3, 4] 

sage: c.support() 

[0, 3, 4] 

sage: c.parent() 

Vector space of dimension 7 over Finite Field of size 2 

 

Further references 

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

 

If you want to get started on Sage's linear codes library, see http://doc.sagemath.org/html/en/thematic_tutorials/coding_theory.html 

 

If you want to learn more on the design of this library, see 

http://doc.sagemath.org/html/en/thematic_tutorials/structures_in_coding_theory.html 

 

REFERENCES: 

 

- [HP2003]_ 

 

- [Gu]_ 

 

AUTHORS: 

 

- David Joyner (2005-11-22, 2006-12-03): initial version 

 

- William Stein (2006-01-23): Inclusion in Sage 

 

- David Joyner (2006-01-30, 2006-04): small fixes 

 

- David Joyner (2006-07): added documentation, group-theoretical methods, 

ToricCode 

 

- David Joyner (2006-08): hopeful latex fixes to documentation, added list and 

__iter__ methods to LinearCode and examples, added hamming_weight function, 

fixed random method to return a vector, TrivialCode, fixed subtle bug in 

dual_code, added galois_closure method, fixed mysterious bug in 

permutation_automorphism_group (GAP was over-using "G" somehow?) 

 

- David Joyner (2006-08): hopeful latex fixes to documentation, added 

CyclicCode, best_known_linear_code, bounds_minimum_distance, 

assmus_mattson_designs (implementing Assmus-Mattson Theorem). 

 

- David Joyner (2006-09): modified decode syntax, fixed bug in 

is_galois_closed, added LinearCode_from_vectorspace, extended_code, 

zeta_function 

 

- Nick Alexander (2006-12-10): factor GUAVA code to guava.py 

 

- David Joyner (2007-05): added methods punctured, shortened, divisor, 

characteristic_polynomial, binomial_moment, support for 

LinearCode. Completely rewritten zeta_function (old version is now 

zeta_function2) and a new function, LinearCodeFromVectorSpace. 

 

- David Joyner (2007-11): added zeta_polynomial, weight_enumerator, 

chinen_polynomial; improved best_known_code; made some pythonic revisions; 

added is_equivalent (for binary codes) 

 

- David Joyner (2008-01): fixed bug in decode reported by Harald Schilly, 

(with Mike Hansen) added some doctests. 

 

- David Joyner (2008-02): translated standard_form, dual_code to Python. 

 

- David Joyner (2008-03): translated punctured, shortened, extended_code, 

random (and renamed random to random_element), deleted zeta_function2, 

zeta_function3, added wrapper automorphism_group_binary_code to Robert 

Miller's code), added direct_sum_code, is_subcode, is_self_dual, 

is_self_orthogonal, redundancy_matrix, did some alphabetical reorganizing 

to make the file more readable. Fixed a bug in permutation_automorphism_group 

which caused it to crash. 

 

- David Joyner (2008-03): fixed bugs in spectrum and zeta_polynomial, which 

misbehaved over non-prime base rings. 

 

- David Joyner (2008-10): use CJ Tjhal's MinimumWeight if char = 2 or 3 for 

min_dist; add is_permutation_equivalent and improve 

permutation_automorphism_group using an interface with Robert Miller's code; 

added interface with Leon's code for the spectrum method. 

 

- David Joyner (2009-02): added native decoding methods (see module_decoder.py) 

 

- David Joyner (2009-05): removed dependence on Guava, allowing it to be an 

option. Fixed errors in some docstrings. 

 

- Kwankyu Lee (2010-01): added methods generator_matrix_systematic, information_set, and 

magma interface for linear codes. 

 

- Niles Johnson (2010-08): :trac:`3893`: ``random_element()`` should pass on ``*args`` and ``**kwds``. 

 

- Thomas Feulner (2012-11): :trac:`13723`: deprecation of ``hamming_weight()`` 

 

- Thomas Feulner (2013-10): added methods to compute a canonical representative 

and the automorphism group 

 

TESTS:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C == loads(dumps(C)) 

True 

""" 

 

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

# Copyright (C) 2005 David Joyner <wdjoyner@gmail.com> 

# 2006 William Stein <wstein@gmail.com> 

# 

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

# version 2 or later (at your preference). 

# 

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

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

# python3 

from __future__ import division, print_function, absolute_import 

from six.moves import range 

from six import iteritems 

 

from sage.modules.module import Module 

from sage.categories.modules import Modules 

from copy import copy 

from sage.interfaces.all import gap 

from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF 

from sage.groups.perm_gps.permgroup import PermutationGroup 

from sage.matrix.matrix_space import MatrixSpace 

from sage.matrix.constructor import Matrix 

from sage.modules.free_module_element import vector 

from sage.arith.all import GCD, rising_factorial, binomial 

from sage.groups.all import SymmetricGroup 

from sage.misc.all import prod 

from sage.misc.functional import is_even 

from sage.rings.rational_field import QQ 

from sage.rings.integer_ring import ZZ 

from sage.structure.parent import Parent 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

from sage.rings.integer import Integer 

from sage.modules.free_module import VectorSpace 

from sage.misc.cachefunc import cached_method 

from sage.misc.superseded import deprecation, deprecated_function_alias 

from sage.misc.randstate import current_randstate 

from sage.misc.package import is_package_installed, PackageNotFoundError 

from .encoder import Encoder 

from .decoder import Decoder, DecodingError 

from sage.combinat.subset import Subsets 

from sage.categories.cartesian_product import cartesian_product 

# import compatible with py2 and py3 

 

from sage.categories.fields import Fields 

 

 

 

####################### coding theory functions ############################### 

 

 

def _dump_code_in_leon_format(C): 

r""" 

Writes a file in Sage's temp directory representing the code C, returning 

the absolute path to the file. 

 

This is the Sage translation of the GuavaToLeon command in Guava's 

codefun.gi file. 

 

INPUT: 

 

- ``C`` - a linear code (over GF(p), p < 11) 

 

OUTPUT: 

 

- Absolute path to the file written 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3); C 

[7, 4] Hamming Code over GF(2) 

sage: file_loc = sage.coding.linear_code._dump_code_in_leon_format(C) 

sage: f = open(file_loc); print(f.read()) 

LIBRARY code; 

code=seq(2,4,7,seq( 

1,0,0,0,0,1,1, 

0,1,0,0,1,0,1, 

0,0,1,0,1,1,0, 

0,0,0,1,1,1,1 

)); 

FINISH; 

sage: f.close() 

 

""" 

from sage.misc.temporary_file import tmp_filename 

F = C.base_ring() 

p = F.order() # must be prime and <11 

s = "LIBRARY code;\n"+"code=seq(%s,%s,%s,seq(\n"%(p,C.dimension(),C.length()) 

Gr = [str(r)[1:-1].replace(" ","") for r in C.generator_matrix().rows()] 

s += ",\n".join(Gr) + "\n));\nFINISH;" 

file_loc = tmp_filename() 

f = open(file_loc,"w") 

f.write(s) 

f.close() 

 

return file_loc 

 

code2leon = deprecated_function_alias(21165, _dump_code_in_leon_format) 

 

def wtdist_gap(Gmat, n, F): 

from sage.misc.superseded import deprecation 

deprecation(20565, "wtdist_gap is now deprecated. You should simply call AbstractLinearCode.weight_distribution instead.") 

G_gap = gap(Gmat) 

G = G_gap._matrix_(F) 

C = LinearCode(G) 

return C._spectrum_from_gap() 

 

def min_wt_vec_gap(Gmat, n, k, F, algorithm=None): 

from sage.misc.superseded import deprecation 

deprecation(20953, "min_wt_vec_gap is now deprecated. Please use AbstractLinearCode._minimum_weight_codeword instead.") 

G_gap = gap(Gmat) 

G = G_gap._matrix_(F) 

C = LinearCode(G) 

return C._minimum_weight_codeword(algorithm) 

 

def _explain_constructor(cl): 

r""" 

Internal function for use error messages when constructing encoders and decoders. 

 

EXAMPLES:: 

 

sage: from sage.coding.linear_code import _explain_constructor, LinearCodeSyndromeDecoder 

sage: cl = LinearCodeSyndromeDecoder 

sage: _explain_constructor(cl) 

"The constructor requires no arguments.\nIt takes the optional arguments ['maximum_error_weight'].\nSee the documentation of sage.coding.linear_code.LinearCodeSyndromeDecoder for more details." 

 

sage: from sage.coding.information_set_decoder import LinearCodeInformationSetDecoder 

sage: cl = LinearCodeInformationSetDecoder 

sage: _explain_constructor(cl) 

"The constructor requires the arguments ['number_errors'].\nIt takes the optional arguments ['algorithm'].\nIt accepts unspecified arguments as well.\nSee the documentation of sage.coding.information_set_decoder.LinearCodeInformationSetDecoder for more details." 

""" 

import inspect 

if inspect.isclass(cl): 

argspec = inspect.getargspec(cl.__init__) 

skip = 2 # skip the self and code arguments 

else: 

# Not a class, assume it's a factory function posing as a class 

argspec = inspect.getargspec(cl) 

skip = 1 # skip code argument 

if argspec.defaults: 

args = argspec.args[skip:-len(argspec.defaults)] 

kwargs = argspec.args[-len(argspec.defaults):] 

opts = "It takes the optional arguments {}.".format(kwargs) 

else: 

args = argspec.args[skip:] 

opts = "It takes no optional arguments." 

if args: 

reqs = "The constructor requires the arguments {}.".format(args) 

else: 

reqs = "The constructor requires no arguments." 

if argspec.varargs or argspec.keywords: 

var = "It accepts unspecified arguments as well.\n" 

else: 

var = "" 

return("{}\n{}\n{}See the documentation of {}.{} for more details."\ 

.format(reqs, opts, var, cl.__module__, cl.__name__)) 

 

 

class AbstractLinearCode(Module): 

""" 

Abstract class for linear codes. 

 

This class contains all methods that can be used on Linear Codes 

and on Linear Codes families. 

So, every Linear Code-related class should inherit from this abstract 

class. 

 

To implement a linear code, you need to: 

 

- inherit from AbstractLinearCode 

 

- call AbstractLinearCode ``__init__`` method in the subclass constructor. Example: 

``super(SubclassName, self).__init__(base_field, length, "EncoderName", "DecoderName")``. 

By doing that, your subclass will have its ``length`` parameter 

initialized and will be properly set as a member of the category framework. 

You need of course to complete the constructor by adding any additional parameter 

needed to describe properly the code defined in the subclass. 

 

- Add the following two lines on the class level:: 

 

_registered_encoders = {} 

_registered_decoders = {} 

 

 

- fill the dictionary of its encoders in ``sage.coding.__init__.py`` file. Example: 

I want to link the encoder ``MyEncoderClass`` to ``MyNewCodeClass`` 

under the name ``MyEncoderName``. 

All I need to do is to write this line in the ``__init__.py`` file: 

``MyNewCodeClass._registered_encoders["NameOfMyEncoder"] = MyEncoderClass`` and all instances of 

``MyNewCodeClass`` will be able to use instances of ``MyEncoderClass``. 

 

- fill the dictionary of its decoders in ``sage.coding.__init__`` file. Example: 

I want to link the encoder ``MyDecoderClass`` to ``MyNewCodeClass`` 

under the name ``MyDecoderName``. 

All I need to do is to write this line in the ``__init__.py`` file: 

``MyNewCodeClass._registered_decoders["NameOfMyDecoder"] = MyDecoderClass`` and all instances of 

``MyNewCodeClass`` will be able to use instances of ``MyDecoderClass``. 

 

 

As AbstractLinearCode is not designed to be implemented, it does not have any representation 

methods. You should implement ``_repr_`` and ``_latex_`` methods in the subclass. 

 

.. NOTE:: 

 

:class:`AbstractLinearCode` has generic implementations of the comparison methods ``__cmp__`` 

and ``__eq__`` which use the generator matrix and are quite slow. In subclasses you are 

encouraged to override these functions. 

 

.. WARNING:: 

 

The default encoder should always have `F^{k}` as message space, with `k` the dimension 

of the code and `F` is the base ring of the code. 

 

A lot of methods of the abstract class rely on the knowledge of a generator matrix. 

It is thus strongly recommended to set an encoder with a generator matrix implemented 

as a default encoder. 

""" 

_registered_encoders = {} 

_registered_decoders = {} 

 

def __init__(self, base_field, length, default_encoder_name, default_decoder_name): 

""" 

Initializes mandatory parameters that any linear code shares. 

 

This method only exists for inheritance purposes as it initializes 

parameters that need to be known by every linear code. The class 

:class:`sage.coding.linear_code.AbstractLinearCode` should never be 

directly instantiated. 

 

INPUT: 

 

- ``base_field`` -- the base field of ``self`` 

 

- ``length`` -- the length of ``self`` (a Python int or a Sage Integer, must be > 0) 

 

- ``default_encoder_name`` -- the name of the default encoder of ``self`` 

 

- ``default_decoder_name`` -- the name of the default decoder of ``self`` 

 

EXAMPLES: 

 

The following example demonstrates how to subclass `AbstractLinearCode` 

for representing a new family of codes. The example family is non-sensical:: 

 

sage: class MyCodeFamily(sage.coding.linear_code.AbstractLinearCode): 

....: def __init__(self, field, length, dimension, generator_matrix): 

....: sage.coding.linear_code.AbstractLinearCode.__init__(self,field, length, "GeneratorMatrix", "Syndrome") 

....: self._dimension = dimension 

....: self._generator_matrix = generator_matrix 

....: def generator_matrix(self): 

....: return self._generator_matrix 

....: def _repr_(self): 

....: return "[%d, %d] dummy code over GF(%s)" % (self.length(), self.dimension(), self.base_field().cardinality()) 

 

We now instantiate a member of our newly made code family:: 

 

sage: generator_matrix = matrix(GF(17), 5, 10, 

....: {(i,i):1 for i in range(5)}) 

sage: C = MyCodeFamily(GF(17), 10, 5, generator_matrix) 

 

We can check its existence and parameters:: 

 

sage: C 

[10, 5] dummy code over GF(17) 

 

We can check that it is truly a part of the framework category:: 

 

sage: C.parent() 

<class '__main__.MyCodeFamily_with_category'> 

sage: C.category() 

Category of facade finite dimensional vector spaces with basis over Finite Field of size 17 

 

And any method that works on linear codes works for our new dummy code:: 

 

sage: C.minimum_distance() 

1 

sage: C.is_self_orthogonal() 

False 

sage: print(C.divisor()) #long time 

1 

 

TESTS: 

 

If the length field is neither a Python int nor a Sage Integer, it will 

raise a exception:: 

 

sage: C = MyCodeFamily(GF(17), 10.0, 5, generator_matrix) 

Traceback (most recent call last): 

... 

ValueError: length must be a Python int or a Sage Integer 

 

If the length of the code is not a non-zero positive integer 

(See :trac:`21326`), it will raise an exception:: 

 

sage: empty_generator_matrix = Matrix(GF(17),0,1) 

sage: C = MyCodeFamily(GF(17), 0, 1, empty_generator_matrix) 

Traceback (most recent call last): 

... 

ValueError: length must be a non-zero positive integer 

 

If the name of the default decoder is not known by the class, it will raise 

a exception:: 

 

sage: class MyCodeFamily2(sage.coding.linear_code.AbstractLinearCode): 

....: def __init__(self, field, length, dimension, generator_matrix): 

....: sage.coding.linear_code.AbstractLinearCode.__init__(self,field, length, "GeneratorMatrix", "Fail") 

....: self._dimension = dimension 

....: self._generator_matrix = generator_matrix 

....: def generator_matrix(self): 

....: return self._generator_matrix 

....: def _repr_(self): 

....: return "[%d, %d] dummy code over GF(%s)" % (self.length(), self.dimension(), self.base_field().cardinality()) 

 

sage: C = MyCodeFamily2(GF(17), 10, 5, generator_matrix) 

Traceback (most recent call last): 

... 

ValueError: You must set a valid decoder as default decoder for this code, by filling in the dictionary of registered decoders 

 

If the name of the default encoder is not known by the class, it will raise 

an exception:: 

 

sage: class MyCodeFamily3(sage.coding.linear_code.AbstractLinearCode): 

....: def __init__(self, field, length, dimension, generator_matrix): 

....: sage.coding.linear_code.AbstractLinearCode.__init__(self,field, length, "Fail", "Syndrome") 

....: self._dimension = dimension 

....: self._generator_matrix = generator_matrix 

....: def generator_matrix(self): 

....: return self._generator_matrix 

....: def _repr_(self): 

....: return "[%d, %d] dummy code over GF(%s)" % (self.length(), self.dimension(), self.base_field().cardinality()) 

 

sage: C = MyCodeFamily3(GF(17), 10, 5, generator_matrix) 

Traceback (most recent call last): 

... 

ValueError: You must set a valid encoder as default encoder for this code, by filling in the dictionary of registered encoders 

 

A ring instead of a field:: 

 

sage: codes.LinearCode(IntegerModRing(4),matrix.ones(4)) 

Traceback (most recent call last): 

... 

ValueError: 'generator' must be defined on a field (not a ring) 

""" 

### Add here any generic encoder/decoder ### 

#This allows any class which inherits from AbstractLinearCode 

#to use generic decoders/encoders 

self._registered_encoders["Systematic"] = LinearCodeSystematicEncoder 

self._registered_decoders["Syndrome"] = LinearCodeSyndromeDecoder 

self._registered_decoders["NearestNeighbor"] = LinearCodeNearestNeighborDecoder 

from sage.coding.information_set_decoder import LinearCodeInformationSetDecoder 

self._registered_decoders["InformationSet"] = LinearCodeInformationSetDecoder 

 

if not isinstance(length, (int, Integer)): 

raise ValueError("length must be a Python int or a Sage Integer") 

if length <= 0: 

raise ValueError("length must be a non-zero positive integer") 

if not base_field.is_field(): 

raise ValueError("'base_field' must be a field (and {} is not one)".format(base_field)) 

if not default_encoder_name in self._registered_encoders: 

raise ValueError("You must set a valid encoder as default encoder for this code, by filling in the dictionary of registered encoders") 

if not default_decoder_name in self._registered_decoders: 

raise ValueError("You must set a valid decoder as default decoder for this code, by filling in the dictionary of registered decoders") 

 

self._length = Integer(length) 

self._default_decoder_name = default_decoder_name 

self._default_encoder_name = default_encoder_name 

cat = Modules(base_field).FiniteDimensional().WithBasis().Finite() 

facade_for = VectorSpace(base_field, self._length) 

self.Element = type(facade_for.an_element()) #for when we made this a non-facade parent 

Parent.__init__(self, base=base_field, facade=facade_for, category=cat) 

 

def _repr_(self): 

r""" 

Return an error message requiring to override ``_repr_`` in ``self``. 

 

As one has to implement specific representation methods (`_repr_` and `_latex_`) 

when writing a new code class which inherits from :class:`AbstractLinearCode`, 

the generic call to `_repr_` has to fail. 

 

EXAMPLES: 

 

This was taken from :trac:`20899` (and thus ensures this method fixes what was 

described in this ticket). 

 

We create a new code class, its dedicated encoder 

and set appropriate parameters:: 

 

sage: from sage.coding.linear_code import AbstractLinearCode 

sage: from sage.coding.encoder import Encoder 

sage: class MyCode(AbstractLinearCode): 

....: _registered_encoders = {} 

....: _registered_decoders = {} 

....: def __init__(self): 

....: super(MyCode, self).__init__(GF(5), 10, "Monkey", "Syndrome") 

....: self._dimension = 2 

 

sage: class MonkeyEncoder(Encoder): 

....: def __init__(self, C): 

....: super(MonkeyEncoder, self).__init__(C) 

....: @cached_method 

....: def generator_matrix(self): 

....: return matrix(GF(5), 2, 10, [ [1]*5 + [0]*5, [0]*5 + [1]*5 ]) 

sage: MyCode._registered_encoders["Monkey"] = MonkeyEncoder 

sage: MyCode._registered_decoders["Syndrome"] = codes.decoders.LinearCodeSyndromeDecoder 

 

We check we get a sensible error message while asking for a string 

representation of an instance of our new class: 

 

sage: C = MyCode() 

sage: C #random 

Traceback (most recent call last): 

... 

RuntimeError: Please override _repr_ in the implementation of <class '__main__.MyCode_with_category'> 

""" 

raise RuntimeError("Please override _repr_ in the implementation of {}".format(self.parent())) 

 

def _latex_(self): 

r""" 

Return an error message requiring to override ``_latex_`` in ``self``. 

 

As one has to implement specific representation methods (`_repr_` and `_latex_`) 

when writing a new code class which inherits from :class:`AbstractLinearCode`, 

the generic call to `_latex_` has to fail. 

 

EXAMPLES: 

 

This was taken from :trac:`20899` (and thus ensures this method fixes what was 

described in this ticket). 

 

We create a new code class, its dedicated encoder 

and set appropriate parameters:: 

 

sage: from sage.coding.linear_code import AbstractLinearCode 

sage: from sage.coding.encoder import Encoder 

sage: class MyCode(AbstractLinearCode): 

....: _registered_encoders = {} 

....: _registered_decoders = {} 

....: def __init__(self): 

....: super(MyCode, self).__init__(GF(5), 10, "Monkey", "Syndrome") 

....: self._dimension = 2 

 

sage: class MonkeyEncoder(Encoder): 

....: def __init__(self, C): 

....: super(MonkeyEncoder, self).__init__(C) 

....: @cached_method 

....: def generator_matrix(self): 

....: return matrix(GF(5), 2, 10, [ [1]*5 + [0]*5, [0]*5 + [1]*5 ]) 

sage: MyCode._registered_encoders["Monkey"] = MonkeyEncoder 

sage: MyCode._registered_decoders["Syndrome"] = codes.decoders.LinearCodeSyndromeDecoder 

 

We check we get a sensible error message while asking for a string 

representation of an instance of our new class: 

 

sage: C = MyCode() 

sage: latex(C) 

Traceback (most recent call last): 

... 

RuntimeError: Please override _latex_ in the implementation of <class '__main__.MyCode_with_category'> 

""" 

raise RuntimeError("Please override _latex_ in the implementation of {}".format(self.parent())) 

 

def _an_element_(self): 

r""" 

Return an element of the linear code. Currently, it simply returns 

the first row of the generator matrix. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.an_element() 

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

sage: C2 = C.cartesian_product(C) 

sage: C2.an_element() 

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

""" 

return self.gens()[0] 

 

def add_decoder(self, name, decoder): 

r""" 

Adds an decoder to the list of registered decoders of ``self``. 

 

.. NOTE:: 

 

This method only adds ``decoder`` to ``self``, and not to any member of the class 

of ``self``. To know how to add an :class:`sage.coding.decoder.Decoder`, please refer 

to the documentation of :class:`AbstractLinearCode`. 

 

INPUT: 

 

- ``name`` -- the string name for the decoder 

 

- ``decoder`` -- the class name of the decoder 

 

EXAMPLES: 

 

First of all, we create a (very basic) new decoder:: 

 

sage: class MyDecoder(sage.coding.decoder.Decoder): 

....: def __init__(self, code): 

....: super(MyDecoder, self).__init__(code) 

....: def _repr_(self): 

....: return "MyDecoder decoder with associated code %s" % self.code() 

 

We now create a new code:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

 

We can add our new decoder to the list of available decoders of C:: 

 

sage: C.add_decoder("MyDecoder", MyDecoder) 

sage: sorted(C.decoders_available()) 

['InformationSet', 'MyDecoder', 'NearestNeighbor', 'Syndrome'] 

 

We can verify that any new code will not know MyDecoder:: 

 

sage: C2 = codes.HammingCode(GF(2), 3) 

sage: sorted(C2.decoders_available()) 

['InformationSet', 'NearestNeighbor', 'Syndrome'] 

 

TESTS: 

 

It is impossible to use a name which is in the dictionary of available decoders:: 

 

sage: C.add_decoder("Syndrome", MyDecoder) 

Traceback (most recent call last): 

... 

ValueError: There is already a registered decoder with this name 

""" 

if self._registered_decoders == self.__class__._registered_decoders: 

self._registered_decoders = copy(self._registered_decoders) 

reg_dec = self._registered_decoders 

if name in reg_dec: 

raise ValueError("There is already a registered decoder with this name") 

reg_dec[name] = decoder 

else: 

if name in self._registered_decoders: 

raise ValueError("There is already a registered decoder with this name") 

reg_dec[name] = decoder 

 

def add_encoder(self, name, encoder): 

r""" 

Adds an encoder to the list of registered encoders of ``self``. 

 

.. NOTE:: 

 

This method only adds ``encoder`` to ``self``, and not to any member of the class 

of ``self``. To know how to add an :class:`sage.coding.encoder.Encoder`, please refer 

to the documentation of :class:`AbstractLinearCode`. 

 

INPUT: 

 

- ``name`` -- the string name for the encoder 

 

- ``encoder`` -- the class name of the encoder 

 

EXAMPLES: 

 

First of all, we create a (very basic) new encoder:: 

 

sage: class MyEncoder(sage.coding.encoder.Encoder): 

....: def __init__(self, code): 

....: super(MyEncoder, self).__init__(code) 

....: def _repr_(self): 

....: return "MyEncoder encoder with associated code %s" % self.code() 

 

We now create a new code:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

 

We can add our new encoder to the list of available encoders of C:: 

 

sage: C.add_encoder("MyEncoder", MyEncoder) 

sage: sorted(C.encoders_available()) 

['MyEncoder', 'ParityCheck', 'Systematic'] 

 

We can verify that any new code will not know MyEncoder:: 

 

sage: C2 = codes.HammingCode(GF(2), 3) 

sage: sorted(C2.encoders_available()) 

['ParityCheck', 'Systematic'] 

 

TESTS: 

 

It is impossible to use a name which is in the dictionary of available encoders:: 

 

sage: C.add_encoder("ParityCheck", MyEncoder) 

Traceback (most recent call last): 

... 

ValueError: There is already a registered encoder with this name 

""" 

if self._registered_encoders == self.__class__._registered_encoders: 

self._registered_encoders = copy(self._registered_encoders) 

reg_enc = self._registered_encoders 

if name in reg_enc: 

raise ValueError("There is already a registered encoder with this name") 

reg_enc[name] = encoder 

else: 

if name in self._registered_encoders: 

raise ValueError("There is already a registered encoder with this name") 

reg_enc[name] = encoder 

 

def automorphism_group_gens(self, equivalence="semilinear"): 

r""" 

Return generators of the automorphism group of ``self``. 

 

INPUT: 

 

- ``equivalence`` (optional) -- which defines the acting group, either 

 

* ``permutational`` 

 

* ``linear`` 

 

* ``semilinear`` 

 

OUTPUT: 

 

- generators of the automorphism group of ``self`` 

- the order of the automorphism group of ``self`` 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(4, 'z'), 3) 

sage: C.automorphism_group_gens() 

([((z, 1, z, z, z, z + 1, 1, z + 1, 1, 1, 1, z + 1, 1, z + 1, z + 1, z + 1, 1, z, 1, z + 1, z); (1,9,5,15,20,13,4)(2,8,12,7,10,14,16,3,21,18,19,6,11,17), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z + 1), 

((z, z, z, z, z, 1, z + 1, 1, z + 1, z + 1, z + 1, 1, z, z + 1, z, z, 1, z + 1, 1, 1, 1); (1,10,20,16,6,3,11,19,15,8,5,9,17,12,13)(4,7,21,14,18), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), 

((z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z); (), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z)], 

362880) 

sage: C.automorphism_group_gens(equivalence="linear") 

([((z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, 1, z + 1, z + 1, z + 1, z + 1, z, z + 1, z + 1, z + 1, z + 1, 1, z + 1, z + 1, z + 1); (1,3,17,20,12,16)(2,18)(4,11,21,9,14,10)(5,15,19)(6,8), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), 

((z + 1, z, 1, z + 1, z, z + 1, z + 1, z, 1, z + 1, z, z + 1, z, 1, z, z, z + 1, z, 1, 1, z); (1,15,18,20,13,7,21,17,9,11,5,14,19,4,2,16,10,6,8,3,12), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), 

((z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1); (), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z)], 

181440) 

sage: C.automorphism_group_gens(equivalence="permutational") 

([((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); (1,11)(3,10)(4,9)(5,7)(12,21)(14,20)(15,19)(16,17), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), ((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); (2,18)(3,19)(4,10)(5,16)(8,13)(9,14)(11,21)(15,20), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), ((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); (1,19)(3,17)(4,21)(5,20)(7,14)(9,12)(10,16)(11,15), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), ((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); (2,13)(3,14)(4,20)(5,11)(8,18)(9,19)(10,15)(16,21), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z)], 64) 

""" 

aut_group_can_label = self._canonize(equivalence) 

return aut_group_can_label.get_autom_gens(), \ 

aut_group_can_label.get_autom_order() 

 

def ambient_space(self): 

r""" 

Returns the ambient vector space of `self`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.ambient_space() 

Vector space of dimension 7 over Finite Field of size 2 

""" 

return VectorSpace(self.base_ring(),self.length()) 

 

def assmus_mattson_designs(self, t, mode=None): 

r""" 

Assmus and Mattson Theorem (section 8.4, page 303 of [HP2003]_): Let 

`A_0, A_1, ..., A_n` be the weights of the codewords in a binary 

linear `[n , k, d]` code `C`, and let `A_0^*, A_1^*, ..., A_n^*` be 

the weights of the codewords in its dual `[n, n-k, d^*]` code `C^*`. 

Fix a `t`, `0<t<d`, and let 

 

.. MATH:: 

 

s = |\{ i\ |\ A_i^* \not= 0, 0< i \leq n-t\}|. 

 

Assume `s\leq d-t`. 

 

1. If `A_i\not= 0` and `d\leq i\leq n` 

then `C_i = \{ c \in C\ |\ wt(c) = i\}` holds a simple t-design. 

 

2. If `A_i^*\not= 0` and `d*\leq i\leq n-t` then 

`C_i^* = \{ c \in C^*\ |\ wt(c) = i\}` holds a simple t-design. 

 

A block design is a pair `(X,B)`, where `X` is a non-empty finite set 

of `v>0` elements called points, and `B` is a non-empty finite 

multiset of size b whose elements are called blocks, such that each 

block is a non-empty finite multiset of `k` points. `A` design without 

repeated blocks is called a simple block design. If every subset of 

points of size `t` is contained in exactly `\lambda` blocks the block 

design is called a `t-(v,k,\lambda)` design (or simply a `t`-design 

when the parameters are not specified). When `\lambda=1` then the 

block design is called a `S(t,k,v)` Steiner system. 

 

In the Assmus and Mattson Theorem (1), `X` is the set `\{1,2,...,n\}` 

of coordinate locations and `B = \{supp(c)\ |\ c \in C_i\}` is the set 

of supports of the codewords of `C` of weight `i`. Therefore, the 

parameters of the `t`-design for `C_i` are 

 

:: 

 

t = given 

v = n 

k = i (k not to be confused with dim(C)) 

b = Ai 

lambda = b*binomial(k,t)/binomial(v,t) (by Theorem 8.1.6, 

p 294, in [HP2003]_) 

 

Setting the ``mode="verbose"`` option prints out the values of the 

parameters. 

 

The first example below means that the binary [24,12,8]-code C has 

the property that the (support of the) codewords of weight 8 (resp., 

12, 16) form a 5-design. Similarly for its dual code `C^*` (of course 

`C=C^*` in this case, so this info is extraneous). The test fails to 

produce 6-designs (ie, the hypotheses of the theorem fail to hold, 

not that the 6-designs definitely don't exist). The command 

assmus_mattson_designs(C,5,mode="verbose") returns the same value 

but prints out more detailed information. 

 

The second example below illustrates the blocks of the 5-(24, 8, 1) 

design (i.e., the S(5,8,24) Steiner system). 

 

EXAMPLES:: 

 

sage: C = codes.GolayCode(GF(2)) # example 1 

sage: C.assmus_mattson_designs(5) 

['weights from C: ', 

[8, 12, 16, 24], 

'designs from C: ', 

[[5, (24, 8, 1)], [5, (24, 12, 48)], [5, (24, 16, 78)], [5, (24, 24, 1)]], 

'weights from C*: ', 

[8, 12, 16], 

'designs from C*: ', 

[[5, (24, 8, 1)], [5, (24, 12, 48)], [5, (24, 16, 78)]]] 

sage: C.assmus_mattson_designs(6) 

0 

sage: X = range(24) # example 2 

sage: blocks = [c.support() for c in C if c.hamming_weight()==8]; len(blocks) # long time computation 

759 

""" 

C = self 

ans = [] 

G = C.generator_matrix() 

n = len(G.columns()) 

Cp = C.dual_code() 

wts = C.weight_distribution() 

d = min([i for i in range(1,len(wts)) if wts[i]!=0]) 

if t>=d: 

return 0 

nonzerowts = [i for i in range(len(wts)) if wts[i]!=0 and i<=n and i>=d] 

if mode=="verbose": 

for w in nonzerowts: 

print("The weight w={} codewords of C* form a t-(v,k,lambda) design, where\n \ 

t={}, v={}, k={}, lambda={}. \nThere are {} block of this design.".format(\ 

w,t,n,w,wts[w]*binomial(w,t)//binomial(n,t),wts[w])) 

wtsp = Cp.weight_distribution() 

dp = min([i for i in range(1,len(wtsp)) if wtsp[i]!=0]) 

nonzerowtsp = [i for i in range(len(wtsp)) if wtsp[i]!=0 and i<=n-t and i>=dp] 

s = len([i for i in range(1,n) if wtsp[i]!=0 and i<=n-t and i>0]) 

if mode=="verbose": 

for w in nonzerowtsp: 

print("The weight w={} codewords of C* form a t-(v,k,lambda) design, where\n \ 

t={}, v={}, k={}, lambda={}. \nThere are {} block of this design.".format(\ 

w,t,n,w,wts[w]*binomial(w,t)//binomial(n,t),wts[w])) 

if s<=d-t: 

des = [[t,(n,w,wts[w]*binomial(w,t)//binomial(n,t))] for w in nonzerowts] 

ans = ans + ["weights from C: ",nonzerowts,"designs from C: ",des] 

desp = [[t,(n,w,wtsp[w]*binomial(w,t)//binomial(n,t))] for w in nonzerowtsp] 

ans = ans + ["weights from C*: ",nonzerowtsp,"designs from C*: ",desp] 

return ans 

return 0 

 

def base_field(self): 

r""" 

Return the base field of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.base_field() 

Finite Field of size 2 

""" 

return self.base_ring() 

 

def basis(self): 

r""" 

Returns a basis of `self`. 

 

OUTPUT: 

 

- ``Sequence`` - an immutable sequence whose universe is ambient space of `self`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.basis() 

[ 

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

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

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

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

] 

sage: C.basis().universe() 

Vector space of dimension 7 over Finite Field of size 2 

""" 

gens = self.gens() 

from sage.structure.sequence import Sequence 

return Sequence(gens, universe=self.ambient_space(), check = False, immutable=True, cr=True) 

 

# S. Pancratz, 19 Jan 2010: In the doctests below, I removed the example 

# ``C.binomial_moment(3)``, which was also marked as ``#long``. This way, 

# we shorten the doctests time while still maintaining a zero and a 

# non-zero example. 

def binomial_moment(self, i): 

r""" 

Returns the i-th binomial moment of the `[n,k,d]_q`-code `C`: 

 

.. MATH:: 

 

B_i(C) = \sum_{S, |S|=i} \frac{q^{k_S}-1}{q-1} 

 

where `k_S` is the dimension of the shortened code `C_{J-S}`, 

`J=[1,2,...,n]`. (The normalized binomial moment is 

`b_i(C) = \binom(n,d+i)^{-1}B_{d+i}(C)`.) In other words, `C_{J-S}` 

is isomorphic to the subcode of C of codewords supported on S. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.binomial_moment(2) 

0 

sage: C.binomial_moment(4) # long time 

35 

 

.. warning:: 

 

This is slow. 

 

REFERENCE: 

 

.. [Du04] \I. Duursma, "Combinatorics of the two-variable zeta function", 

Finite fields and applications, 109-136, Lecture Notes in 

Comput. Sci., 2948, Springer, Berlin, 2004. 

""" 

n = self.length() 

k = self.dimension() 

d = self.minimum_distance() 

F = self.base_ring() 

q = F.order() 

J = range(1,n+1) 

Cp = self.dual_code() 

dp = Cp.minimum_distance() 

if i<d: 

return 0 

if i>n-dp and i<=n: 

return binomial(n,i)*(q**(i+k-n) -1)//(q-1) 

from sage.combinat.set_partition import SetPartitions 

P = SetPartitions(J,2).list() 

b = QQ(0) 

for p in P: 

p = list(p) 

S = p[0] 

if len(S)==n-i: 

C_S = self.shortened(S) 

k_S = C_S.dimension() 

b = b + (q**(k_S) -1)//(q-1) 

return b 

 

@cached_method 

def _canonize(self, equivalence): 

r""" 

Compute a canonical representative and the automorphism group 

under the action of the semimonomial transformation group. 

 

INPUT: 

 

- ``equivalence`` -- which defines the acting group, either 

 

* ``permutational`` 

 

* ``linear`` 

 

* ``semilinear`` 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(4, 'z'), 3) 

sage: aut_group_can_label = C._canonize("semilinear") 

sage: C_iso = LinearCode(aut_group_can_label.get_transporter()*C.generator_matrix()) 

sage: C_iso == aut_group_can_label.get_canonical_form() 

True 

sage: aut_group_can_label.get_autom_gens() 

[((z, 1, z + 1, z, 1, 1, z, 1, z + 1, 1, 1, z, 1, z + 1, z, 1, z, 1, z + 1, z + 1, 1); (1,10,8,21,3,20,2,4,6,18,14,9,12,16,17)(5,15,13,7,19), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z), 

((z + 1, z, z, z + 1, 1, 1, 1, z + 1, z + 1, z, 1, z, z + 1, 1, 1, z + 1, z + 1, 1, 1, z, z); (1,18,17,5,16,3,10,11,8,21,7,12,9,4)(2,19,15,14,6,20,13), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z + 1), 

((z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z); (), Ring endomorphism of Finite Field in z of size 2^2 

Defn: z |--> z)] 

""" 

from sage.coding.codecan.autgroup_can_label import LinearCodeAutGroupCanLabel 

return LinearCodeAutGroupCanLabel(self, algorithm_type=equivalence) 

 

def canonical_representative(self, equivalence="semilinear"): 

r""" 

Compute a canonical orbit representative under the action of the 

semimonomial transformation group. 

 

See :mod:`sage.coding.codecan.autgroup_can_label` 

for more details, for example if you would like to compute 

a canonical form under some more restrictive notion of equivalence, 

i.e. if you would like to restrict the permutation group 

to a Young subgroup. 

 

INPUT: 

 

- ``equivalence`` (optional) -- which defines the acting group, either 

 

* ``permutational`` 

 

* ``linear`` 

 

* ``semilinear`` 

 

OUTPUT: 

 

- a canonical representative of ``self`` 

- a semimonomial transformation mapping ``self`` onto its representative 

 

EXAMPLES:: 

 

sage: F.<z> = GF(4) 

sage: C = codes.HammingCode(F, 3) 

sage: CanRep, transp = C.canonical_representative() 

 

Check that the transporter element is correct:: 

 

sage: LinearCode(transp*C.generator_matrix()) == CanRep 

True 

 

Check if an equivalent code has the same canonical representative:: 

 

sage: f = F.hom([z**2]) 

sage: C_iso = LinearCode(C.generator_matrix().apply_map(f)) 

sage: CanRep_iso, _ = C_iso.canonical_representative() 

sage: CanRep_iso == CanRep 

True 

 

Since applying the Frobenius automorphism could be extended to an 

automorphism of `C`, the following must also yield ``True``:: 

 

sage: CanRep1, _ = C.canonical_representative("linear") 

sage: CanRep2, _ = C_iso.canonical_representative("linear") 

sage: CanRep2 == CanRep1 

True 

 

TESTS: 

 

Check that interrupting this does not segfault 

(see :trac:`21651`):: 

 

sage: C = LinearCode(random_matrix(GF(47), 25, 35)) 

sage: alarm(0.5); C.canonical_representative() 

Traceback (most recent call last): 

... 

AlarmInterrupt 

""" 

aut_group_can_label = self._canonize(equivalence) 

return aut_group_can_label.get_canonical_form(), \ 

aut_group_can_label.get_transporter() 

 

def __contains__(self, v): 

r""" 

Returns True if `v` can be coerced into `self`. Otherwise, returns False. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: vector((1, 0, 0, 0, 0, 1, 1)) in C # indirect doctest 

True 

sage: vector((1, 0, 0, 0, 2, 1, 1)) in C # indirect doctest 

True 

sage: vector((1, 0, 0, 0, 0, 1/2, 1)) in C # indirect doctest 

False 

""" 

if not v in self.ambient_space() or len(v) != self.length(): 

return False 

return self.syndrome(v) == 0 

 

def characteristic(self): 

r""" 

Returns the characteristic of the base ring of `self`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.characteristic() 

2 

""" 

return (self.base_ring()).characteristic() 

 

def characteristic_polynomial(self): 

r""" 

Returns the characteristic polynomial of a linear code, as defined in 

[Lin1999]_. 

 

EXAMPLES:: 

 

sage: C = codes.GolayCode(GF(2)) 

sage: C.characteristic_polynomial() 

-4/3*x^3 + 64*x^2 - 2816/3*x + 4096 

""" 

R = PolynomialRing(QQ,"x") 

x = R.gen() 

C = self 

Cd = C.dual_code() 

Sd = Cd.support() 

k = C.dimension() 

n = C.length() 

q = (C.base_ring()).order() 

return q**(n-k)*prod([1-x/j for j in Sd if j>0]) 

 

def chinen_polynomial(self): 

""" 

Returns the Chinen zeta polynomial of the code. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.chinen_polynomial() # long time 

1/5*(2*sqrt(2)*t^3 + 2*sqrt(2)*t^2 + 2*t^2 + sqrt(2)*t + 2*t + 1)/(sqrt(2) + 1) 

sage: C = codes.GolayCode(GF(3), False) 

sage: C.chinen_polynomial() # long time 

1/7*(3*sqrt(3)*t^3 + 3*sqrt(3)*t^2 + 3*t^2 + sqrt(3)*t + 3*t + 1)/(sqrt(3) + 1) 

 

This last output agrees with the corresponding example given in 

Chinen's paper below. 

 

REFERENCES: 

 

- Chinen, K. "An abundance of invariant polynomials satisfying the 

Riemann hypothesis", April 2007 preprint. 

""" 

from sage.functions.all import sqrt 

C = self 

n = C.length() 

RT = PolynomialRing(QQ,2,"Ts") 

T,s = RT.fraction_field().gens() 

t = PolynomialRing(QQ,"t").gen() 

Cd = C.dual_code() 

k = C.dimension() 

q = (C.base_ring()).characteristic() 

d = C.minimum_distance() 

dperp = Cd.minimum_distance() 

if dperp > d: 

P = RT(C.zeta_polynomial()) 

# Sage does not find dealing with sqrt(int) *as an algebraic object* 

# an easy thing to do. Some tricky gymnastics are used to 

# make Sage deal with objects over QQ(sqrt(q)) nicely. 

if is_even(n): 

Pd = q**(k-n//2) * RT(Cd.zeta_polynomial()) * T**(dperp - d) 

else: 

Pd = s * q**(k-(n+1)//2) * RT(Cd.zeta_polynomial()) * T**(dperp - d) 

CP = P+Pd 

f = CP/CP(1,s) 

return f(t,sqrt(q)) 

if dperp < d: 

P = RT(C.zeta_polynomial())*T**(d - dperp) 

if is_even(n): 

Pd = q**(k-n/2)*RT(Cd.zeta_polynomial()) 

if not(is_even(n)): 

Pd = s*q**(k-(n+1)/2)*RT(Cd.zeta_polynomial()) 

CP = P+Pd 

f = CP/CP(1,s) 

return f(t,sqrt(q)) 

if dperp == d: 

P = RT(C.zeta_polynomial()) 

if is_even(n): 

Pd = q**(k-n/2)*RT(Cd.zeta_polynomial()) 

if not(is_even(n)): 

Pd = s*q**(k-(n+1)/2)*RT(Cd.zeta_polynomial()) 

CP = P+Pd 

f = CP/CP(1,s) 

return f(t,sqrt(q)) 

 

@cached_method 

def parity_check_matrix(self): 

r""" 

Returns the parity check matrix of ``self``. 

 

The parity check matrix of a linear code `C` corresponds to the 

generator matrix of the dual code of `C`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: Cperp = C.dual_code() 

sage: C; Cperp 

[7, 4] Hamming Code over GF(2) 

[7, 3] linear code over GF(2) 

sage: C.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 1 1 0] 

[0 0 0 1 1 1 1] 

sage: C.parity_check_matrix() 

[1 0 1 0 1 0 1] 

[0 1 1 0 0 1 1] 

[0 0 0 1 1 1 1] 

sage: Cperp.parity_check_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 1 1 0] 

[0 0 0 1 1 1 1] 

sage: Cperp.generator_matrix() 

[1 0 1 0 1 0 1] 

[0 1 1 0 0 1 1] 

[0 0 0 1 1 1 1] 

""" 

G = self.generator_matrix() 

H = G.right_kernel() 

M = H.basis_matrix() 

M.set_immutable() 

return M 

 

@cached_method 

def covering_radius(self): 

r""" 

Return the minimal integer `r` such that any element in the ambient space of ``self`` has distance at most `r` to a codeword of ``self``. 

 

This method requires the optional GAP package Guava. 

 

If the covering radius a code equals its minimum distance, then the code is called perfect. 

 

.. NOTE:: 

 

This method is currently not implemented on codes over base fields 

of cardinality greater than 256 due to limitations in the underlying 

algorithm of GAP. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 5) 

sage: C.covering_radius() # optional - gap_packages (Guava package) 

1 

 

sage: C = codes.random_linear_code(GF(263), 5, 1) 

sage: C.covering_radius() # optional - gap_packages (Guava package) 

Traceback (most recent call last): 

... 

NotImplementedError: the GAP algorithm that Sage is using is limited to computing with fields of size at most 256 

""" 

if not is_package_installed('gap_packages'): 

raise PackageNotFoundError('gap_packages') 

gap.load_package("guava") 

F = self.base_ring() 

if F.cardinality() > 256: 

raise NotImplementedError("the GAP algorithm that Sage is using " 

"is limited to computing with fields " 

"of size at most 256") 

gapG = gap(self.generator_matrix()) 

C = gapG.GeneratorMatCode(gap(F)) 

r = C.CoveringRadius() 

try: 

return ZZ(r) 

except TypeError: 

raise RuntimeError("the covering radius of this code cannot be computed by Guava") 

 

def decode_to_code(self, word, decoder_name=None, *args, **kwargs): 

r""" 

Corrects the errors in ``word`` and returns a codeword. 

 

INPUT: 

 

- ``word`` -- a vector of the same length as ``self`` over 

the base field of ``self`` 

 

- ``decoder_name`` -- (default: ``None``) Name of the decoder which will be used 

to decode ``word``. The default decoder of ``self`` will be used if 

default value is kept. 

 

- ``args``, ``kwargs`` -- all additional arguments are forwarded to :meth:`decoder` 

 

OUTPUT: 

 

- A vector of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0)) 

sage: w_err = word + vector(GF(2), (1, 0, 0, 0, 0, 0, 0)) 

sage: C.decode_to_code(w_err) 

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

 

It is possible to manually choose the decoder amongst the list of the available ones:: 

 

sage: sorted(C.decoders_available()) 

['InformationSet', 'NearestNeighbor', 'Syndrome'] 

sage: C.decode_to_code(w_err, 'NearestNeighbor') 

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

""" 

D = self.decoder(decoder_name, *args, **kwargs) 

return D.decode_to_code(word) 

 

def decode_to_message(self, word, decoder_name=None, *args, **kwargs): 

r""" 

Correct the errors in word and decodes it to the message space. 

 

INPUT: 

 

- ``word`` -- a vector of the same length as ``self`` over the 

base field of ``self`` 

 

- ``decoder_name`` -- (default: ``None``) Name of the decoder which will be used 

to decode ``word``. The default decoder of ``self`` will be used if 

default value is kept. 

 

- ``args``, ``kwargs`` -- all additional arguments are forwarded to :meth:`decoder` 

 

OUTPUT: 

 

- A vector of the message space of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0)) 

sage: C.decode_to_message(word) 

(0, 1, 1, 0) 

 

It is possible to manually choose the decoder amongst the list of the available ones:: 

 

sage: sorted(C.decoders_available()) 

['InformationSet', 'NearestNeighbor', 'Syndrome'] 

sage: C.decode_to_message(word, 'NearestNeighbor') 

(0, 1, 1, 0) 

""" 

return self.unencode(self.decode_to_code(word, decoder_name, *args, **kwargs), **kwargs) 

 

@cached_method 

def decoder(self, decoder_name=None, *args, **kwargs): 

r""" 

Return a decoder of ``self``. 

 

INPUT: 

 

- ``decoder_name`` -- (default: ``None``) name of the decoder which will be 

returned. The default decoder of ``self`` will be used if 

default value is kept. 

 

- ``args``, ``kwargs`` -- all additional arguments will be forwarded to the constructor of the decoder 

that will be returned by this method 

 

OUTPUT: 

 

- a decoder object 

 

Besides creating the decoder and returning it, this method also stores 

the decoder in a cache. With this behaviour, each decoder will be created 

at most one time for ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.decoder() 

Syndrome decoder for [7, 4] linear code over GF(2) handling errors of weight up to 1 

 

 

If the name of a decoder which is not known by ``self`` is passed, 

an exception will be raised:: 

 

sage: sorted(C.decoders_available()) 

['InformationSet', 'NearestNeighbor', 'Syndrome'] 

sage: C.decoder('Try') 

Traceback (most recent call last): 

... 

ValueError: There is no Decoder named 'Try'. The known Decoders are: ['InformationSet', 'NearestNeighbor', 'Syndrome'] 

 

Some decoders take extra arguments. If the user forgets to supply these, 

the error message attempts to be helpful:: 

 

sage: C.decoder('InformationSet') 

Traceback (most recent call last): 

... 

ValueError: Constructing the InformationSet decoder failed, possibly due to missing or incorrect parameters. 

The constructor requires the arguments ['number_errors']. 

It takes the optional arguments ['algorithm']. 

It accepts unspecified arguments as well. 

See the documentation of sage.coding.information_set_decoder.LinearCodeInformationSetDecoder for more details. 

 

""" 

if decoder_name is None: 

decoder_name = self._default_decoder_name 

if decoder_name in self._registered_decoders: 

decClass = self._registered_decoders[decoder_name] 

try: 

return decClass(self, *args, **kwargs) 

except TypeError: 

raise ValueError( 

"Constructing the {0} decoder failed, possibly due " 

"to missing or incorrect parameters.\n{1}".format( 

decoder_name, _explain_constructor(decClass))) 

else: 

raise ValueError( 

"There is no Decoder named '{0}'. The known Decoders are: " 

"{1}".format(decoder_name, self.decoders_available())) 

 

def decoders_available(self, classes=False): 

r""" 

Returns a list of the available decoders' names for ``self``. 

 

INPUT: 

 

- ``classes`` -- (default: ``False``) if ``classes`` is set to ``True``, 

return instead a ``dict`` mapping available decoder name to the 

associated decoder class. 

 

OUTPUT: a list of strings, or a `dict` mapping strings to classes. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.decoders_available() 

['InformationSet', 'NearestNeighbor', 'Syndrome'] 

 

sage: dictionary = C.decoders_available(True) 

sage: sorted(dictionary.keys()) 

['InformationSet', 'NearestNeighbor', 'Syndrome'] 

sage: dictionary['NearestNeighbor'] 

<class 'sage.coding.linear_code.LinearCodeNearestNeighborDecoder'> 

""" 

if classes: 

return copy(self._registered_decoders) 

 

return sorted(self._registered_decoders) 

 

def divisor(self): 

r""" 

Returns the greatest common divisor of the weights of the nonzero codewords. 

 

EXAMPLES:: 

 

sage: C = codes.GolayCode(GF(2)) 

sage: C.divisor() # Type II self-dual 

4 

sage: C = codes.QuadraticResidueCodeEvenPair(17,GF(2))[0] 

sage: C.divisor() 

2 

""" 

C = self 

A = C.weight_distribution() 

n = C.length() 

V = VectorSpace(QQ,n+1) 

S = V(A).nonzero_positions() 

S0 = [S[i] for i in range(1,len(S))] 

if len(S)>1: return GCD(S0) 

return 1 

 

def is_projective(self): 

r""" 

Test whether the code is projective. 

 

A linear code `C` over a field is called *projective* when its dual `Cd` 

has minimum weight `\geq 3`, i.e. when no two coordinate positions of 

`C` are linearly independent (cf. definition 3 from [BS2011]_ or 9.8.1 from 

[BH12]_). 

 

EXAMPLES:: 

 

sage: C = codes.GolayCode(GF(2), False) 

sage: C.is_projective() 

True 

sage: C.dual_code().minimum_distance() 

8 

 

A non-projective code:: 

 

sage: C = codes.LinearCode(matrix(GF(2),[[1,0,1],[1,1,1]])) 

sage: C.is_projective() 

False 

""" 

M = self.generator_matrix().transpose() 

R = self.base_field() 

 

def projectivize(row): 

if not row.is_zero(): 

for i in range(len(row)): 

if row[i]: 

break 

row = ~(row[i]) * row 

row.set_immutable() 

return row 

 

rows = set() 

for row in M.rows(): 

row = projectivize(row) 

if row in rows: 

return False 

rows.add(row) 

 

return True 

 

def dual_code(self): 

r""" 

Returns the dual code `C^{\perp}` of the code `C`, 

 

.. MATH:: 

 

C^{\perp} = \{ v \in V\ |\ v\cdot c = 0,\ \forall c \in C \}. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.dual_code() 

[7, 3] linear code over GF(2) 

sage: C = codes.HammingCode(GF(4, 'a'), 3) 

sage: C.dual_code() 

[21, 3] linear code over GF(4) 

""" 

return LinearCode(self.parity_check_matrix()) 

 

def dimension(self): 

r""" 

Returns the dimension of this code. 

 

EXAMPLES:: 

 

sage: G = matrix(GF(2),[[1,0,0],[1,1,0]]) 

sage: C = LinearCode(G) 

sage: C.dimension() 

2 

 

TESTS: 

 

Check that :trac:`21156` is fixed:: 

 

sage: from sage.coding.linear_code import AbstractLinearCode 

sage: from sage.coding.encoder import Encoder 

sage: class MonkeyCode(AbstractLinearCode): 

....: _registered_encoders = {} 

....: _registered_decoders = {} 

....: def __init__(self): 

....: super(MonkeyCode, self).__init__(GF(5), 10, "Monkey", "Syndrome") 

....: 

sage: class MonkeyEncoder(Encoder): 

....: def __init__(self, code): 

....: super(MonkeyEncoder, self).__init__(C) 

....: @cached_method 

....: def generator_matrix(self): 

....: G = identity_matrix(GF(5), 5).augment(matrix(GF(5), 5, 7)) 

....: return G 

....: 

sage: MonkeyCode._registered_encoders["Monkey"] = MonkeyEncoder 

sage: C = MonkeyCode() 

sage: C.dimension() 

5 

""" 

try: 

return self._dimension 

except AttributeError: 

dimension = self.generator_matrix().nrows() 

self._dimension = dimension 

return self._dimension 

 

def direct_sum(self, other): 

""" 

Returns the code given by the direct sum of the codes ``self`` and 

``other``, which must be linear codes defined over the same base ring. 

 

EXAMPLES:: 

 

sage: C1 = codes.HammingCode(GF(2), 3) 

sage: C2 = C1.direct_sum(C1); C2 

[14, 8] linear code over GF(2) 

sage: C3 = C1.direct_sum(C2); C3 

[21, 12] linear code over GF(2) 

""" 

C1 = self; C2 = other 

G1 = C1.generator_matrix() 

G2 = C2.generator_matrix() 

F = C1.base_ring() 

n1 = len(G1.columns()) 

k1 = len(G1.rows()) 

n2 = len(G2.columns()) 

k2 = len(G2.rows()) 

MS1 = MatrixSpace(F,k2,n1) 

MS2 = MatrixSpace(F,k1,n2) 

Z1 = MS1(0) 

Z2 = MS2(0) 

top = G1.augment(Z2) 

bottom = Z1.augment(G2) 

G = top.stack(bottom) 

return LinearCode(G) 

 

def __eq__(self, right): 

""" 

Checks if ``self`` is equal to ``right``. 

 

EXAMPLES:: 

 

sage: C1 = codes.HammingCode(GF(2), 3) 

sage: C2 = codes.HammingCode(GF(2), 3) 

sage: C1 == C2 

True 

 

TESTS: 

 

We check that :trac:`16644` is fixed:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C == ZZ 

False 

""" 

if not (isinstance(right, LinearCode)\ 

and self.length() == right.length()\ 

and self.dimension() == right.dimension()\ 

and self.base_ring() == right.base_ring()): 

return False 

Ks = self.parity_check_matrix().right_kernel() 

rbas = right.gens() 

if not all(c in Ks for c in rbas): 

return False 

Kr = right.parity_check_matrix().right_kernel() 

sbas = self.gens() 

if not all(c in Kr for c in sbas): 

return False 

return True 

 

def __ne__(self, other): 

r""" 

Tests inequality of ``self`` and ``other``. 

 

This is a generic implementation, which returns the inverse of ``__eq__`` for self. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C1 = LinearCode(G) 

sage: C2 = LinearCode(G) 

sage: C1 != C2 

False 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,1,1]]) 

sage: C2 = LinearCode(G) 

sage: C1 != C2 

True 

""" 

return not self == other 

 

def encode(self, word, encoder_name=None, *args, **kwargs): 

r""" 

Transforms an element of a message space into a codeword. 

 

INPUT: 

 

- ``word`` -- a vector of a message space of the code. 

 

- ``encoder_name`` -- (default: ``None``) Name of the encoder which will be used 

to encode ``word``. The default encoder of ``self`` will be used if 

default value is kept. 

 

- ``args``, ``kwargs`` -- all additional arguments are forwarded to the construction of the 

encoder that is used. 

 

.. NOTE:: 

 

The default encoder always has `F^{k}` as message space, with `k` the dimension 

of ``self`` and `F` the base ring of ``self``. 

 

One can use the following shortcut to encode a word :: 

 

C(word) 

 

OUTPUT: 

 

- a vector of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: word = vector((0, 1, 1, 0)) 

sage: C.encode(word) 

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

sage: C(word) 

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

 

It is possible to manually choose the encoder amongst the list of the available ones:: 

 

sage: sorted(C.encoders_available()) 

['GeneratorMatrix', 'Systematic'] 

sage: word = vector((0, 1, 1, 0)) 

sage: C.encode(word, 'GeneratorMatrix') 

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

""" 

E = self.encoder(encoder_name, *args, **kwargs) 

return E.encode(word) 

 

def __call__(self, m): 

r""" 

Returns either ``m`` if it is a codeword or ``self.encode(m)`` 

if it is an element of the message space of the encoder used by 

``encode``. 

 

INPUT: 

 

- ``m`` -- a vector whose length equals to code's length or an element 

of the message space used by ``encode`` 

 

- ``**kwargs`` -- extra arguments are forwarded to ``encode`` 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: word = vector((0, 1, 1, 0)) 

sage: C(word) 

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

 

sage: c = C.random_element() 

sage: C(c) == c 

True 

 

TESTS: 

 

If one passes a vector which belongs to the ambient space, it has to be a codeword. 

Otherwise, an exception is raised:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: word = vector((0, 1, 1, 0, 0, 1, 0)) 

sage: C(word) 

Traceback (most recent call last): 

... 

ValueError: If the input is a vector which belongs to the ambient space, it has to be a codeword 

""" 

if m in self.ambient_space(): 

if m in self: 

return m 

else: 

raise ValueError("If the input is a vector which belongs to the ambient space, it has to be a codeword") 

else: 

return self.encode(m) 

 

@cached_method 

def encoder(self, encoder_name=None, *args, **kwargs): 

r""" 

Returns an encoder of ``self``. 

 

The returned encoder provided by this method is cached. 

 

This methods creates a new instance of the encoder subclass designated by ``encoder_name``. 

While it is also possible to do the same by directly calling the subclass' constructor, 

it is strongly advised to use this method to take advantage of the caching mechanism. 

 

INPUT: 

 

- ``encoder_name`` -- (default: ``None``) name of the encoder which will be 

returned. The default encoder of ``self`` will be used if 

default value is kept. 

 

- ``args``, ``kwargs`` -- all additional arguments are forwarded to the constructor of the encoder 

this method will return. 

 

OUTPUT: 

 

- an Encoder object. 

 

.. NOTE:: 

 

The default encoder always has `F^{k}` as message space, with `k` the dimension 

of ``self`` and `F` the base ring of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.encoder() 

Generator matrix-based encoder for [7, 4] linear code over GF(2) 

 

We check that the returned encoder is cached:: 

 

sage: C.encoder.is_in_cache() 

True 

 

If the name of an encoder which is not known by ``self`` is passed, 

an exception will be raised:: 

 

sage: sorted(C.encoders_available()) 

['GeneratorMatrix', 'Systematic'] 

sage: C.encoder('NonExistingEncoder') 

Traceback (most recent call last): 

... 

ValueError: There is no Encoder named 'NonExistingEncoder'. The known Encoders are: ['GeneratorMatrix', 'Systematic'] 

 

Some encoders take extra arguments. If the user incorrectly supplies 

these, the error message attempts to be helpful:: 

 

sage: C.encoder('Systematic', strange_parameter=True) 

Traceback (most recent call last): 

... 

ValueError: Constructing the Systematic encoder failed, possibly due to missing or incorrect parameters. 

The constructor requires no arguments. 

It takes the optional arguments ['systematic_positions']. 

See the documentation of sage.coding.linear_code.LinearCodeSystematicEncoder for more details. 

""" 

if encoder_name is None: 

encoder_name = self._default_encoder_name 

if encoder_name in self._registered_encoders: 

encClass = self._registered_encoders[encoder_name] 

try: 

return encClass(self, *args, **kwargs) 

except TypeError: 

raise ValueError( 

"Constructing the {0} encoder failed, possibly due " 

"to missing or incorrect parameters.\n{1}".format( 

encoder_name, _explain_constructor(encClass))) 

else: 

raise ValueError( 

"There is no Encoder named '{0}'. The known Encoders are: " 

"{1}".format(encoder_name, self.encoders_available())) 

 

def encoders_available(self, classes=False): 

r""" 

Returns a list of the available encoders' names for ``self``. 

 

INPUT: 

 

- ``classes`` -- (default: ``False``) if ``classes`` is set to ``True``, 

return instead a ``dict`` mapping available encoder name to the 

associated encoder class. 

 

OUTPUT: a list of strings, or a `dict` mapping strings to classes. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.encoders_available() 

['GeneratorMatrix', 'Systematic'] 

sage: dictionary = C.encoders_available(True) 

sage: sorted(dictionary.items()) 

[('GeneratorMatrix', <class 'sage.coding.linear_code.LinearCodeGeneratorMatrixEncoder'>), 

('Systematic', <class 'sage.coding.linear_code.LinearCodeSystematicEncoder'>)] 

""" 

if classes: 

return copy(self._registered_encoders) 

 

return sorted(self._registered_encoders) 

 

def extended_code(self): 

r""" 

Returns `self` as an extended code. 

 

See documentation of :class:`sage.coding.extended_code.ExtendedCode` 

for details. 

EXAMPLES:: 

 

 

sage: C = codes.HammingCode(GF(4,'a'), 3) 

sage: C 

[21, 18] Hamming Code over GF(4) 

sage: Cx = C.extended_code() 

sage: Cx 

Extension of [21, 18] Hamming Code over GF(4) 

""" 

from .extended_code import ExtendedCode 

return ExtendedCode(self) 

 

def galois_closure(self, F0): 

r""" 

If ``self`` is a linear code defined over `F` and `F_0` is a subfield 

with Galois group `G = Gal(F/F_0)` then this returns the `G`-module 

`C^-` containing `C`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(4,'a'), 3) 

sage: Cc = C.galois_closure(GF(2)) 

sage: C; Cc 

[21, 18] Hamming Code over GF(4) 

[21, 20] linear code over GF(4) 

sage: c = C.basis()[2] 

sage: V = VectorSpace(GF(4,'a'),21) 

sage: c2 = V([x^2 for x in c.list()]) 

sage: c2 in C 

False 

sage: c2 in Cc 

True 

""" 

G = self.generator_matrix() 

F = self.base_ring() 

q = F.order() 

q0 = F0.order() 

a = q.log(q0) # test if F/F0 is a field extension 

if not isinstance(a, Integer): 

raise ValueError("Base field must be an extension of given field %s"%F0) 

n = len(G.columns()) 

k = len(G.rows()) 

G0 = [[x**q0 for x in g.list()] for g in G.rows()] 

G1 = [[x for x in g.list()] for g in G.rows()] 

G2 = G0+G1 

MS = MatrixSpace(F,2*k,n) 

G3 = MS(G2) 

r = G3.rank() 

MS = MatrixSpace(F,r,n) 

Grref = G3.echelon_form() 

G = MS([Grref.row(i) for i in range(r)]) 

return LinearCode(G) 

 

def __getitem__(self, i): 

r""" 

Returns the `i`-th codeword of this code. 

 

The implementation of this depends on the implementation of the 

:meth:`.__iter__` method. 

 

The implementation is as follows. Suppose that: 

 

- the primitive element of the base_ring of this code is `a`, 

- the prime subfield is `p`, 

- the field has order `p^m`, 

- the code has dimension `k`, 

- and the generator matrix is `G`. 

 

Then the :meth:`.__iter__` method returns the elements in this order: 

 

1. first, the following ordered list is returned: 

``[i*a^0 * G[0] for i in range(p)]`` 

2. Next, the following ordered list is returned: 

``[i*a^0 * G[0] + a^1*G[0] for i in range(p)]`` 

3. This continues till we get 

``[(i*a^0 +(p-1)*a^1 +...+ (p-1)*a^(m-1))*G[0] for i in range(p)]`` 

4. Then, we move to G[1]: 

``[i*a^0 * G[0] + a^0*G[1] for i in range(p)]``, 

and so on. 

Hence the `i`-th element can be obtained by the p-adic expansion 

of `i` as ``[i_0, i_1, ...,i_{m-1}, i_m, i_{m+1}, ..., i_{km-1}].`` 

The element that is generated is: 

 

.. MATH:: 

 

\begin{aligned} 

& (i_0 a^0 + i_1 a^1 + \cdots + i_{m-1} a^{m-1}) G[0] + \\ 

& (i_m a^0 + i_{m+1} a^1 + \cdots + i_{2m-1} a^{m-1}) G[1] + \\ 

& \vdots\\ 

& (i_{(k-1)m} a^0 + \cdots + i_{km-1} a^{m-1}) G[k-1] 

\end{aligned} 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C[24] 

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

sage: C[24] == C.list()[24] 

True 

 

TESTS:: 

 

sage: C = random_matrix(GF(25,'a'), 2, 7).row_space() 

sage: C = LinearCode(C.basis_matrix()) 

sage: Clist = C.list() 

sage: all([C[i]==Clist[i] for i in range(len(C))]) 

True 

 

Check that only the indices less than the size of the code are 

allowed:: 

 

sage: C[25**2] 

Traceback (most recent call last): 

... 

IndexError: The value of the index 'i' (=625) must be between 

0 and 'q^k -1' (=624), inclusive, where 'q' is the size of the 

base field and 'k' is the dimension of the code. 

 

Check that codewords are immutable. See :trac:`16338`:: 

 

sage: C[0].is_immutable() 

True 

 

""" 

# IMPORTANT: If the __iter__() function implementation is changed 

# then the implementation here must also be changed so that 

# list(self)[i] and self[i] both return the same element. 

 

F = self.base_ring() 

maxindex = F.order()**self.dimension()-1 

if i < 0 or i > maxindex: 

raise IndexError("The value of the index 'i' (={}) must be between " 

"0 and 'q^k -1' (={}), inclusive, where 'q' is " 

"the size of the base field and 'k' is the " 

"dimension of the code.".format(i, maxindex)) 

 

a = F.primitive_element() 

m = F.degree() 

p = F.prime_subfield().order() 

A = [a ** k for k in range(m)] 

G = self.generator_matrix() 

N = self.dimension()*F.degree() # the total length of p-adic vector 

ivec = Integer(i).digits(p, padto=N) 

 

codeword = 0 

row = 0 

for g in G: 

codeword += sum(ivec[j+row*m]*A[j] for j in range(m)) * g 

row += 1 

 

# The codewords for a specific code can not change. So, we set them 

# to be immutable. 

codeword.set_immutable() 

return codeword 

 

def generator_matrix(self, encoder_name=None, **kwargs): 

r""" 

Returns a generator matrix of ``self``. 

 

INPUT: 

 

- ``encoder_name`` -- (default: ``None``) name of the encoder which will be 

used to compute the generator matrix. The default encoder of ``self`` 

will be used if default value is kept. 

 

- ``kwargs`` -- all additional arguments are forwarded to the construction of the 

encoder that is used. 

 

EXAMPLES:: 

 

sage: G = matrix(GF(3),2,[1,-1,1,-1,1,1]) 

sage: code = LinearCode(G) 

sage: code.generator_matrix() 

[1 2 1] 

[2 1 1] 

""" 

E = self.encoder(encoder_name, **kwargs) 

return E.generator_matrix() 

 

def systematic_generator_matrix(self, systematic_positions=None): 

""" 

Return a systematic generator matrix of the code. 

 

A generator matrix of a code is called systematic if it contains 

a set of columns forming an identity matrix. 

 

INPUT: 

 

- ``systematic_positions`` -- (default: ``None``) if supplied, the set 

of systematic positions in the systematic generator matrix. See the 

documentation for :class:`LinearCodeSystematicEncoder` details. 

 

EXAMPLES:: 

 

sage: G = matrix(GF(3), [[ 1, 2, 1, 0],\ 

[ 2, 1, 1, 1]]) 

sage: C = LinearCode(G) 

sage: C.generator_matrix() 

[1 2 1 0] 

[2 1 1 1] 

sage: C.systematic_generator_matrix() 

[1 2 0 1] 

[0 0 1 2] 

 

Specific systematic positions can also be requested: 

 

sage: C.systematic_generator_matrix(systematic_positions=[3,2]) 

[1 2 0 1] 

[1 2 1 0] 

""" 

systematic_positions = tuple(systematic_positions) if systematic_positions else None 

return self.encoder("Systematic", systematic_positions=systematic_positions).generator_matrix() 

 

generator_matrix_systematic = deprecated_function_alias(20835, 

systematic_generator_matrix) 

 

@cached_method 

def gens(self): 

r""" 

Returns the generators of this code as a list of vectors. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.gens() 

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

""" 

return self.generator_matrix().rows() 

 

def genus(self): 

r""" 

Returns the "Duursma genus" of the code, `\gamma_C = n+1-k-d`. 

 

EXAMPLES:: 

 

sage: C1 = codes.HammingCode(GF(2), 3); C1 

[7, 4] Hamming Code over GF(2) 

sage: C1.genus() 

1 

sage: C2 = codes.HammingCode(GF(4,"a"), 2); C2 

[5, 3] Hamming Code over GF(4) 

sage: C2.genus() 

0 

 

Since all Hamming codes have minimum distance 3, these computations 

agree with the definition, `n+1-k-d`. 

""" 

d = self.minimum_distance() 

n = self.length() 

k = self.dimension() 

gammaC = n+1-k-d 

return gammaC 

 

def __iter__(self): 

""" 

Return an iterator over the elements of this linear code. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: [list(c) for c in C if c.hamming_weight() < 4] 

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

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

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

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

 

TESTS:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: L = list(C) 

sage: L[10].is_immutable() 

True 

 

""" 

from sage.modules.finite_submodule_iter import \ 

FiniteFieldsubspace_iterator 

return FiniteFieldsubspace_iterator(self.generator_matrix(), immutable=True) 

 

@cached_method 

def information_set(self): 

""" 

Return an information set of the code. 

 

Return value of this method is cached. 

 

A set of column positions of a generator matrix of a code 

is called an information set if the corresponding columns 

form a square matrix of full rank. 

 

OUTPUT: 

 

- Information set of a systematic generator matrix of the code. 

 

EXAMPLES:: 

 

sage: G = matrix(GF(3),2,[1,2,0,\ 

2,1,1]) 

sage: code = LinearCode(G) 

sage: code.systematic_generator_matrix() 

[1 2 0] 

[0 0 1] 

sage: code.information_set() 

(0, 2) 

""" 

return self.encoder("Systematic").systematic_positions() 

 

def is_information_set(self, positions): 

""" 

Return whether the given positions form an information set. 

 

INPUT: 

 

- A list of positions, i.e. integers in the range 0 to `n-1` where `n` 

is the length of `self`. 

 

OUTPUT: 

 

- A boolean indicating whether the positions form an information set. 

 

 

EXAMPLES:: 

 

sage: G = matrix(GF(3),2,[1,2,0,\ 

2,1,1]) 

sage: code = LinearCode(G) 

sage: code.is_information_set([0,1]) 

False 

sage: code.is_information_set([0,2]) 

True 

""" 

try: 

self.encoder("Systematic", systematic_positions=tuple(positions)) 

return True 

except ValueError: 

return False 

 

 

def is_permutation_automorphism(self,g): 

r""" 

Returns `1` if `g` is an element of `S_n` (`n` = length of self) and 

if `g` is an automorphism of self. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(3), 3) 

sage: g = SymmetricGroup(13).random_element() 

sage: C.is_permutation_automorphism(g) 

0 

sage: MS = MatrixSpace(GF(2),4,8) 

sage: G = MS([[1,0,0,0,1,1,1,0],[0,1,1,1,0,0,0,0],[0,0,0,0,0,0,0,1],[0,0,0,0,0,1,0,0]]) 

sage: C = LinearCode(G) 

sage: S8 = SymmetricGroup(8) 

sage: g = S8("(2,3)") 

sage: C.is_permutation_automorphism(g) 

1 

sage: g = S8("(1,2,3,4)") 

sage: C.is_permutation_automorphism(g) 

0 

""" 

basis = self.generator_matrix().rows() 

H = self.parity_check_matrix() 

V = H.column_space() 

HGm = H*g.matrix() 

for c in basis: 

if HGm*c != V(0): 

return False 

return True 

 

def is_permutation_equivalent(self,other,algorithm=None): 

""" 

Returns ``True`` if ``self`` and ``other`` are permutation equivalent 

codes and ``False`` otherwise. 

 

The ``algorithm="verbose"`` option also returns a permutation (if 

``True``) sending ``self`` to ``other``. 

 

Uses Robert Miller's double coset partition refinement work. 

 

EXAMPLES:: 

 

sage: P.<x> = PolynomialRing(GF(2),"x") 

sage: g = x^3+x+1 

sage: C1 = codes.CyclicCode(length = 7, generator_pol = g); C1 

[7, 4] Cyclic Code over GF(2) 

sage: C2 = codes.HammingCode(GF(2), 3); C2 

[7, 4] Hamming Code over GF(2) 

sage: C1.is_permutation_equivalent(C2) 

True 

sage: C1.is_permutation_equivalent(C2,algorithm="verbose") 

(True, (3,4)(5,7,6)) 

sage: C1 = codes.random_linear_code(GF(2), 10, 5) 

sage: C2 = codes.random_linear_code(GF(3), 10, 5) 

sage: C1.is_permutation_equivalent(C2) 

False 

""" 

from sage.groups.perm_gps.partn_ref.refinement_binary import NonlinearBinaryCodeStruct 

F = self.base_ring() 

F_o = other.base_ring() 

q = F.order() 

G = self.generator_matrix() 

n = self.length() 

n_o = other.length() 

if F != F_o or n != n_o: 

return False 

k = len(G.rows()) 

MS = MatrixSpace(F,q**k,n) 

CW1 = MS(self.list()) 

CW2 = MS(other.list()) 

B1 = NonlinearBinaryCodeStruct(CW1) 

B2 = NonlinearBinaryCodeStruct(CW2) 

ans = B1.is_isomorphic(B2) 

if ans is not False: 

if algorithm=="verbose": 

Sn = SymmetricGroup(n) 

return True, Sn([i+1 for i in ans])**(-1) 

return True 

return False 

 

def is_self_dual(self): 

""" 

Returns ``True`` if the code is self-dual (in the usual Hamming inner 

product) and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: C = codes.GolayCode(GF(2)) 

sage: C.is_self_dual() 

True 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.is_self_dual() 

False 

""" 

return self == self.dual_code() 

 

def is_self_orthogonal(self): 

""" 

Returns ``True`` if this code is self-orthogonal and ``False`` 

otherwise. 

 

A code is self-orthogonal if it is a subcode of its dual. 

 

EXAMPLES:: 

 

sage: C = codes.GolayCode(GF(2)) 

sage: C.is_self_orthogonal() 

True 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.is_self_orthogonal() 

False 

sage: C = codes.QuasiQuadraticResidueCode(11) # optional - gap_packages (Guava package) 

sage: C.is_self_orthogonal() # optional - gap_packages (Guava package) 

True 

""" 

return self.is_subcode(self.dual_code()) 

 

def is_galois_closed(self): 

r""" 

Checks if ``self`` is equal to its Galois closure. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(4,"a"), 3) 

sage: C.is_galois_closed() 

False 

""" 

F = self.base_ring() 

p = F.characteristic() 

return self == self.galois_closure(GF(p)) 

 

def is_subcode(self, other): 

""" 

Returns ``True`` if ``self`` is a subcode of ``other``. 

 

EXAMPLES:: 

 

sage: C1 = codes.HammingCode(GF(2), 3) 

sage: G1 = C1.generator_matrix() 

sage: G2 = G1.matrix_from_rows([0,1,2]) 

sage: C2 = LinearCode(G2) 

sage: C2.is_subcode(C1) 

True 

sage: C1.is_subcode(C2) 

False 

sage: C3 = C1.extended_code() 

sage: C1.is_subcode(C3) 

False 

sage: C4 = C1.punctured([1]) 

sage: C4.is_subcode(C1) 

False 

sage: C5 = C1.shortened([1]) 

sage: C5.is_subcode(C1) 

False 

sage: C1 = codes.HammingCode(GF(9,"z"), 3) 

sage: G1 = C1.generator_matrix() 

sage: G2 = G1.matrix_from_rows([0,1,2]) 

sage: C2 = LinearCode(G2) 

sage: C2.is_subcode(C1) 

True 

""" 

G = self.generator_matrix() 

for r in G.rows(): 

if not(r in other): 

return False 

return True 

 

def cardinality(self): 

r""" 

Return the size of this code. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.cardinality() 

16 

sage: len(C) 

16 

""" 

return self.base_ring().order()**self.dimension() 

 

__len__ = cardinality 

 

def length(self): 

r""" 

Returns the length of this code. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.length() 

7 

""" 

return self._length 

 

def list(self): 

r""" 

Return a list of all elements of this linear code. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: Clist = C.list() 

sage: Clist[5]; Clist[5] in C 

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

True 

""" 

return [x for x in self] 

 

def _magma_init_(self, magma): 

r""" 

Retun a string representation in Magma of this linear code. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: Cm = magma(C) # optional - magma, indirect doctest 

sage: Cm.MinimumWeight() # optional - magma 

3 

 

""" 

G = magma(self.generator_matrix())._ref() 

s = 'LinearCode(%s)' % G 

return s 

 

@cached_method 

def minimum_distance(self, algorithm=None): 

r""" 

Returns the minimum distance of ``self``. 

 

.. NOTE:: 

 

When using GAP, this raises a ``NotImplementedError`` if 

the base field of the code has size greater than 256 due 

to limitations in GAP. 

 

INPUT: 

 

- ``algorithm`` -- (default: ``None``) the name of the algorithm to use 

to perform minimum distance computation. If set to ``None``, 

GAP methods will be used. ``algorithm`` can be: 

- ``"Guava"``, which will use optional GAP package Guava 

 

OUTPUT: 

 

- Integer, minimum distance of this code 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(3),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.minimum_distance() 

3 

 

If ``algorithm`` is provided, then the minimum distance will be 

recomputed even if there is a stored value from a previous run.:: 

 

sage: C.minimum_distance(algorithm="gap") 

3 

sage: C.minimum_distance(algorithm="guava") # optional - gap_packages (Guava package) 

3 

 

TESTS:: 

 

sage: C = codes.random_linear_code(GF(4,"a"), 5, 2) 

sage: C.minimum_distance(algorithm='something') 

Traceback (most recent call last): 

... 

ValueError: The algorithm argument must be one of None, 'gap' or 'guava'; got 'something' 

 

The field must be size at most 256:: 

 

sage: C = codes.random_linear_code(GF(257,"a"), 5, 2) 

sage: C.minimum_distance() 

Traceback (most recent call last): 

... 

NotImplementedError: the GAP algorithm that Sage is using 

is limited to computing with fields of size at most 256 

""" 

if algorithm == "guava" and not is_package_installed('gap_packages'): 

raise PackageNotFoundError('gap_packages') 

# If the minimum distance has already been computed or provided by 

# the user then simply return the stored value. 

# This is done only if algorithm is None. 

if algorithm not in (None, "gap", "guava"): 

raise ValueError("The algorithm argument must be one of None, " 

"'gap' or 'guava'; got '{0}'".format(algorithm)) 

 

F = self.base_ring() 

q = F.order() 

if q > 256: 

raise NotImplementedError("the GAP algorithm that Sage is using " 

"is limited to computing with fields " 

"of size at most 256") 

 

G = self.generator_matrix() 

n = self.length() 

k = self.dimension() 

if (q == 2 or q == 3) and algorithm=="guava": 

gap.load_package("guava") 

C = gap(G).GeneratorMatCode(gap(F)) 

d = C.MinimumWeight() 

return ZZ(d) 

return self._minimum_weight_codeword(algorithm).hamming_weight() 

 

def _minimum_weight_codeword(self, algorithm = None): 

r""" 

Returns a minimum weight codeword of ``self``. 

 

INPUT: 

 

- ``algorithm`` -- (default: ``None``) the name of the algorithm to use 

to perform minimum weight codeword search. If set to ``None``, 

a search using GAP methods will be done. ``algorithm`` can be: 

- ``"Guava"``, which will use optional GAP package Guava 

 

REMARKS: 

 

- The code in the default case allows one (for free) to also compute the 

message vector `m` such that `m\*G = v`, and the (minimum) distance, as 

a triple. however, this output is not implemented. 

- The binary case can presumably be done much faster using Robert Miller's 

code (see the docstring for the spectrum method). This is also not (yet) 

implemented. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C._minimum_weight_codeword() 

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

 

TESTS: 

 

We check that :trac:`18480` is fixed:: 

 

sage: codes.HammingCode(GF(2), 2).minimum_distance() 

3 

 

AUTHORS: 

 

- David Joyner (11-2005) 

""" 

G = self.generator_matrix() 

n, k = self.length(), self.dimension() 

F = self.base_field() 

Gmat = self.generator_matrix()._gap_init_() 

 

current_randstate().set_seed_gap() 

 

if algorithm=="guava": 

if not is_package_installed('gap_packages'): 

raise PackageNotFoundError('gap_packages') 

gap.load_package("guava") 

from sage.interfaces.gap import gfq_gap_to_sage 

gap.eval("G:="+Gmat) 

C = gap(Gmat).GeneratorMatCode(F) 

cg = C.MinimumDistanceCodeword() 

c = [gfq_gap_to_sage(cg[j],F) for j in range(1,n+1)] 

return vector(F, c) 

 

q = F.order() 

ans = None 

dist_min = n + 1 

gap.eval('Gmat:='+Gmat) 

gap.eval('K:=GF({})'.format(q)) 

gap.eval('v:=Z({})*{}'.format(q,[0]*n)) 

for i in range(1,k+1): 

gap.eval("P:=AClosestVectorCombinationsMatFFEVecFFECoords(Gmat,K,v,{},1)".format(i)) 

gap.eval("d:=WeightVecFFE(P[1])") 

v = gap("P[1]") 

dist = gap("d") 

if dist and dist < dist_min: 

dist_min = dist 

ans = list(v) 

 

if ans is None: 

raise RuntimeError("Computation failed due to some GAP error") 

 

# return the result as a vector (and not a 1xn matrix) 

return vector(F, ans) 

 

def module_composition_factors(self, gp): 

r""" 

Prints the GAP record of the Meataxe composition factors module in 

Meataxe notation. This uses GAP but not Guava. 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,8) 

sage: G = MS([[1,0,0,0,1,1,1,0],[0,1,1,1,0,0,0,0],[0,0,0,0,0,0,0,1],[0,0,0,0,0,1,0,0]]) 

sage: C = LinearCode(G) 

sage: gp = C.permutation_automorphism_group() 

 

Now type "C.module_composition_factors(gp)" to get the record printed. 

""" 

F = self.base_ring() 

q = F.order() 

gens = gp.gens() 

G = self.generator_matrix() 

n = len(G.columns()) 

MS = MatrixSpace(F,n,n) 

mats = [] # initializing list of mats by which the gens act on self 

Fn = VectorSpace(F, n) 

W = Fn.subspace_with_basis(G.rows()) # this is self 

for g in gens: 

p = MS(g.matrix()) 

m = [W.coordinate_vector(r*p) for r in G.rows()] 

mats.append(m) 

mats_str = str(gap([[list(r) for r in m] for m in mats])) 

gap.eval("M:=GModuleByMats("+mats_str+", GF("+str(q)+"))") 

print(gap("MTX.CompositionFactors( M )")) 

 

def permutation_automorphism_group(self, algorithm="partition"): 

r""" 

If `C` is an `[n,k,d]` code over `F`, this function computes the 

subgroup `Aut(C) \subset S_n` of all permutation automorphisms of `C`. 

The binary case always uses the (default) partition refinement 

algorithm of Robert Miller. 

 

Note that if the base ring of `C` is `GF(2)` then this is the full 

automorphism group. Otherwise, you could use 

:meth:`~sage.coding.linear_code.LinearCode.automorphism_group_gens` 

to compute generators of the full automorphism group. 

 

INPUT: 

 

- ``algorithm`` - If ``"gap"`` then GAP's MatrixAutomorphism function 

(written by Thomas Breuer) is used. The implementation combines an 

idea of mine with an improvement suggested by Cary Huffman. If 

``"gap+verbose"`` then code-theoretic data is printed out at 

several stages of the computation. If ``"partition"`` then the 

(default) partition refinement algorithm of Robert Miller is used. 

Finally, if ``"codecan"`` then the partition refinement algorithm 

of Thomas Feulner is used, which also computes a canonical 

representative of ``self`` (call 

:meth:`~sage.coding.linear_code.LinearCode.canonical_representative` 

to access it). 

 

OUTPUT: 

 

- Permutation automorphism group 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,8) 

sage: G = MS([[1,0,0,0,1,1,1,0],[0,1,1,1,0,0,0,0],[0,0,0,0,0,0,0,1],[0,0,0,0,0,1,0,0]]) 

sage: C = LinearCode(G) 

sage: C 

[8, 4] linear code over GF(2) 

sage: G = C.permutation_automorphism_group() 

sage: G.order() 

144 

sage: GG = C.permutation_automorphism_group("codecan") 

sage: GG == G 

True 

 

A less easy example involves showing that the permutation 

automorphism group of the extended ternary Golay code is the 

Mathieu group `M_{11}`. 

 

:: 

 

sage: C = codes.GolayCode(GF(3)) 

sage: M11 = MathieuGroup(11) 

sage: M11.order() 

7920 

sage: G = C.permutation_automorphism_group() # long time (6s on sage.math, 2011) 

sage: G.is_isomorphic(M11) # long time 

True 

sage: GG = C.permutation_automorphism_group("codecan") # long time 

sage: GG == G # long time 

True 

 

Other examples:: 

 

sage: C = codes.GolayCode(GF(2)) 

sage: G = C.permutation_automorphism_group() 

sage: G.order() 

244823040 

sage: C = codes.HammingCode(GF(2), 5) 

sage: G = C.permutation_automorphism_group() 

sage: G.order() 

9999360 

sage: C = codes.HammingCode(GF(3), 2); C 

[4, 2] Hamming Code over GF(3) 

sage: C.permutation_automorphism_group(algorithm="partition") 

Permutation Group with generators [(1,3,4)] 

sage: C = codes.HammingCode(GF(4,"z"), 2); C 

[5, 3] Hamming Code over GF(4) 

sage: G = C.permutation_automorphism_group(algorithm="partition"); G 

Permutation Group with generators [(1,3)(4,5), (1,4)(3,5)] 

sage: GG = C.permutation_automorphism_group(algorithm="codecan") # long time 

sage: GG == G # long time 

True 

sage: C.permutation_automorphism_group(algorithm="gap") # optional - gap_packages (Guava package) 

Permutation Group with generators [(1,3)(4,5), (1,4)(3,5)] 

sage: C = codes.GolayCode(GF(3), True) 

sage: C.permutation_automorphism_group(algorithm="gap") # optional - gap_packages (Guava package) 

Permutation Group with generators [(5,7)(6,11)(8,9)(10,12), (4,6,11)(5,8,12)(7,10,9), (3,4)(6,8)(9,11)(10,12), (2,3)(6,11)(8,12)(9,10), (1,2)(5,10)(7,12)(8,9)] 

 

However, the option ``algorithm="gap+verbose"``, will print out:: 

 

Minimum distance: 5 Weight distribution: [1, 0, 0, 0, 0, 132, 132, 

0, 330, 110, 0, 24] 

 

Using the 132 codewords of weight 5 Supergroup size: 39916800 

 

in addition to the output of 

``C.permutation_automorphism_group(algorithm="gap")``. 

""" 

F = self.base_ring() 

q = F.order() 

G = self.generator_matrix() if 2*self.dimension() <= self.length() else self.dual_code().generator_matrix() 

n = len(G.columns()) 

k = len(G.rows()) 

if "gap" in algorithm: 

if not is_package_installed('gap_packages'): 

raise PackageNotFoundError('gap_packages') 

gap.load_package('guava') 

wts = self.weight_distribution() # bottleneck 1 

nonzerowts = [i for i in range(len(wts)) if wts[i]!=0] 

Sn = SymmetricGroup(n) 

Gp = gap("SymmetricGroup(%s)"%n) # initializing G in gap 

Gstr = str(gap(G)) 

gap.eval("C:=GeneratorMatCode("+Gstr+",GF("+str(q)+"))") 

gap.eval("eltsC:=Elements(C)") 

if algorithm=="gap+verbose": 

print("\n Minimum distance: %s \n Weight distribution: \n %s" % (nonzerowts[1], wts)) 

stop = 0 # only stop if all gens are autos 

for i in range(1,len(nonzerowts)): 

if stop == 1: 

break 

wt = nonzerowts[i] 

if algorithm=="gap+verbose": 

size = Gp.Size() 

print("\n Using the %s codewords of weight %s \n Supergroup size: \n %s\n " % (wts[wt], wt, size)) 

gap.eval("Cwt:=Filtered(eltsC,c->WeightCodeword(c)=%s)"%wt) # bottleneck 2 (repeated 

gap.eval("matCwt:=List(Cwt,c->VectorCodeword(c))") # for each i until stop = 1) 

if gap("Length(matCwt)") > 0: 

A = gap("MatrixAutomorphisms(matCwt)") 

G2 = gap("Intersection2(%s,%s)"%(str(A).replace("\n",""),str(Gp).replace("\n",""))) # bottleneck 3 

Gp = G2 

if Gp.Size()==1: 

return PermutationGroup([()]) 

autgp_gens = Gp.GeneratorsOfGroup() 

gens = [Sn(str(x).replace("\n","")) for x in autgp_gens] 

stop = 1 # get ready to stop 

for x in gens: # if one of these gens is not an auto then don't stop 

if not(self.is_permutation_automorphism(x)): 

stop = 0 

break 

G = PermutationGroup(gens) 

return G 

if algorithm=="partition": 

if q == 2: 

from sage.groups.perm_gps.partn_ref.refinement_binary import LinearBinaryCodeStruct 

B = LinearBinaryCodeStruct(G) 

autgp = B.automorphism_group() 

L = [[j+1 for j in gen] for gen in autgp[0]] 

AutGp = PermutationGroup(L) 

else: 

from sage.groups.perm_gps.partn_ref.refinement_matrices import MatrixStruct 

from sage.matrix.constructor import matrix 

weights = {} 

for c in self: 

wt = c.hamming_weight() 

if wt not in weights: 

weights[wt] = [c] 

else: 

weights[wt].append(c) 

weights.pop(0) 

AutGps = [] 

for wt, words in iteritems(weights): 

M = MatrixStruct(matrix(words)) 

autgp = M.automorphism_group() 

L = [[j+1 for j in gen] for gen in autgp[0]] 

G = PermutationGroup(L) 

AutGps.append(G) 

if len(AutGps) > 0: 

AutGp = AutGps[0] 

for G in AutGps[1:]: 

AutGp = AutGp.intersection(G) 

else: 

return PermutationGroup([]) 

return AutGp 

if algorithm=="codecan": 

gens, _ = self.automorphism_group_gens("permutational") 

return PermutationGroup([x.get_perm() for x in gens]) 

raise NotImplementedError("The only algorithms implemented currently are 'gap', 'gap+verbose', and 'partition'.") 

 

def permuted_code(self, p): 

r""" 

Returns the permuted code, which is equivalent to ``self`` via the 

column permutation ``p``. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: G = C.permutation_automorphism_group(); G 

Permutation Group with generators [(4,5)(6,7), (4,6)(5,7), (2,3)(6,7), (2,4)(3,5), (1,2)(5,6)] 

sage: g = G("(2,3)(6,7)") 

sage: Cg = C.permuted_code(g) 

sage: Cg 

[7, 4] linear code over GF(2) 

sage: C.generator_matrix() == Cg.systematic_generator_matrix() 

True 

""" 

G = copy(self.generator_matrix()) 

G.permute_columns(p) 

return LinearCode(G) 

 

def punctured(self, L): 

r""" 

Returns a :class:`sage.coding.punctured_code` object from ``L``. 

 

INPUT: 

 

- ``L`` - List of positions to puncture 

 

OUTPUT: 

 

- an instance of :class:`sage.coding.punctured_code` 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.punctured([1,2]) 

Puncturing of [7, 4] Hamming Code over GF(2) on position(s) [1, 2] 

""" 

from .punctured_code import PuncturedCode 

return PuncturedCode(self, set(L)) 

 

def _punctured_form(self, points): 

r""" 

Returns a representation of self as a :class:`LinearCode` punctured in ``points``. 

 

INPUT: 

 

- ``points`` -- a set of positions where to puncture ``self`` 

 

EXAMPLES:: 

 

sage: C = codes.random_linear_code(GF(7), 11, 4) 

sage: C._punctured_form({3}) 

[10, 4] linear code over GF(7) 

""" 

if not isinstance(points, (Integer, int, set)): 

raise TypeError("points must be either a Sage Integer, a Python int, or a set") 

M = self.generator_matrix() 

G = M.delete_columns(list(points)) 

G = G.echelon_form() 

k = G.rank() 

return LinearCode(G[:k]) 

 

def random_element(self, *args, **kwds): 

""" 

Returns a random codeword; passes other positional and keyword 

arguments to ``random_element()`` method of vector space. 

 

OUTPUT: 

 

- Random element of the vector space of this code 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(4,'a'), 3) 

sage: C.random_element() # random test 

(1, 0, 0, a + 1, 1, a, a, a + 1, a + 1, 1, 1, 0, a + 1, a, 0, a, a, 0, a, a, 1) 

 

Passes extra positional or keyword arguments through:: 

 

sage: C.random_element(prob=.5, distribution='1/n') # random test 

(1, 0, a, 0, 0, 0, 0, a + 1, 0, 0, 0, 0, 0, 0, 0, 0, a + 1, a + 1, 1, 0, 0) 

 

TESTS: 

 

Test that the codeword returned is immutable (see :trac:`16469`):: 

 

sage: c = C.random_element() 

sage: c.is_immutable() 

True 

 

Test that codeword returned has the same parent as any non-random codeword 

(see :trac:`19653`):: 

 

sage: C = codes.random_linear_code(GF(16, 'a'), 10, 4) 

sage: c1 = C.random_element() 

sage: c2 = C[1] 

sage: c1.parent() == c2.parent() 

True 

""" 

E = self.encoder() 

M = E.message_space() 

m = M.random_element(*args, **kwds) 

c = E.encode(m) 

c.set_immutable() 

return c 

 

def relative_distance(self): 

r""" 

Return the ratio of the minimum distance to the code length. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2),3) 

sage: C.relative_distance() 

3/7 

""" 

return self.minimum_distance() / self.length() 

 

def rate(self): 

r""" 

Return the ratio of the number of information symbols to 

the code length. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.rate() 

4/7 

""" 

return self.dimension() / self.length() 

 

def redundancy_matrix(self): 

r""" 

Returns the non-identity columns of a systematic generator matrix for 

``self``. 

 

A systematic generator matrix is a generator matrix such that a subset 

of its columns forms the identity matrix. This method returns the 

remaining part of the matrix. 

 

For any given code, there can be many systematic generator matrices 

(depending on which positions should form the identity). This method 

will use the matrix returned by 

:meth:`AbstractLinearCode.systematic_generator_matrix`. 

 

OUTPUT: 

 

- An `k \times (n-k)` matrix. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 1 1 0] 

[0 0 0 1 1 1 1] 

sage: C.redundancy_matrix() 

[0 1 1] 

[1 0 1] 

[1 1 0] 

[1 1 1] 

sage: C = LinearCode(matrix(GF(3),2,[1,2,0,\ 

2,1,1])) 

sage: C.systematic_generator_matrix() 

[1 2 0] 

[0 0 1] 

sage: C.redundancy_matrix() 

[2] 

[0] 

""" 

E = self.encoder("Systematic") 

G = E.generator_matrix() 

return G.delete_columns(E.systematic_positions()) 

 

def sd_duursma_data(self, i, warn=True): 

r""" 

Compute two integers pertaining to the computation of the self-dual 

Duursma zeta function for ``self``, if ``self`` is a self-dual code. 

 

INPUT: 

 

- ``i`` - Type number 

 

OUTPUT: 

 

- Pair ``(v, m)`` as in Duursma [Du2003]_ 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),2,4) 

sage: G = MS([1,1,0,0,0,0,1,1]) 

sage: C = LinearCode(G) 

sage: C == C.dual_code() # checks that C is self dual 

True 

sage: for i in [1,2,3,4]: print(C.sd_duursma_data(i)) 

doctest:...: DeprecationWarning: AbstractLinearCode.sd_duursma_data will be removed in a future release of Sage. Please use AbstractLinearCode.zeta_polynomial() to compute the Duursma zeta polynomial 

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

(2, -1) 

(2, -3) 

(2, -2) 

(2, -1) 

""" 

if warn: 

deprecation(21165, "AbstractLinearCode.sd_duursma_data will be removed in a future release of Sage. Please use AbstractLinearCode.zeta_polynomial() to compute the Duursma zeta polynomial") 

n = self.length() 

d = self.minimum_distance() 

if i == 1: 

v = (n-4*d)//2 + 4 

m = d-3 

elif i == 2: 

v = (n-6*d)//8 + 3 

m = d-5 

elif i == 3: 

v = (n-4*d)//4 + 3 

m = d-4 

elif i == 4: 

v = (n-3*d)//2 + 3 

m = d-3 

else: 

raise ValueError("the type i should be 1,2,3 or 4") 

return (ZZ(v),m) 

 

def sd_duursma_q(self, i, d0, warn=True): 

r""" 

Compute a polynomial pertaining to the computation of the self-dual 

Duursma zeta function for ``self``, if ``self`` is a self-dual code. 

 

INPUT: 

 

- ``i`` - Type number, one of 1,2,3,4 

- ``d0`` - Divisor, the smallest integer such that each `A_i > 0` iff 

`i` is divisible by `d0` 

 

OUTPUT: 

 

- The polynomial `Q(T)` as in Duursma [Du2003]_ 

 

EXAMPLES:: 

 

sage: C1 = codes.HammingCode(GF(2), 3) 

sage: C2 = C1.extended_code(); C2 

Extension of [7, 4] Hamming Code over GF(2) 

sage: C2.sd_duursma_q(1,1) 

doctest:...: DeprecationWarning: AbstractLinearCode.sd_duursma_q will be removed in a future release of Sage. Please use AbstractLinearCode.zeta_polynomial() to compute the Duursma zeta polynomial 

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

2/5*T^2 + 2/5*T + 1/5 

sage: C2.sd_duursma_q(3,1) 

3/5*T^4 + 1/5*T^3 + 1/15*T^2 + 1/15*T + 1/15 

""" 

if warn: 

deprecation(21165, "AbstractLinearCode.sd_duursma_q will be removed in a future release of Sage. Please use AbstractLinearCode.zeta_polynomial() to compute the Duursma zeta polynomial") 

q = (self.base_ring()).order() 

n = self.length() 

d = self.minimum_distance() 

d0 = self.divisor() 

if i==1 or i==2: 

if d>d0: 

c0 = QQ((n-d)*rising_factorial(d-d0,d0+1)*self.weight_distribution()[d])/rising_factorial(n-d0-1,d0+2) 

else: 

c0 = QQ((n-d)*self.weight_distribution()[d])/rising_factorial(n-d0-1,d0+2) 

if i==3 or i==4: 

if d>d0: 

c0 = rising_factorial(d-d0,d0+1)*self.weight_distribution()[d]/((q-1)*rising_factorial(n-d0,d0+1)) 

else: 

c0 = self.weight_distribution()[d]/((q-1)*rising_factorial(n-d0,d0+1)) 

v, m = self.sd_duursma_data(i, warn=False) 

if m<0 or v<0: 

raise NotImplementedError("This combination of length and minimum distance is not supported.") 

PR = PolynomialRing(QQ,"T") 

T = PR.gen() 

if i == 1: 

coefs = PR(c0*(1+3*T+2*T**2)**m*(2*T**2+2*T+1)**v).list() 

qc = [coefs[j]/binomial(4*m+2*v,m+j) for j in range(2*m+2*v+1)] 

if i == 2: 

F = ((T+1)**8+14*T**4*(T+1)**4+T**8)**v 

coefs = (c0*(1+T)**m*(1+4*T+6*T**2+4*T**3)**m*F).coefficients(sparse=False) 

qc = [coefs[j]/binomial(6*m+8*v,m+j) for j in range(4*m+8*v+1)] 

if i == 3: 

F = (3*T**2+4*T+1)**v*(1+3*T**2)**v 

# Note that: (3*T**2+4*T+1)(1+3*T**2)=(T+1)**4+8*T**3*(T+1) 

coefs = (c0*(1+3*T+3*T**2)**m*F).coefficients(sparse=False) 

qc = [coefs[j]/binomial(4*m+4*v,m+j) for j in range(2*m+4*v+1)] 

if i == 4: 

coefs = (c0*(1+2*T)**m*(4*T**2+2*T+1)**v).coefficients(sparse=False) 

qc = [coefs[j]/binomial(3*m+2*v,m+j) for j in range(m+2*v+1)] 

Q = PR(qc) 

return Q/Q(1) 

 

def sd_zeta_polynomial(self, typ=1): 

r""" 

Return the Duursma zeta polynomial, computed in a fashion that only 

works if ``self`` is self-dual. 

 

.. WARNING:: 

 

This function does not check that ``self`` is self-dual. Indeed, it 

is not even clear which notion of self-dual is supported ([Du2003]_ seems 

to indicate formal self-dual, but the example below is a hexacode 

which is Hermitian self-dual). 

 

INPUT: 

 

- ``typ`` - Integer, type of this s.d. code; one of 1,2,3, or 

4 (default: 1) 

 

OUTPUT: 

 

- Polynomial in a variable "T": the Duursma zeta function as in [Du2003]_ 

 

EXAMPLES:: 

 

sage: C1 = codes.HammingCode(GF(2), 3) 

sage: C2 = C1.extended_code(); C2 

Extension of [7, 4] Hamming Code over GF(2) 

sage: P = C2.sd_zeta_polynomial(); P 

doctest:...: DeprecationWarning: AbstractLinearCode.sd_zeta_polynomial() will be removed in a future release of Sage. Please use AbstractLinearCode.zeta_polynomial() instead 

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

2/5*T^2 + 2/5*T + 1/5 

sage: P(1) 

1 

sage: F.<z> = GF(4,"z") 

sage: MS = MatrixSpace(F, 3, 6) 

sage: G = MS([[1,0,0,1,z,z],[0,1,0,z,1,z],[0,0,1,z,z,1]]) 

sage: C = LinearCode(G) # the "hexacode" 

sage: C.sd_zeta_polynomial(4) 

1 

""" 

deprecation(21165, "AbstractLinearCode.sd_zeta_polynomial() will be removed in a future release of Sage. Please use AbstractLinearCode.zeta_polynomial() instead") 

if not self.base_field().cardinality() <= 4: 

raise ValueError("the Duursma zeta polynomial is only defined for codes over GF(2), GF(3) or GF(4).") 

d0 = self.divisor() 

Q = self.sd_duursma_q(typ,d0, warn=False) 

PR = Q.parent() 

T = PR.fraction_field().gen() 

if typ == 1: 

P0 = Q 

if typ == 2: 

P0 = Q/(1-2*T+2*T**2) 

if typ == 3: 

P0 = Q/(1+3*T**2) 

if typ == 4: 

P0 = Q/(1+2*T) 

return PR(P0/P0(1)) 

 

def shortened(self, L): 

r""" 

Returns the code shortened at the positions ``L``, where 

`L \subset \{1,2,...,n\}`. 

 

Consider the subcode `C(L)` consisting of all codewords `c\in C` which 

satisfy `c_i=0` for all `i\in L`. The punctured code `C(L)^L` is 

called the shortened code on `L` and is denoted `C_L`. The code 

constructed is actually only isomorphic to the shortened code defined 

in this way. 

 

By Theorem 1.5.7 in [HP2003]_, `C_L` is `((C^\perp)^L)^\perp`. This is used 

in the construction below. 

 

INPUT: 

 

- ``L`` - Subset of `\{1,...,n\}`, where `n` is the length of this code 

 

OUTPUT: 

 

- Linear code, the shortened code described above 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.shortened([1,2]) 

[5, 2] linear code over GF(2) 

""" 

Cd = self.dual_code() 

Cdp = Cd.punctured(set(L)) 

return Cdp.dual_code() 

 

@cached_method 

def weight_distribution(self, algorithm=None): 

r""" 

Returns the weight distribution, or spectrum, of ``self`` as a list. 

 

The weight distribution a code of length `n` is the sequence `A_0, 

A_1,..., A_n` where `A_i` is the number of codewords of weight `i`. 

 

INPUT: 

 

- ``algorithm`` - (optional, default: ``None``) If set to ``"gap"``, 

call GAP. If set to `"leon"`, call the option GAP package GUAVA and 

call a function therein by Jeffrey Leon (see warning below). If set to 

``"binary"``, use an algorithm optimized for binary codes. The default 

is to use ``"binary"`` for binary codes and ``"gap"`` otherwise. 

 

OUTPUT: 

 

- A list of non-negative integers: the weight distribution. 

 

.. WARNING:: 

 

Specifying ``algorithm = "leon"`` sometimes prints a traceback 

related to a stack smashing error in the C library. The result 

appears to be computed correctly, however. It appears to run much 

faster than the GAP algorithm in small examples and much slower than 

the GAP algorithm in larger examples. 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C.weight_distribution() 

[1, 0, 0, 7, 7, 0, 0, 1] 

sage: F.<z> = GF(2^2,"z") 

sage: C = codes.HammingCode(F, 2); C 

[5, 3] Hamming Code over GF(4) 

sage: C.weight_distribution() 

[1, 0, 0, 30, 15, 18] 

sage: C = codes.HammingCode(GF(2), 3); C 

[7, 4] Hamming Code over GF(2) 

sage: C.weight_distribution(algorithm="leon") # optional - gap_packages (Guava package) 

[1, 0, 0, 7, 7, 0, 0, 1] 

sage: C.weight_distribution(algorithm="gap") 

[1, 0, 0, 7, 7, 0, 0, 1] 

sage: C.weight_distribution(algorithm="binary") 

[1, 0, 0, 7, 7, 0, 0, 1] 

sage: C = codes.HammingCode(GF(3), 3); C 

[13, 10] Hamming Code over GF(3) 

sage: C.weight_distribution() == C.weight_distribution(algorithm="leon") # optional - gap_packages (Guava package) 

True 

sage: C = codes.HammingCode(GF(5), 2); C 

[6, 4] Hamming Code over GF(5) 

sage: C.weight_distribution() == C.weight_distribution(algorithm="leon") # optional - gap_packages (Guava package) 

True 

sage: C = codes.HammingCode(GF(7), 2); C 

[8, 6] Hamming Code over GF(7) 

sage: C.weight_distribution() == C.weight_distribution(algorithm="leon") # optional - gap_packages (Guava package) 

True 

 

""" 

if algorithm is None: 

if self.base_ring().order() == 2: 

algorithm = "binary" 

else: 

algorithm = "gap" 

F = self.base_ring() 

n = self.length() 

G = self.generator_matrix() 

if algorithm=="gap": 

Gmat = self.generator_matrix()._gap_init_() 

G = gap(Gmat) 

q = self.base_ring().order() 

k = gap(self.base_ring()) 

z = 'Z(%s)*%s'%(q, [0]*self.length()) # GAP zero vector as a string 

_ = gap.eval("w:=DistancesDistributionMatFFEVecFFE("+Gmat+", GF("+str(q)+"),"+z+")") 

v = [eval(gap.eval("w["+str(i)+"]")) for i in range(1,self.length()+2)] # because GAP returns vectors in compressed form 

return v 

elif algorithm=="binary": 

from sage.coding.binary_code import weight_dist 

return weight_dist(self.generator_matrix()) 

elif algorithm=="leon": 

if not(F.order() in [2,3,5,7]): 

raise NotImplementedError("The algorithm 'leon' is only implemented for q = 2,3,5,7.") 

# The GAP command DirectoriesPackageLibrary tells the location of the latest 

# version of the Guava libraries, so gives us the location of the Guava binaries too. 

guava_bin_dir = gap.eval('DirectoriesPackagePrograms("guava")[1]') 

guava_bin_dir = guava_bin_dir[guava_bin_dir.index('"') + 1:guava_bin_dir.rindex('"')] 

input = _dump_code_in_leon_format(self) + "::code" 

import os 

import subprocess 

lines = subprocess.check_output([os.path.join(guava_bin_dir, 'wtdist'), input]) 

from six import StringIO 

# to use the already present output parser 

wts = [0] * (n + 1) 

s = 0 

for L in StringIO(lines).readlines(): 

L = L.strip() 

if L: 

o = ord(L[0]) 

if o >= 48 and o <= 57: 

wt, num = L.split() 

wts[eval(wt)] = eval(num) 

return wts 

else: 

raise NotImplementedError("The only algorithms implemented currently are 'gap', 'leon' and 'binary'.") 

 

spectrum = weight_distribution 

 

def standard_form(self, return_permutation=True): 

r""" 

Returns a linear code which is permutation-equivalent to ``self`` and 

admits a generator matrix in standard form. 

 

A generator matrix is in standard form if it is of the form `[I \vert 

A]`, where `I` is the `k \times k` identity matrix. Any code admits a 

generator matrix in systematic form, i.e. where a subset of the columns 

form the identity matrix, but one might need to permute columns to allow 

the identity matrix to be leading. 

 

INPUT: 

 

- ``return_permutation`` -- (default: ``True``) if ``True``, the column 

permutation which brings ``self`` into the returned code is also 

returned. 

 

OUTPUT: 

 

- A :class:`LinearCode` whose :meth:`systematic_generator_matrix` is 

guaranteed to be of the form `[I \vert A]`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 1 1 0] 

[0 0 0 1 1 1 1] 

sage: Cs,p = C.standard_form() 

sage: p 

[] 

sage: Cs is C 

True 

sage: C = LinearCode(matrix(GF(2), [[1,0,0,0,1,1,0],\ 

[0,1,0,1,0,1,0],\ 

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

sage: Cs, p = C.standard_form() 

sage: p 

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

sage: Cs.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 0 0 0] 

""" 

E = self.encoder("Systematic") 

if E.systematic_positions() == tuple(range(self.dimension())): 

from sage.combinat.permutation import Permutation 

return self, Permutation([]) 

else: 

perm = E.systematic_permutation() 

return self.permuted_code(perm), perm 

 

def support(self): 

r""" 

Returns the set of indices `j` where `A_j` is nonzero, where 

`A_j` is the number of codewords in `self` of Hamming weight `j`. 

 

OUTPUT: 

 

- List of integers 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.weight_distribution() 

[1, 0, 0, 7, 7, 0, 0, 1] 

sage: C.support() 

[0, 3, 4, 7] 

""" 

n = self.length() 

F = self.base_ring() 

V = VectorSpace(F,n+1) 

return V(self.weight_distribution()).support() 

 

def syndrome(self, r): 

r""" 

Returns the syndrome of ``r``. 

 

The syndrome of ``r`` is the result of `H \times r` where `H` is 

the parity check matrix of ``self``. If ``r`` belongs to ``self``, 

its syndrome equals to the zero vector. 

 

INPUT: 

 

- ``r`` -- a vector of the same length as ``self`` 

 

OUTPUT: 

 

- a column vector 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: r = vector(GF(2), (1,0,1,0,1,0,1)) 

sage: r in C 

True 

sage: C.syndrome(r) 

(0, 0, 0) 

 

If ``r`` is not a codeword, its syndrome is not equal to zero:: 

 

sage: r = vector(GF(2), (1,0,1,0,1,1,1)) 

sage: r in C 

False 

sage: C.syndrome(r) 

(0, 1, 1) 

 

Syndrome computation works fine on bigger fields:: 

 

sage: C = codes.random_linear_code(GF(59), 12, 4) 

sage: c = C.random_element() 

sage: C.syndrome(c) 

(0, 0, 0, 0, 0, 0, 0, 0) 

""" 

return self.parity_check_matrix()*r 

 

def unencode(self, c, encoder_name=None, nocheck=False, **kwargs): 

r""" 

Returns the message corresponding to ``c``. 

 

This is the inverse of :meth:`encode`. 

 

INPUT: 

 

- ``c`` -- a codeword of ``self``. 

 

- ``encoder_name`` -- (default: ``None``) name of the decoder which will be used 

to decode ``word``. The default decoder of ``self`` will be used if 

default value is kept. 

 

- ``nocheck`` -- (default: ``False``) checks if ``c`` is in ``self``. You might set 

this to ``True`` to disable the check for saving computation. Note that if ``c`` is 

not in ``self`` and ``nocheck = True``, then the output of :meth:`unencode` is 

not defined (except that it will be in the message space of ``self``). 

 

- ``kwargs`` -- all additional arguments are forwarded to the construction of the 

encoder that is used. 

 

OUTPUT: 

 

- an element of the message space of ``encoder_name`` of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: c = vector(GF(2), (1, 1, 0, 0, 1, 1, 0)) 

sage: C.unencode(c) 

(0, 1, 1, 0) 

""" 

E = self.encoder(encoder_name, **kwargs) 

return E.unencode(c, nocheck) 

 

def weight_enumerator(self, names=None, name2=None, bivariate=True): 

""" 

Return the weight enumerator polynomial of ``self``. 

 

This is the bivariate, homogeneous polynomial in `x` and `y` whose 

coefficient to `x^i y^{n-i}` is the number of codewords of `self` of 

Hamming weight `i`. Here, `n` is the length of `self`. 

 

INPUT: 

 

- ``names`` - (default: ``"xy"``) The names of the variables in the 

homogeneous polynomial. Can be given as a single string of length 2, 

or a single string with a comma, or as a tuple or list of two strings. 

 

- ``name2`` - Deprecated, (default: ``None``) The string name of the 

second variable. 

 

- ``bivariate`` - (default: `True`) Whether to return a bivariate, 

homogeneous polynomial or just a univariate polynomial. If set to 

``False``, then ``names`` will be interpreted as a single variable 

name and default to ``"x"``. 

 

OUTPUT: 

 

- The weight enumerator polynomial over `\ZZ`. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.weight_enumerator() 

x^7 + 7*x^4*y^3 + 7*x^3*y^4 + y^7 

sage: C.weight_enumerator(names="st") 

s^7 + 7*s^4*t^3 + 7*s^3*t^4 + t^7 

sage: C.weight_enumerator(names="var1, var2") 

var1^7 + 7*var1^4*var2^3 + 7*var1^3*var2^4 + var2^7 

sage: C.weight_enumerator(names=('var1', 'var2')) 

var1^7 + 7*var1^4*var2^3 + 7*var1^3*var2^4 + var2^7 

sage: C.weight_enumerator(bivariate=False) 

x^7 + 7*x^4 + 7*x^3 + 1 

 

An example of a code with a non-symmetrical weight enumerator:: 

 

sage: C = codes.GolayCode(GF(3), extended=False) 

sage: C.weight_enumerator() 

24*x^11 + 110*x^9*y^2 + 330*x^8*y^3 + 132*x^6*y^5 + 132*x^5*y^6 + y^11 

""" 

if names is None: 

if bivariate: 

names = "xy" 

else: 

names = "x" 

else: 

if name2 is not None: 

from sage.misc.superseded import deprecation 

deprecation(21576, "Optional argument name2 is deprecated. You should just give a tuple to `names`.") 

names = (names, name2) 

spec = self.weight_distribution() 

n = self.length() 

if bivariate: 

R = PolynomialRing(ZZ,2,names) 

x,y = R.gens() 

return sum(spec[i]*x**i*y**(n-i) for i in range(n+1)) 

else: 

R = PolynomialRing(ZZ,names) 

x, = R.gens() 

return sum(spec[i]*x**i for i in range(n+1)) 

 

@cached_method 

def zero(self): 

r""" 

Returns the zero vector of ``self``. 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.zero() 

(0, 0, 0, 0, 0, 0, 0) 

sage: C.sum(()) # indirect doctest 

(0, 0, 0, 0, 0, 0, 0) 

sage: C.sum((C.gens())) # indirect doctest 

(1, 1, 1, 1, 1, 1, 1) 

""" 

return self.ambient_space().zero() 

 

def zeta_polynomial(self, name="T"): 

r""" 

Returns the Duursma zeta polynomial of this code. 

 

Assumes that the minimum distances of this code and its dual are 

greater than 1. Prints a warning to ``stdout`` otherwise. 

 

INPUT: 

 

- ``name`` - String, variable name (default: ``"T"``) 

 

OUTPUT: 

 

- Polynomial over `\QQ` 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.zeta_polynomial() 

2/5*T^2 + 2/5*T + 1/5 

sage: C = codes.databases.best_linear_code_in_guava(6,3,GF(2)) # optional - gap_packages (Guava package) 

sage: C.minimum_distance() # optional - gap_packages (Guava package) 

3 

sage: C.zeta_polynomial() # optional - gap_packages (Guava package) 

2/5*T^2 + 2/5*T + 1/5 

sage: C = codes.HammingCode(GF(2), 4) 

sage: C.zeta_polynomial() 

16/429*T^6 + 16/143*T^5 + 80/429*T^4 + 32/143*T^3 + 30/143*T^2 + 2/13*T + 1/13 

sage: F.<z> = GF(4,"z") 

sage: MS = MatrixSpace(F, 3, 6) 

sage: G = MS([[1,0,0,1,z,z],[0,1,0,z,1,z],[0,0,1,z,z,1]]) 

sage: C = LinearCode(G) # the "hexacode" 

sage: C.zeta_polynomial() 

1 

 

REFERENCES: 

 

.. [Du01] \I. Duursma, "From weight enumerators to zeta functions", in 

Discrete Applied Mathematics, vol. 111, no. 1-2, pp. 55-73, 2001. 

""" 

n = self.length() 

q = (self.base_ring()).order() 

d = self.minimum_distance() 

dperp = (self.dual_code()).minimum_distance() 

if d == 1 or dperp == 1: 

print("\n WARNING: There is no guarantee this function works when the minimum distance") 

print(" of the code or of the dual code equals 1.\n") 

RT = PolynomialRing(QQ,"%s"%name) 

R = PolynomialRing(QQ,3,"xy%s"%name) 

x,y,T = R.gens() 

we = self.weight_enumerator() 

A = R(we) 

#B = A(x+y,y,T)-(x+y)**n 

B = A(x,x+y,T)-(x+y)**n 

Bs = B.coefficients() 

Bs.reverse() 

b = [Bs[i]/binomial(n,i+d) for i in range(len(Bs))] 

r = n-d-dperp+2 

P_coeffs = [] 

for i in range(len(b)): 

if i == 0: 

P_coeffs.append(b[0]) 

if i == 1: 

P_coeffs.append(b[1] - (q+1)*b[0]) 

if i>1: 

P_coeffs.append(b[i] - (q+1)*b[i-1] + q*b[i-2]) 

P = sum([P_coeffs[i]*T**i for i in range(r+1)]) 

return RT(P)/RT(P)(1) 

 

def zeta_function(self, name="T"): 

r""" 

Returns the Duursma zeta function of the code. 

 

INPUT: 

 

- ``name`` - String, variable name (default: ``"T"``) 

 

OUTPUT: 

 

- Element of `\QQ(T)` 

 

EXAMPLES:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: C.zeta_function() 

(2/5*T^2 + 2/5*T + 1/5)/(2*T^2 - 3*T + 1) 

""" 

P = self.zeta_polynomial() 

q = (self.base_ring()).characteristic() 

RT = PolynomialRing(QQ,"%s"%name) 

T = RT.gen() 

return P/((1-T)*(1-q*T)) 

 

def LinearCodeFromVectorSpace(V, d=None): 

""" 

Simply converts a vector subspace `V` of `GF(q)^n` into a `LinearCode`. 

 

INPUT: 

 

- ``V`` -- The vector space 

 

- ``d`` -- (Optional, default: ``None``) the minimum distance of the 

code, if known. This is an optional parameter. 

 

.. note:: 

 

The veracity of the minimum distance ``d``, if provided, is not 

checked. 

 

EXAMPLES:: 

 

sage: V = VectorSpace(GF(2), 8) 

sage: L = V.subspace([[1,1,1,1,0,0,0,0],[0,0,0,0,1,1,1,1]]) 

sage: C = LinearCodeFromVectorSpace(L) 

doctest:...: DeprecationWarning: LinearCodeFromVectorSpace is deprecated. Simply call LinearCode with your vector space instead. 

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

sage: C.generator_matrix() 

[1 1 1 1 0 0 0 0] 

[0 0 0 0 1 1 1 1] 

sage: C.minimum_distance() 

4 

 

Here, we provide the minimum distance of the code.:: 

 

sage: C = LinearCodeFromVectorSpace(L, d=4) 

sage: C.minimum_distance() 

4 

""" 

from sage.misc.superseded import deprecation 

deprecation(21165, "LinearCodeFromVectorSpace is deprecated. Simply call LinearCode with your vector space instead.") 

F = V.base_ring() 

B = V.basis() 

n = len(B[0].list()) 

k = len(B) 

MS = MatrixSpace(F,k,n) 

G = MS([B[i].list() for i in range(k)]) 

return LinearCode(G, d=d) 

 

 

 

 

############################ linear codes python class ######################## 

 

class LinearCode(AbstractLinearCode): 

r""" 

Linear codes over a finite field or finite ring, represented using a 

generator matrix. 

 

This class should be used for arbitrary and unstructured linear codes. This 

means that basic operations on the code, such as the computation of the 

minimum distance, will use generic, slow algorithms. 

 

If you are looking for constructing a code from a more specific family, see 

if the family has been implemented by investigating `codes.<tab>`. These 

more specific classes use properties particular to that family to allow 

faster algorithms, and could also have family-specific methods. 

 

See :wikipedia:`Linear_code` for more information on unstructured linear codes. 

 

INPUT: 

 

- ``generator`` -- a generator matrix over a finite field (``G`` can be 

defined over a finite ring but the matrices over that ring must have 

certain attributes, such as ``rank``); or a code over a finite field 

 

- ``d`` -- (optional, default: ``None``) the minimum distance of the code 

 

.. NOTE:: 

 

The veracity of the minimum distance ``d``, if provided, is not 

checked. 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C 

[7, 4] linear code over GF(2) 

sage: C.base_ring() 

Finite Field of size 2 

sage: C.dimension() 

4 

sage: C.length() 

7 

sage: C.minimum_distance() 

3 

sage: C.spectrum() 

[1, 0, 0, 7, 7, 0, 0, 1] 

sage: C.weight_distribution() 

[1, 0, 0, 7, 7, 0, 0, 1] 

 

The minimum distance of the code, if known, can be provided as an 

optional parameter.:: 

 

sage: C = LinearCode(G, d=3) 

sage: C.minimum_distance() 

3 

 

Another example.:: 

 

sage: MS = MatrixSpace(GF(5),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C 

[7, 4] linear code over GF(5) 

 

Providing a code as the parameter in order to "forget" its structure (see 

:trac:`20198`):: 

 

sage: C = codes.GeneralizedReedSolomonCode(GF(23).list(), 12) 

sage: LinearCode(C) 

[23, 12] linear code over GF(23) 

 

Another example:: 

 

sage: C = codes.HammingCode(GF(7), 3) 

sage: C 

[57, 54] Hamming Code over GF(7) 

sage: LinearCode(C) 

[57, 54] linear code over GF(7) 

 

AUTHORS: 

 

- David Joyner (11-2005) 

- Charles Prior (03-2016): :trac:`20198`, LinearCode from a code 

""" 

def __init__(self, generator, d=None): 

r""" 

See the docstring for :meth:`LinearCode`. 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) # indirect doctest 

sage: C 

[7, 4] linear code over GF(2) 

 

The minimum distance of the code, if known, can be provided as an 

optional parameter.:: 

 

sage: C = LinearCode(G, d=3) 

sage: C.minimum_distance() 

3 

 

TESTS:: 

 

sage: C = codes.HammingCode(GF(2), 3) 

sage: TestSuite(C).run() 

 

Check that it works even with input matrix with non full rank (see 

:trac:`17452`):: 

 

sage: K.<a> = GF(4) 

sage: G = matrix([[a, a + 1, 1, a + 1, 1, 0, 0], 

....: [0, a, a + 1, 1, a + 1, 1, 0], 

....: [0, 0, a, a + 1, 1, a + 1, 1], 

....: [a + 1, 0, 1, 0, a + 1, 1, a + 1], 

....: [a, a + 1, a + 1, 0, 0, a + 1, 1], 

....: [a + 1, a, a, 1, 0, 0, a + 1], 

....: [a, a + 1, 1, a + 1, 1, 0, 0]]) 

sage: C = LinearCode(G) 

sage: C.basis() 

[ 

(1, 0, 0, a + 1, 0, 1, 0), 

(0, 1, 0, 0, a + 1, 0, 1), 

(0, 0, 1, a, a + 1, a, a + 1) 

] 

sage: C.minimum_distance() 

3 

 

We can construct a linear code directly from a vector space 

sage: VS = matrix(GF(2), [[1,0,1],\ 

[1,0,1]]).row_space() 

sage: C = LinearCode(VS); C 

[3, 1] linear code over GF(2) 

 

Forbid the zero vector space (see :trac:`17452` and :trac:`6486`):: 

 

sage: G = matrix(GF(2), [[0,0,0]]) 

sage: C = LinearCode(G) 

Traceback (most recent call last): 

... 

ValueError: this linear code contains no non-zero vector 

""" 

 

base_ring = generator.base_ring() 

if not base_ring.is_field(): 

raise ValueError("'generator' must be defined on a field (not a ring)") 

 

try: 

basis = None 

if hasattr(generator,"nrows"): # generator matrix case 

if generator.rank() < generator.nrows(): 

basis = generator.row_space().basis() 

else: 

basis = generator.basis() # vector space etc. case 

if not basis is None: 

from sage.matrix.constructor import matrix 

generator = matrix(base_ring, basis) 

if generator.nrows() == 0: 

raise ValueError("this linear code contains no non-zero vector") 

except AttributeError: 

# Assume input is an AbstractLinearCode, extract its generator matrix 

generator = generator.generator_matrix() 

 

super(LinearCode, self).__init__(base_ring, generator.ncols(), "GeneratorMatrix", "Syndrome") 

self._generator_matrix = generator 

self._dimension = generator.rank() 

self._minimum_distance = d 

 

def _repr_(self): 

r""" 

See the docstring for :meth:`LinearCode`. 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: C # indirect doctest 

[7, 4] linear code over GF(2) 

""" 

R = self.base_ring() 

if R in Fields(): 

return "[%s, %s] linear code over GF(%s)"%(self.length(), self.dimension(), R.cardinality()) 

else: 

return "[%s, %s] linear code over %s"%(self.length(), self.dimension(), R) 

 

def _latex_(self): 

""" 

Return a latex representation of ``self``. 

 

EXAMPLES:: 

 

sage: MS = MatrixSpace(GF(2),4,7) 

sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: latex(C) 

[7, 4]\textnormal{ Linear code over }\Bold{F}_{2} 

""" 

return "[%s, %s]\\textnormal{ Linear code over }%s"\ 

% (self.length(), self.dimension(), self.base_ring()._latex_()) 

 

def __hash__(self): 

r""" 

Returns the hash value of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: hash(C) #random 

9015017528451745710 

 

If ``C1`` and ``C2`` are two codes which only differ by the 

coefficients of their generator matrices, their hashes are 

different (we check that the bug found in :trac:`18813` is 

fixed):: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C1 = LinearCode(G) 

sage: G = Matrix(GF(2), [[1,0,0,1,0,1,0],[0,1,0,0,1,0,0],[0,0,1,1,0,1,0],[0,0,0,0,0,0,1]]) 

sage: C2 = LinearCode(G) 

sage: hash(C1) != hash(C2) 

True 

""" 

Str = str(self) 

G = self.generator_matrix() 

return hash((Str, G)) ^ hash(Str) ^ hash(G) 

 

def generator_matrix(self, encoder_name=None, **kwargs): 

r""" 

Returns a generator matrix of ``self``. 

 

INPUT: 

 

- ``encoder_name`` -- (default: ``None``) name of the encoder which will be 

used to compute the generator matrix. ``self._generator_matrix`` 

will be returned if default value is kept. 

 

- ``kwargs`` -- all additional arguments are forwarded to the construction of the 

encoder that is used. 

 

EXAMPLES:: 

 

sage: G = matrix(GF(3),2,[1,-1,1,-1,1,1]) 

sage: code = LinearCode(G) 

sage: code.generator_matrix() 

[1 2 1] 

[2 1 1] 

""" 

if encoder_name is None or encoder_name is 'GeneratorMatrix': 

g = self._generator_matrix 

else: 

g = super(LinearCode, self).generator_matrix(encoder_name, **kwargs) 

g.set_immutable() 

return g 

 

 

 

 

 

 

 

 

 

####################### encoders ############################### 

class LinearCodeGeneratorMatrixEncoder(Encoder): 

r""" 

Encoder based on generator_matrix for Linear codes. 

 

This is the default encoder of a generic linear code, and should never be used for other codes than 

:class:`LinearCode`. 

 

INPUT: 

 

- ``code`` -- The associated :class:`LinearCode` of this encoder. 

""" 

 

def __init__(self, code): 

r""" 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C) 

sage: E 

Generator matrix-based encoder for [7, 4] linear code over GF(2) 

""" 

super(LinearCodeGeneratorMatrixEncoder, self).__init__(code) 

 

def __eq__(self, other): 

r""" 

Tests equality between LinearCodeGeneratorMatrixEncoder objects. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: E1 = LinearCode(G).encoder() 

sage: E2 = LinearCode(G).encoder() 

sage: E1 == E2 

True 

""" 

return isinstance(other, LinearCodeGeneratorMatrixEncoder)\ 

and self.code() == other.code() 

 

def _repr_(self): 

r""" 

Returns a string representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C) 

sage: E 

Generator matrix-based encoder for [7, 4] linear code over GF(2) 

""" 

return "Generator matrix-based encoder for %s" % self.code() 

 

def _latex_(self): 

r""" 

Returns a latex representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C) 

sage: latex(E) 

\textnormal{Generator matrix-based encoder for }[7, 4]\textnormal{ Linear code over }\Bold{F}_{2} 

""" 

return "\\textnormal{Generator matrix-based encoder for }%s" % self.code()._latex_() 

 

@cached_method 

def generator_matrix(self): 

r""" 

Returns a generator matrix of the associated code of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C) 

sage: E.generator_matrix() 

[1 1 1 0 0 0 0] 

[1 0 0 1 1 0 0] 

[0 1 0 1 0 1 0] 

[1 1 0 1 0 0 1] 

""" 

g = self.code().generator_matrix() 

g.set_immutable() 

return g 

 

 

 

 

 

 

 

 

 

 

class LinearCodeParityCheckEncoder(Encoder): 

r""" 

Encoder based on :meth:`parity_check_matrix` for Linear codes. 

 

It constructs the generator matrix through the parity check matrix. 

 

INPUT: 

 

- ``code`` -- The associated code of this encoder. 

""" 

 

def __init__(self, code): 

r""" 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeParityCheckEncoder(C) 

doctest:...: DeprecationWarning: LinearCodeParityCheckEncoder is now deprecated. Please use LinearCodeSystematicEncoder instead. 

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

sage: E 

Parity check matrix-based encoder for [7, 4] linear code over GF(2) 

""" 

from sage.misc.superseded import deprecation 

deprecation(20835, "LinearCodeParityCheckEncoder is now deprecated. Please use LinearCodeSystematicEncoder instead.") 

super(LinearCodeParityCheckEncoder, self).__init__(code) 

 

def _repr_(self): 

r""" 

Return a string representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeParityCheckEncoder(C) 

doctest:...: DeprecationWarning: LinearCodeParityCheckEncoder is now deprecated. Please use LinearCodeSystematicEncoder instead. 

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

sage: E 

Parity check matrix-based encoder for [7, 4] linear code over GF(2) 

""" 

return "Parity check matrix-based encoder for %s" % self.code() 

 

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeParityCheckEncoder(C) 

doctest:...: DeprecationWarning: LinearCodeParityCheckEncoder is now deprecated. Please use LinearCodeSystematicEncoder instead. 

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

sage: latex(E) 

\textnormal{Parity check matrix-based encoder for }[7, 4]\textnormal{ Linear code over }\Bold{F}_{2} 

""" 

return "\\textnormal{Parity check matrix-based encoder for }%s" % self.code()._latex_() 

 

@cached_method 

def generator_matrix(self): 

r""" 

Returns a generator matrix of the associated code of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeParityCheckEncoder(C) 

doctest:...: DeprecationWarning: LinearCodeParityCheckEncoder is now deprecated. Please use LinearCodeSystematicEncoder instead. 

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

sage: E.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 1 1 0] 

[0 0 0 1 1 1 1] 

""" 

g = self.code().parity_check_matrix().right_kernel_matrix() 

g.set_immutable() 

return g 

 

 

 

 

 

 

 

 

 

 

class LinearCodeSystematicEncoder(Encoder): 

r""" 

Encoder based on a generator matrix in systematic form for Linear codes. 

 

To encode an element of its message space, this encoder first builds a 

generator matrix in systematic form. What is called systematic form here 

is the reduced row echelon form of a matrix, which is not necessarily 

`[I \vert H]`, where `I` is the identity block and `H` the parity block. 

One can refer to :meth:`LinearCodeSystematicEncoder.generator_matrix` 

for a concrete example. 

Once such a matrix has been computed, it is used to encode any message 

into a codeword. 

 

This encoder can also serve as the default encoder of a code defined by a 

parity check matrix: if the :class:`LinearCodeSystematicEncoder` detects 

that it is the default encoder, it computes a generator matrix as the 

reduced row echelon form of the right kernel of the parity check matrix. 

 

INPUT: 

 

- ``code`` -- The associated code of this encoder. 

 

- ``systematic_positions`` -- (default: ``None``) the positions in codewords that 

should correspond to the message symbols. A list of `k` distinct integers in 

the range 0 to `n-1` where `n` is the length of the code and `k` its 

dimension. The 0th symbol of a message will then be at position 

``systematic_positions[0]``, the 1st index at position 

``systematic_positions[1]``, etc. A ``ValueError`` is raised at 

construction time if the supplied indices do not form an information set. 

 

EXAMPLES: 

 

The following demonstrates the basic usage of :class:`LinearCodeSystematicEncoder`:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0,0],\ 

[1,0,0,1,1,0,0,0],\ 

[0,1,0,1,0,1,0,0],\ 

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

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E.generator_matrix() 

[1 0 0 0 0 1 1 1] 

[0 1 0 0 1 0 1 1] 

[0 0 1 0 1 1 0 0] 

[0 0 0 1 1 1 1 1] 

sage: E2 = codes.encoders.LinearCodeSystematicEncoder(C, systematic_positions=[5,4,3,2]) 

sage: E2.generator_matrix() 

[1 0 0 0 0 1 1 1] 

[0 1 0 0 1 0 1 1] 

[1 1 0 1 0 0 1 1] 

[1 1 1 0 0 0 0 0] 

 

An error is raised if one specifies systematic positions which do not form 

an information set:: 

 

sage: E3 = codes.encoders.LinearCodeSystematicEncoder(C, systematic_positions=[0,1,6,7]) 

Traceback (most recent call last): 

... 

ValueError: systematic_positions are not an information set 

 

 

We exemplify how to use :class:`LinearCodeSystematicEncoder` as the default 

encoder. The following class is the dual of the repetition code:: 

 

sage: class DualRepetitionCode(sage.coding.linear_code.AbstractLinearCode): 

....: def __init__(self, field, length): 

....: sage.coding.linear_code.AbstractLinearCode.__init__(self,field, length, "Systematic", "Syndrome") 

....: 

....: def parity_check_matrix(self): 

....: return Matrix(self.base_field(), [1]*self.length()) 

....: 

....: def _repr_(self): 

....: return "Dual of the [%d, 1] Repetition Code over GF(%s)" % (self.length(), self.base_field().cardinality()) 

....: 

sage: DualRepetitionCode(GF(3), 5).generator_matrix() 

[1 0 0 0 2] 

[0 1 0 0 2] 

[0 0 1 0 2] 

[0 0 0 1 2] 

 

 

An exception is thrown if :class:`LinearCodeSystematicEncoder` is the default encoder but no 

parity check matrix has been specified for the code:: 

 

sage: class BadCodeFamily(sage.coding.linear_code.AbstractLinearCode): 

....: def __init__(self, field, length): 

....: sage.coding.linear_code.AbstractLinearCode.__init__(self, field, length, "Systematic", "Syndrome") 

....: 

....: def _repr_(self): 

....: return "I am a badly defined code" 

....: 

sage: BadCodeFamily(GF(3), 5).generator_matrix() 

Traceback (most recent call last): 

... 

ValueError: a parity check matrix must be specified if LinearCodeSystematicEncoder is the default encoder 

""" 

 

def __init__(self, code, systematic_positions=None): 

r""" 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E 

Systematic encoder for [7, 4] linear code over GF(2) 

""" 

super(LinearCodeSystematicEncoder, self).__init__(code) 

self._systematic_positions = tuple(systematic_positions) if systematic_positions else None 

if systematic_positions: 

# Test that systematic_positions consists of integers in the right 

# range. We test that len(systematic_positions) = code.dimension() 

# in self.generator_matrix() to avoid possible infinite recursion. 

if (not all( e in ZZ and e >= 0 and e < code.length() for e in systematic_positions)) \ 

or len(systematic_positions) != len(set(systematic_positions)): 

raise ValueError("systematic positions must be a tuple of distinct integers in the range 0 to n-1 where n is the length of the code") 

# Test that the systematic positions are an information set 

self.generator_matrix() 

 

 

def __eq__(self, other): 

r""" 

Tests equality between LinearCodeSystematicEncoder objects. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: E1 = codes.encoders.LinearCodeSystematicEncoder(LinearCode(G)) 

sage: E2 = codes.encoders.LinearCodeSystematicEncoder(LinearCode(G)) 

sage: E1 == E2 

True 

sage: E1.systematic_positions() 

(0, 1, 2) 

sage: E3 = codes.encoders.LinearCodeSystematicEncoder(LinearCode(G), systematic_positions=(2,5,6)) 

sage: E3.systematic_positions() 

(2, 5, 6) 

sage: E1 == E3 

False 

""" 

return isinstance(other, LinearCodeSystematicEncoder)\ 

and self.code() == other.code()\ 

and self.systematic_positions() == other.systematic_positions() 

 

def _repr_(self): 

r""" 

Return a string representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E 

Systematic encoder for [7, 4] linear code over GF(2) 

""" 

return "Systematic encoder for %s" % self.code() 

 

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: latex(E) 

\textnormal{Systematic encoder for }[7, 4]\textnormal{ Linear code over }\Bold{F}_{2} 

""" 

return "\\textnormal{Systematic encoder for }%s" % self.code()._latex_() 

 

@cached_method 

def generator_matrix(self): 

r""" 

Returns a generator matrix in systematic form of the associated code of ``self``. 

 

Systematic form here means that a subsets of the columns of the matrix 

forms the identity matrix. 

 

.. NOTE:: 

 

The matrix returned by this method will not necessarily be `[I \vert H]`, where `I` 

is the identity block and `H` the parity block. If one wants to know which columns 

create the identity block, one can call :meth:`systematic_positions` 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],\ 

[1,0,0,1,1,0,0],\ 

[0,1,0,1,0,1,0],\ 

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

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[0 0 1 0 1 1 0] 

[0 0 0 1 1 1 1] 

 

We can ask for different systematic positions:: 

 

sage: E2 = codes.encoders.LinearCodeSystematicEncoder(C, systematic_positions=[5,4,3,2]) 

sage: E2.generator_matrix() 

[1 0 0 0 0 1 1] 

[0 1 0 0 1 0 1] 

[1 1 0 1 0 0 1] 

[1 1 1 0 0 0 0] 

 

Another example where there is no generator matrix of the form `[I \vert H]`:: 

 

sage: G = Matrix(GF(2), [[1,1,0,0,1,0,1],\ 

[1,1,0,0,1,0,0],\ 

[0,0,1,0,0,1,0],\ 

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

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E.generator_matrix() 

[1 1 0 0 0 1 0] 

[0 0 1 0 0 1 0] 

[0 0 0 0 1 1 0] 

[0 0 0 0 0 0 1] 

""" 

C = self.code() 

# This if statement detects if this encoder is itself the default encoder. 

# In this case, attempt building the generator matrix from the parity 

# check matrix 

if hasattr(self, "_use_pc_matrix"): 

if self._use_pc_matrix == 1: 

self._use_pc_matrix = 2 

return C.parity_check_matrix().right_kernel_matrix() 

else: 

raise ValueError("a parity check matrix must be specified if LinearCodeSystematicEncoder is the default encoder") 

else: 

self._use_pc_matrix = 1 

M = copy(C.generator_matrix()) 

if not self._systematic_positions: 

M.echelonize() 

else: 

k = M.nrows() # it is important that k is *not* computed as C.dimension() to avoid possible cyclic dependency 

if len(self._systematic_positions) != k: 

raise ValueError("systematic_positions must be a tuple of length equal to the dimension of the code") 

# Permute the columns of M and bring to reduced row echelon formb 

perm = self.systematic_permutation() 

M.permute_columns(perm) 

M.echelonize() 

if M[:,:k].is_singular(): 

raise ValueError("systematic_positions are not an information set") 

M.permute_columns(perm.inverse()) 

M.set_immutable() 

return M 

 

def systematic_permutation(self): 

r""" 

Returns a permutation which would take the systematic positions into [0,..,k-1] 

 

EXAMPLES:: 

 

sage: C = LinearCode(matrix(GF(2), [[1,0,0,0,1,1,0],\ 

[0,1,0,1,0,1,0],\ 

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

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E.systematic_positions() 

(0, 1, 6) 

sage: E.systematic_permutation() 

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

""" 

n = self.code().length() 

systematic_positions = self.systematic_positions() 

k = len(systematic_positions) 

lp = [ None ]*n 

for (i,j) in zip(range(k), systematic_positions): 

lp[i] = j 

j = k 

set_sys_pos = set(systematic_positions) 

for i in range(n): 

if not i in set_sys_pos: 

lp[j] = i 

j += 1 

from sage.combinat.permutation import Permutation 

return Permutation([1 + e for e in lp]) 

 

def systematic_positions(self): 

r""" 

Returns a tuple containing the indices of the columns which form an 

identity matrix when the generator matrix is in systematic form. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],\ 

[1,0,0,1,1,0,0],\ 

[0,1,0,1,0,1,0],\ 

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

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E.systematic_positions() 

(0, 1, 2, 3) 

 

We take another matrix with a less nice shape:: 

 

sage: G = Matrix(GF(2), [[1,1,0,0,1,0,1],\ 

[1,1,0,0,1,0,0],\ 

[0,0,1,0,0,1,0],\ 

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

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C) 

sage: E.systematic_positions() 

(0, 2, 4, 6) 

 

The systematic positions correspond to the positions which carry information in a codeword:: 

 

sage: MS = E.message_space() 

sage: m = MS.random_element() 

sage: c = m * E.generator_matrix() 

sage: pos = E.systematic_positions() 

sage: info = MS([c[i] for i in pos]) 

sage: m == info 

True 

 

When constructing a systematic encoder with specific systematic 

positions, then it is guaranteed that this method returns exactly those 

positions (even if another choice might also be systematic):: 

 

sage: G = Matrix(GF(2), [[1,0,0,0],\ 

[0,1,0,0],\ 

[0,0,1,1]]) 

sage: C = LinearCode(G) 

sage: E = codes.encoders.LinearCodeSystematicEncoder(C, systematic_positions=[0,1,3]) 

sage: E.systematic_positions() 

(0, 1, 3) 

""" 

return self._systematic_positions if self._systematic_positions else self.generator_matrix().pivots() 

 

 

 

 

 

 

 

 

 

 

 

####################### decoders ############################### 

class LinearCodeSyndromeDecoder(Decoder): 

r""" 

Constructs a decoder for Linear Codes based on syndrome lookup table. 

 

The decoding algorithm works as follows: 

 

- First, a lookup table is built by computing the syndrome of every error 

pattern of weight up to ``maximum_error_weight``. 

- Then, whenever one tries to decode a word ``r``, the syndrome of ``r`` is 

computed. The corresponding error pattern is recovered from the 

pre-computed lookup table. 

- Finally, the recovered error pattern is subtracted from ``r`` to recover 

the original word. 

 

``maximum_error_weight`` need never exceed the covering radius of the code, 

since there are then always lower-weight errors with the same syndrome. If 

one sets ``maximum_error_weight`` to a value greater than the covering 

radius, then the covering radius will be determined while building the 

lookup-table. This lower value is then returned if you query 

``decoding_radius`` after construction. 

 

If ``maximum_error_weight`` is left unspecified or set to a number at least 

the covering radius of the code, this decoder is complete, i.e. it decodes 

every vector in the ambient space. 

 

.. NOTE:: 

 

Constructing the lookup table takes time exponential in the length of the 

code and the size of the code's base field. Afterwards, the individual 

decodings are fast. 

 

INPUT: 

 

- ``code`` -- A code associated to this decoder 

 

- ``maximum_error_weight`` -- (default: ``None``) the maximum number of 

errors to look for when building the table. An error is raised if it is 

set greater than `n-k`, since this is an upper bound on the covering 

radius on any linear code. If ``maximum_error_weight`` is kept 

unspecified, it will be set to `n - k`, where `n` is the length of 

``code`` and `k` its dimension. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: D 

Syndrome decoder for [9, 3] linear code over GF(3) handling errors of weight up to 4 

 

If one wants to correct up to a lower number of errors, one can do as follows:: 

 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, maximum_error_weight=2) 

sage: D 

Syndrome decoder for [9, 3] linear code over GF(3) handling errors of weight up to 2 

 

If one checks the list of types of this decoder before constructing it, 

one will notice it contains the keyword ``dynamic``. 

Indeed, the behaviour of the syndrome decoder depends on the maximum 

error weight one wants to handle, and how it compares to the minimum 

distance and the covering radius of ``code``. 

In the following examples, we illustrate this property by computing 

different instances of syndrome decoder for the same code. 

 

We choose the following linear code, whose covering radius equals to 4 

and minimum distance to 5 (half the minimum distance is 2):: 

 

sage: G = matrix(GF(5), [[1, 0, 0, 0, 0, 4, 3, 0, 3, 1, 0], 

....: [0, 1, 0, 0, 0, 3, 2, 2, 3, 2, 1], 

....: [0, 0, 1, 0, 0, 1, 3, 0, 1, 4, 1], 

....: [0, 0, 0, 1, 0, 3, 4, 2, 2, 3, 3], 

....: [0, 0, 0, 0, 1, 4, 2, 3, 2, 2, 1]]) 

sage: C = LinearCode(G) 

 

In the following examples, we illustrate how the choice of 

``maximum_error_weight`` influences the types of the instance of 

syndrome decoder, alongside with its decoding radius. 

 

We build a first syndrome decoder, and pick a ``maximum_error_weight`` 

smaller than both the covering radius and half the minimum distance:: 

 

sage: D = C.decoder("Syndrome", maximum_error_weight = 1) 

sage: D.decoder_type() 

{'always-succeed', 'bounded_distance', 'hard-decision'} 

sage: D.decoding_radius() 

1 

 

In that case, we are sure the decoder will always succeed. It is also 

a bounded distance decoder. 

 

We now build another syndrome decoder, and this time, 

``maximum_error_weight`` is chosen to be bigger than half the minimum distance, 

but lower than the covering radius:: 

 

sage: D = C.decoder("Syndrome", maximum_error_weight = 3) 

sage: D.decoder_type() 

{'bounded_distance', 'hard-decision', 'might-error'} 

sage: D.decoding_radius() 

3 

 

Here, we still get a bounded distance decoder. 

But because we have a maximum error weight bigger than half the 

minimum distance, we know it might return a codeword which was not 

the original codeword. 

 

And now, we build a third syndrome decoder, whose ``maximum_error_weight`` 

is bigger than both the covering radius and half the minimum distance:: 

 

sage: D = C.decoder("Syndrome", maximum_error_weight = 5) 

sage: D.decoder_type() 

{'complete', 'hard-decision', 'might-error'} 

sage: D.decoding_radius() 

4 

 

In that case, the decoder might still return an unexpected codeword, but 

it is now complete. Note the decoding radius is equal to 4: it was 

determined while building the syndrome lookup table that any error with 

weight more than 4 will be decoded incorrectly. That is because the covering 

radius for the code is 4. 

 

The minimum distance and the covering radius are both determined while 

computing the syndrome lookup table. They user did not explicitly ask to 

compute these on the code ``C``. The dynamic typing of the syndrome decoder 

might therefore seem slightly surprising, but in the end is quite 

informative. 

""" 

 

def __init__(self, code, maximum_error_weight=None): 

r""" 

TESTS: 

 

If ``maximum_error_weight`` is greater or equal than `n-k`, where `n` 

is ``code``'s length, and `k` is ``code``'s dimension, 

an error is raised:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, 42) 

Traceback (most recent call last): 

... 

ValueError: maximum_error_weight has to be less than code's length minus its dimension 

 

The Syndrome Decoder of a Hamming code should have types 

``minimum-distance`` and ``always-succeed`` (see :trac:`20898`):: 

 

sage: C = codes.HammingCode(GF(5), 3) 

sage: D = C.decoder("Syndrome") 

sage: C.minimum_distance() 

3 

sage: D.maximum_error_weight() 

1 

sage: D.decoder_type() 

{'always-succeed', 'complete', 'hard-decision', 'minimum-distance'} 

""" 

n_minus_k = code.length() - code.dimension() 

if maximum_error_weight is None: 

self._maximum_error_weight = n_minus_k 

elif not isinstance(maximum_error_weight, (Integer, int)): 

raise ValueError("maximum_error_weight has to be a Sage integer or a Python int") 

elif maximum_error_weight > n_minus_k: 

raise ValueError("maximum_error_weight has to be less than code's length minus its dimension") 

else: 

self._maximum_error_weight = maximum_error_weight 

super(LinearCodeSyndromeDecoder, self).__init__(code, code.ambient_space(),\ 

code._default_encoder_name) 

self._lookup_table = self._build_lookup_table() 

 

def __eq__(self, other): 

r""" 

Tests equality between LinearCodeSyndromeDecoder objects. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: D1 = codes.decoders.LinearCodeSyndromeDecoder(LinearCode(G)) 

sage: D2 = codes.decoders.LinearCodeSyndromeDecoder(LinearCode(G)) 

sage: D1 == D2 

True 

""" 

return isinstance(other, LinearCodeSyndromeDecoder)\ 

and self.code() == other.code()\ 

and self.maximum_error_weight() == other.maximum_error_weight() 

 

def _repr_(self): 

r""" 

Return a string representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: D 

Syndrome decoder for [9, 3] linear code over GF(3) handling errors of weight up to 4 

""" 

return "Syndrome decoder for %s handling errors of weight up to %s" % (self.code(), self.maximum_error_weight()) 

 

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: latex(D) 

\textnormal{Syndrome decoder for [9, 3]\textnormal{ Linear code over }\Bold{F}_{3} handling errors of weight up to 4} 

""" 

return "\\textnormal{Syndrome decoder for %s handling errors of weight up to %s}" % (self.code()._latex_(), self.maximum_error_weight()) 

 

@cached_method 

def _build_lookup_table(self): 

r""" 

Builds lookup table for all possible error patterns of weight up to :meth:`maximum_error_weight`. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3),[ 

....: [1, 0, 0, 0, 2, 2, 1, 1], 

....: [0, 1, 0, 0, 0, 0, 1, 1], 

....: [0, 0, 1, 0, 2, 0, 0, 2], 

....: [0, 0, 0, 1, 0, 2, 0, 1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, maximum_error_weight = 1) 

sage: D._build_lookup_table() 

{(0, 0, 0, 0): (0, 0, 0, 0, 0, 0, 0, 0), 

(0, 0, 0, 1): (0, 0, 0, 0, 1, 0, 0, 0), 

(0, 0, 0, 2): (0, 0, 0, 0, 2, 0, 0, 0), 

(0, 0, 1, 0): (0, 0, 1, 0, 0, 0, 0, 0), 

(0, 0, 1, 2): (0, 0, 0, 0, 0, 0, 0, 1), 

(0, 0, 2, 0): (0, 0, 2, 0, 0, 0, 0, 0), 

(0, 0, 2, 1): (0, 0, 0, 0, 0, 0, 0, 2), 

(0, 1, 0, 0): (0, 1, 0, 0, 0, 0, 0, 0), 

(0, 1, 1, 2): (0, 0, 0, 0, 0, 0, 2, 0), 

(0, 2, 0, 0): (0, 2, 0, 0, 0, 0, 0, 0), 

(0, 2, 2, 1): (0, 0, 0, 0, 0, 0, 1, 0), 

(1, 0, 0, 0): (1, 0, 0, 0, 0, 0, 0, 0), 

(1, 2, 0, 2): (0, 0, 0, 0, 0, 1, 0, 0), 

(1, 2, 2, 0): (0, 0, 0, 1, 0, 0, 0, 0), 

(2, 0, 0, 0): (2, 0, 0, 0, 0, 0, 0, 0), 

(2, 1, 0, 1): (0, 0, 0, 0, 0, 2, 0, 0), 

(2, 1, 1, 0): (0, 0, 0, 2, 0, 0, 0, 0)} 

 

TESTS: 

 

Check that :trac:`24114` is fixed:: 

 

sage: R.<x> = PolynomialRing(GF(3)) 

sage: f = x^2 + x + 2 

sage: K.<a> = f.root_field() 

sage: H = Matrix(K,[[1,2,1],[2*a+1,a,1]]) 

sage: C = codes.from_parity_check_matrix(H) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: D.syndrome_table()  

{(0, 0): (0, 0, 0), 

(0, 1): (0, 1, 0), 

(0, 2): (0, 2, 0), 

(0, a): (0, a, 0), 

... 

(2*a + 2, 2*a): (0, 0, 2), 

(2*a + 2, 2*a + 1): (2*a + 2, 2*a + 1, 0), 

(2*a + 2, 2*a + 2): (2*a + 2, 2*a + 2, 0)} 

""" 

t = self._maximum_error_weight 

self._code_covering_radius = None 

self._code_minimum_distance = None 

self._decoder_type = copy(self._decoder_type) 

self._decoder_type.remove("dynamic") 

C = self.code() 

n = C.length() 

k = C.dimension() 

H = C.parity_check_matrix() 

F = C.base_ring() 

l = list(F) 

zero = F.zero() 

#Builds a list of generators of all error positions for all 

#possible error weights 

if zero in l: 

l.remove(zero) 

# Remember to include the no-error-vector to handle codes of minimum 

# distance 1 gracefully 

zero_syndrome = vector(F,[F.zero()]*(n-k)) 

zero_syndrome.set_immutable() 

lookup = { zero_syndrome : vector(F,[F.zero()]*n) } 

error_position_tables = [cartesian_product([l]*i) for i in range(1, t+1)] 

first_collision = True 

#Filling the lookup table 

for i in range(1, t+1): 

stop = True 

patterns = Subsets(range(n), i) 

basic = vector(F, n) 

for p in patterns: 

for error in error_position_tables[i-1]: 

ind = 0 

e = copy(basic) 

for pos in p: 

e[pos] = error[ind] 

ind += 1 

s = H * e 

s.set_immutable() 

try: 

e_cur = lookup[s] 

#if this is the first time we see a collision 

#we learn the minimum distance of the code 

if first_collision: 

self._code_minimum_distance = e.hamming_weight() + e_cur.hamming_weight() 

first_collision = False 

except KeyError: 

stop = False 

lookup[s] = copy(e) 

#if we reached the early termination condition 

#we learn the covering radius of the code 

if stop: 

self._code_covering_radius = i - 1 

self._maximum_error_weight = self._code_covering_radius 

break 

# Update decoder types depending on whether we are decoding up to covering radius 

if self._code_covering_radius: 

self._decoder_type.add("complete") 

else: 

self._decoder_type.add("bounded_distance") 

# Update decoder types depending on whether we are decoding beyond d/2 

if self._code_minimum_distance: 

if self._maximum_error_weight == (self._code_minimum_distance-1)//2: 

self._decoder_type.update({"minimum-distance","always-succeed"}) 

else: 

# then t > (d-1)/2 

self._decoder_type.add("might-error") 

else: 

self._decoder_type.add("always-succeed") 

return lookup 

 

 

def decode_to_code(self, r): 

r""" 

Corrects the errors in ``word`` and returns a codeword. 

 

INPUT: 

 

- ``r`` -- a codeword of ``self`` 

 

OUTPUT: 

 

- a vector of ``self``'s message space 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3),[ 

....: [1, 0, 0, 0, 2, 2, 1, 1], 

....: [0, 1, 0, 0, 0, 0, 1, 1], 

....: [0, 0, 1, 0, 2, 0, 0, 2], 

....: [0, 0, 0, 1, 0, 2, 0, 1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, maximum_error_weight = 2) 

sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), 2) 

sage: c = C.random_element() 

sage: r = Chan(c) 

sage: c == D.decode_to_code(r) 

True 

""" 

lookup_table = self.syndrome_table() 

s = self.code().parity_check_matrix() * r 

s.set_immutable() 

if s.is_zero(): 

return r 

err = lookup_table[s] 

r_corr = copy(r) 

for i in range(self.code().length()): 

r_corr[i] = r[i] - err[i] 

return r_corr 

 

def maximum_error_weight(self): 

r""" 

Returns the maximal number of errors a received word can have 

and for which ``self`` is guaranteed to return a most likely codeword. 

 

Same as ``self.decoding_radius``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: D.maximum_error_weight() 

4 

""" 

return self._maximum_error_weight 

 

def decoding_radius(self): 

r""" 

Returns the maximal number of errors a received word can have 

and for which ``self`` is guaranteed to return a most likely codeword. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: D.decoding_radius() 

4 

""" 

return self._maximum_error_weight 

 

def syndrome_table(self): 

r""" 

Return the syndrome lookup table of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeSyndromeDecoder(C) 

sage: D.syndrome_table() 

{(0, 0, 0): (0, 0, 0, 0, 0, 0, 0), 

(0, 0, 1): (0, 0, 0, 1, 0, 0, 0), 

(0, 1, 0): (0, 1, 0, 0, 0, 0, 0), 

(0, 1, 1): (0, 0, 0, 0, 0, 1, 0), 

(1, 0, 0): (1, 0, 0, 0, 0, 0, 0), 

(1, 0, 1): (0, 0, 0, 0, 1, 0, 0), 

(1, 1, 0): (0, 0, 1, 0, 0, 0, 0), 

(1, 1, 1): (0, 0, 0, 0, 0, 0, 1)} 

""" 

return self._lookup_table 

 

 

class LinearCodeNearestNeighborDecoder(Decoder): 

r""" 

Construct a decoder for Linear Codes. This decoder will decode to the 

nearest codeword found. 

 

INPUT: 

 

- ``code`` -- A code associated to this decoder 

""" 

 

def __init__(self, code): 

r""" 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C) 

sage: D 

Nearest neighbor decoder for [7, 4] linear code over GF(2) 

""" 

super(LinearCodeNearestNeighborDecoder, self).__init__(code, code.ambient_space(), \ 

code._default_encoder_name) 

 

def __eq__(self, other): 

r""" 

Tests equality between LinearCodeNearestNeighborDecoder objects. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: D1 = codes.decoders.LinearCodeNearestNeighborDecoder(LinearCode(G)) 

sage: D2 = codes.decoders.LinearCodeNearestNeighborDecoder(LinearCode(G)) 

sage: D1 == D2 

True 

""" 

return isinstance(other, LinearCodeNearestNeighborDecoder)\ 

and self.code() == other.code() 

 

def _repr_(self): 

r""" 

Returns a string representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C) 

sage: D 

Nearest neighbor decoder for [7, 4] linear code over GF(2) 

""" 

return "Nearest neighbor decoder for %s" % self.code() 

 

def _latex_(self): 

r""" 

Returns a latex representation of ``self``. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C) 

sage: latex(D) 

\textnormal{Nearest neighbor decoder for }[7, 4]\textnormal{ Linear code over }\Bold{F}_{2} 

""" 

return "\\textnormal{Nearest neighbor decoder for }%s" % self.code()._latex_() 

 

def decode_to_code(self, r): 

r""" 

Corrects the errors in ``word`` and returns a codeword. 

 

INPUT: 

 

- ``r`` -- a codeword of ``self`` 

 

OUTPUT: 

 

- a vector of ``self``'s message space 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C) 

sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0)) 

sage: w_err = word + vector(GF(2), (1, 0, 0, 0, 0, 0, 0)) 

sage: D.decode_to_code(w_err) 

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

""" 

c_min = self.code().zero() 

h_min = r.hamming_weight() 

for c in self.code(): 

if (c-r).hamming_weight() < h_min: 

h_min = (c-r).hamming_weight() 

c_min = c 

c_min.set_immutable() 

return c_min 

 

def decoding_radius(self): 

r""" 

Return maximal number of errors ``self`` can decode. 

 

EXAMPLES:: 

 

sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]]) 

sage: C = LinearCode(G) 

sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C) 

sage: D.decoding_radius() 

1 

""" 

return (self.code().minimum_distance()-1) // 2 

 

 

 

 

 

 

####################### registration ############################### 

 

LinearCode._registered_encoders["GeneratorMatrix"] = LinearCodeGeneratorMatrixEncoder 

 

LinearCodeSyndromeDecoder._decoder_type = {"hard-decision", "dynamic"} 

LinearCodeNearestNeighborDecoder._decoder_type = {"hard-decision", "always-succeed", "complete"}