File: vspcrow.gi

package info (click to toggle)
gap 4r4p12-2
  • links: PTS
  • area: main
  • in suites: squeeze, wheezy
  • size: 29,584 kB
  • ctags: 7,113
  • sloc: ansic: 98,786; sh: 3,299; perl: 2,263; makefile: 498; asm: 63; awk: 6
file content (1917 lines) | stat: -rw-r--r-- 59,324 bytes parent folder | download | duplicates (3)
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
#############################################################################
##
#W  vspcrow.gi                  GAP library                     Thomas Breuer
##
#H  @(#)$Id: vspcrow.gi,v 4.91.2.3 2005/11/26 06:59:01 gap Exp $
##
#Y  Copyright (C)  1997,  Lehrstuhl D fuer Mathematik,  RWTH Aachen,  Germany
#Y  (C) 1998 School Math and Comp. Sci., University of St.  Andrews, Scotland
#Y  Copyright (C) 2002 The GAP Group
##
##  This file contains methods for row spaces.
##  A row space is a vector space whose elements are row vectors.
##
##  The coefficients field need *not* contain all entries of the row vectors.
##  If it does then the space is a *Gaussian row space*,
##  with better methods to deal with bases.
##  If it does not then the bases use the mechanism of associated bases.
##
##  (See the file `vspcmat.gi' for methods for matrix spaces.)
##
##  For all row spaces, the value of the attribute `DimensionOfVectors' is
##  the length of the row vectors in the space.
##
##  1. Domain constructors for row spaces
##  2. Methods for bases of non-Gaussian row spaces
##  3. Methods for semi-echelonized bases of Gaussian row spaces
##  4. Methods for row spaces
##  5. Methods for full row spaces
##  6. Methods for collections of subspaces of full row spaces
##  7. Methods for mutable bases of Gaussian row spaces
##  8. Methods installed by somebody else without documenting this ...
##
Revision.vspcrow_gi :=
    "@(#)$Id: vspcrow.gi,v 4.91.2.3 2005/11/26 06:59:01 gap Exp $";


#############################################################################
##
##  1. Domain constructors for row spaces
##

#############################################################################
##
#M  LeftModuleByGenerators( <F>, <mat>[, <zerorow>] )
##
##  We keep these special methods since row spaces are the most usual ones,
##  and the explicit construction shall not be slowed down by the call of
##  `CheckForHandlingByNiceBasis'.
##  However, the method installed for the filter `IsNonGaussianRowSpace'
##  would be sufficient to force `IsGaussianRowSpace'.
##
##  Additionally, we guarantee that vector spaces really know that their
##  left acting domain is a division ring.
##
InstallMethod( LeftModuleByGenerators,
    "for division ring and matrix over it",
    IsElmsColls,
    [ IsDivisionRing, IsMatrix ],
    function( F, mat )
    local V;

    if ForAll( mat, row -> IsSubset( F, row ) ) then
      V:= Objectify( NewType( FamilyObj( mat ),
                                  IsGaussianRowSpace
                              and IsAttributeStoringRep ),
                     rec() );
    else
      V:= Objectify( NewType( FamilyObj( mat ),
                                  IsVectorSpace
                              and IsNonGaussianRowSpace
                              and IsRowModule
                              and IsAttributeStoringRep ),
                     rec() );
    fi;

    SetLeftActingDomain( V, F );
    SetGeneratorsOfLeftModule( V, AsList( mat ) );
    SetDimensionOfVectors( V, Length( mat[1] ) );

    return V;
    end );

InstallMethod( LeftModuleByGenerators,
    "for division ring, empty list, and row vector",
    [ IsDivisionRing, IsList and IsEmpty, IsRowVector ],
    function( F, empty, zero )
    local V;

    # Check whether this method is the right one.
    if not IsIdenticalObj( FamilyObj( F ), FamilyObj( zero ) ) then
      TryNextMethod();
    fi;
#T explicit 2nd argument above!

    V:= Objectify( NewType( CollectionsFamily( FamilyObj( F ) ),
                                IsGaussianRowSpace
                            and IsAttributeStoringRep ),
                   rec() );
    SetLeftActingDomain( V, F );
    SetGeneratorsOfLeftModule( V, empty );
    SetZero( V, zero );
    SetDimensionOfVectors( V, Length( zero ) );

    return V;
    end );

InstallMethod( LeftModuleByGenerators,
    "for division ring, matrix over it, and row vector",
    [ IsDivisionRing, IsMatrix, IsRowVector ],
    function( F, mat, zero )
    local V;

    # Check whether this method is the right one.
    if not IsElmsColls( FamilyObj( F ), FamilyObj( mat ) ) then
      TryNextMethod();
    fi;
#T explicit 2nd argument above!

    if ForAll( mat, row -> IsSubset( F, row ) ) then
      V:= Objectify( NewType( FamilyObj( mat ),
                                  IsGaussianRowSpace
                              and IsAttributeStoringRep ),
                     rec() );
    else
      V:= Objectify( NewType( FamilyObj( mat ),
                                  IsVectorSpace
                              and IsNonGaussianRowSpace
                              and IsRowModule
                              and IsAttributeStoringRep ),
                     rec() );
    fi;

    SetLeftActingDomain( V, F );
    SetGeneratorsOfLeftModule( V, AsList( mat ) );
    SetZero( V, zero );
    SetDimensionOfVectors( V, Length( mat[1] ) );

    return V;
    end );


#############################################################################
##
##  2. Methods for bases of non-Gaussian row spaces
##

#############################################################################
##
#M  NiceFreeLeftModuleInfo( <V> )
#M  NiceVector( <V>, <v> )
#M  UglyVector( <V>, <r> )
##
##  The purpose of the check is twofold.
##
##  First, we check whether <V> is a non-Gaussian row space.
##  If yes then it gets the filter `IsNonGaussianRowSpace' that indicates
##  that it is handled via the mechanism of nice bases.
##
##  Second, we set the filter `IsRowModule' if <V> consists of row vectors.
##  If additionally <V> turns out to be Gaussian then we set also the filter
##  `IsGaussianSpace'.
##
InstallHandlingByNiceBasis( "IsNonGaussianRowSpace", rec(
    detect:= function( R, mat, V, zero )
      if IsEmpty( mat ) then
        if     IsRowVector( zero )
           and IsIdenticalObj( FamilyObj( R ), FamilyObj( zero ) ) then
          SetFilterObj( V, IsRowModule );
          if IsDivisionRing( R ) then
            SetFilterObj( V, IsGaussianRowSpace );
            return fail;
          fi;
        fi;
        return false;
      fi;
      if    not IsMatrix( mat )
         or not IsElmsColls( FamilyObj( R ), FamilyObj( mat ) ) then
        return false;
      fi;
      SetFilterObj( V, IsRowModule );
      if ForAll( mat, row -> IsSubset( R, row ) ) then
        if IsDivisionRing( R ) then
          SetFilterObj( V, IsGaussianRowSpace );
        fi;
        return fail;
      fi;
      return true;
      end,

    NiceFreeLeftModuleInfo := function( V )
      local vgens,  # vector space generators of `V'
            F,      # left acting domain of `V'
            K;      # field generated by entries in elements of `V'

      vgens:= GeneratorsOfLeftModule( V );
      F:= LeftActingDomain( V );
      if not IsEmpty( vgens ) then
        K:= ClosureField( F, Concatenation( vgens ) );
#T cheaper way?
        return Basis( AsField( Intersection( K, F ), K ) );
      fi;
      end,

    NiceVector := function( V, v )
      local list, entry, new;
      list:= [];
      for entry in v do
        new:= Coefficients( NiceFreeLeftModuleInfo( V ), entry );
        if new = fail then
          return fail;
        fi;
        Append( list, new );
      od;
      return list;
      end,

    UglyVector := function( V, v )
      local FB,  # basis vectors of the basis of the field extension
            n,   # degree of the field extension
            w,   # associated vector, result
            i;   # loop variable

      FB:= BasisVectors( NiceFreeLeftModuleInfo( V ) );
      n:= Length( FB );
      w:= [];
      for i in [ 1 .. Length( v ) / n ] do
        w[i]:= v{ [ n*(i-1)+1 .. n*i ] } * FB;
      od;
      return w;
      end ) );


#############################################################################
##
##  3. Methods for semi-echelonized bases of Gaussian row spaces
##

#############################################################################
##
#R  IsSemiEchelonBasisOfGaussianRowSpaceRep( <B> )
##
##  A basis of a Gaussian row space is either semi-echelonized or it is a
##  relative basis.
##  (So there is no need for `IsBasisGaussianRowSpace').
##
##  If basis vectors are known then the component `heads' is bound.
##
DeclareRepresentation( "IsSemiEchelonBasisOfGaussianRowSpaceRep",
    IsAttributeStoringRep,
    [ "heads" ] );

InstallTrueMethod( IsSmallList,
    IsList and IsSemiEchelonBasisOfGaussianRowSpaceRep );


#############################################################################
##
#M  LinearCombination( <B>, <coeff> )
##
InstallMethod( LinearCombination, IsCollsElms,
    [ IsBasis and IsSemiEchelonBasisOfGaussianRowSpaceRep, IsRowVector ],
        function( B, coeff )
    if Length(coeff) = 0 then
        TryNextMethod();
    fi;
    return coeff * BasisVectors( B );
    end );


#############################################################################
##
#M  Coefficients( <B>, <v> )  .  method for semi-ech. basis of Gaussian space
##
InstallMethod( Coefficients,
    "for semi-ech. basis of a Gaussian row space, and a row vector",
    IsCollsElms,
    [ IsBasis and IsSemiEchelonBasisOfGaussianRowSpaceRep, IsRowVector ],
    function( B, v )
    local vectors,   # basis vectors of `B'
          heads,     # heads info of `B'
          len,       # length of `v'
          zero,      # zero of the field
          coeff,     # coefficients list, result
          i,         # loop over `v'
          pos;       # heads position

    # Check whether the vector has the right length.
    # (The heads info is not stored before the basis vectors are known.)
    vectors:= BasisVectors( B );
    heads:= B!.heads;
    len:= Length( v );
    if len <> Length( heads ) then
      return fail;
    fi;

    # Preset the coefficients list with zeroes.
    zero:= Zero( v[1] );
    coeff:= List( vectors, x -> zero );

    # Compute the coefficients of the base vectors.
    v:= ShallowCopy( v );
    i:= PositionNot( v, zero );
    while i <= len do
      pos:= heads[i];
      if pos <> 0 then
        coeff[ pos ]:= v[i];
        AddRowVector( v, vectors[ pos ], - v[i] );
      else
        return fail;
      fi;
      i:= PositionNot( v, zero );
    od;

    # Return the coefficients.
    return coeff;
    end );


#############################################################################
##
#F  SiftedVectorForGaussianRowSpace( <F>, <vectors>, <heads>, <v> )
##
##  is the remainder of the row vector <v> after sifting through the
##  (mutable) <F>-basis with besis vectors <vectors> and heads information
##  <heads>.
##
BindGlobal( "SiftedVectorForGaussianRowSpace",
    function( F, vectors, heads, v )
    local zero,    # zero of the field
          i;       # loop over basis vectors

    if Length( heads ) <> Length( v ) or not IsSubset( F, v ) then
      return fail;
    fi;

    zero:= Zero( v[1] );

    # Compute the coefficients of the `B' vectors.
    v:= ShallowCopy( v );
    for i in [ 1 .. Length( heads ) ] do
      if heads[i] <> 0 and v[i] <> zero then
        AddRowVector( v, vectors[ heads[i] ], - v[i] );
      fi;
    od;

    # Return the remainder.
    return v;
end );


#############################################################################
##
#M  SiftedVector( <B>, <v> )
##
##  If `<B>!.heads[<i>]' is nonzero this means that the <i>-th column is
##  leading column of the row `<B>!.heads[<i>]'.
##
InstallMethod( SiftedVector,
    "for semi-ech. basis of Gaussian row space, and row vector",
    IsCollsElms,
    [ IsBasis and IsSemiEchelonBasisOfGaussianRowSpaceRep, IsRowVector ],
    function( B, v )
    return SiftedVectorForGaussianRowSpace(
               LeftActingDomain( UnderlyingLeftModule( B ) ),
               BasisVectors( B ), B!.heads, v );
    end );


#############################################################################
##
#F  HeadsInfoOfSemiEchelonizedMat( <mat>, <dim> )
##
##  is the `heads' information of the matrix <mat> with <dim> columns
##  if <mat> can be viewed as a semi-echelonized basis
##  of a Gaussian row space, and `fail' otherwise.
#T into `matrix.gi' ?
##
HeadsInfoOfSemiEchelonizedMat := function( mat, dim )
    local zero,     # zero of the field
          one,      # one of the field
          nrows,    # number of rows
          heads,    # list of pivot rows
          i,        # loop over rows
          j,        # pivot column
          k;        # loop over lower rows

    nrows:= Length( mat );
    heads:= ListWithIdenticalEntries( dim, 0 );

    if 0 < nrows then

      zero := Zero( mat[1][1] );
      one  := One( zero );

      # Loop over the columns.
      for i in [ 1 .. nrows ] do

        j:= PositionNot( mat[i], zero );
        if dim < j or mat[i][j] <> one then
          return fail;
        fi;
        for k in [ i+1 .. nrows ] do
          if mat[k][j] <> zero then
            return fail;
          fi;
        od;
        heads[j]:= i;

      od;

    fi;

    return heads;
end;


#############################################################################
##
#M  IsSemiEchelonized( <B> )
##
##  A basis of a Gaussian row space over a division ring with identity
##  element $e$ is in semi-echelon form if the leading entry of every row is
##  equal to $e$, and all entries exactly below that position are zero.
##
##  (This form is obtained on application of `SemiEchelonMat' to a matrix.)
##
InstallMethod( IsSemiEchelonized,
    "for basis of a Gaussian row space",
    [ IsBasis ],
    function( B )
    local V;
    V:= UnderlyingLeftModule( B );
    if not ( IsRowSpace( V ) and IsGaussianRowSpace( V ) ) then
#T The basis does not know whether it is a basis of a row space at all.
      TryNextMethod();
    else
      return HeadsInfoOfSemiEchelonizedMat( BasisVectors( B ),
                                            DimensionOfVectors( V ) ) <> fail;
#T change the basis from relative to seb ?
    fi;
    end );


#############################################################################
##
##  4. Methods for row spaces
##


#############################################################################
##
#M  \*( <V>, <mat> ) . . . . . . . . . . . . . action of matrix on row spaces
#M  \^( <V>, <mat> ) . . . . . . . . . . . . . action of matrix on row spaces
##
InstallOtherMethod( \*, IsIdenticalObj, [ IsRowSpace, IsMatrix ],
    function( V, mat )
    return LeftModuleByGenerators( LeftActingDomain( V ),
                            List( GeneratorsOfLeftModule( V ),
                                  v -> v * mat ) );
    end );

InstallOtherMethod( \^, IsIdenticalObj, [ IsRowSpace, IsMatrix ],
    function( V, mat )
    return LeftModuleByGenerators( LeftActingDomain( V ),
                            List( GeneratorsOfLeftModule( V ),
                                  v -> v * mat ) );
    end );


#############################################################################
##
#M  \in( <v>, <V> ) . . . . . . . . . . for row vector and Gaussian row space
##
InstallMethod( \in,
    "for row vector and Gaussian row space",
    IsElmsColls,
    [ IsRowVector, IsGaussianRowSpace ],
    function( v, V )
    if IsEmpty( v ) then
      return DimensionOfVectors( V ) = 0;
    elif DimensionOfVectors( V ) <> Length( v ) then
      return false;
    else
      v:= SiftedVector( Basis( V ), v );
#T any basis supports sifting?
      return v <> fail and DimensionOfVectors( V ) < PositionNonZero( v );
    fi;
    end );


#############################################################################
##
#M  Basis( <V> )  . . . . . . . . . . . . . . . . . .  for Gaussian row space
#M  Basis( <V>, <vectors> ) . . . . . . . . . . . . .  for Gaussian row space
#M  BasisNC( <V>, <vectors> ) . . . . . . . . . . . .  for Gaussian row space
##
##  Distinguish the cases whether the space <V> is a *Gaussian* row vector
##  space or not.
##
##  If the coefficients field is big enough then either a semi-echelonized or
##  a relative basis is constructed.
##
##  Otherwise the mechanism of associated nice bases is used.
##  In this case the default methods have been installed by
##  `InstallHandlingByNiceBasis'.
##
InstallMethod( Basis,
    "for Gaussian row space (construct a semi-echelonized basis)",
    [ IsGaussianRowSpace ],
    SemiEchelonBasis );

InstallMethod( Basis,
    "for Gaussian row space and matrix (try semi-echelonized)",
    IsIdenticalObj,
    [ IsGaussianRowSpace, IsMatrix ],
    function( V, gens )
    local heads, B, v;

    # Test whether the vectors form a semi-echelonized basis.
    # (If not then give up.)
    heads:= HeadsInfoOfSemiEchelonizedMat( gens, DimensionOfVectors( V ) );
    if heads = fail then
      TryNextMethod();
    fi;

    # Construct the basis.
    B:= Objectify( NewType( FamilyObj( gens ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep ),
                   rec() );
    SetUnderlyingLeftModule( B, V );
    SetBasisVectors( B, gens );
    if IsEmpty( gens ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;

    B!.heads:= heads;

    # The basis vectors are linearly independent since they form
    # a semi-echelonized matrix.
    # Hence it is sufficient to check whether they generate the space.
    for v in GeneratorsOfLeftModule( V ) do
      if Coefficients( B, v ) = fail then
        return fail;
      fi;
    od;

    # Return the basis.
    return B;
    end );

InstallMethod( BasisNC,
    "for Gaussian row space and matrix (try semi-echelonized)",
    IsIdenticalObj,
    [ IsGaussianRowSpace, IsMatrix ],
    function( V, gens )
    local heads, B;

    # Test whether the vectors form a semi-echelonized basis.
    # (If not then give up.)
    heads:= HeadsInfoOfSemiEchelonizedMat( gens, DimensionOfVectors( V ) );
    if heads = fail then
      TryNextMethod();
    fi;

    # Construct the basis.
    B:= Objectify( NewType( FamilyObj( gens ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep ),
                   rec() );
    SetUnderlyingLeftModule( B, V );
    SetBasisVectors( B, gens );
    if IsEmpty( gens ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;

    B!.heads:= heads;

    # Return the basis.
    return B;
    end );


#############################################################################
##
#M  SemiEchelonBasis( <V> )
#M  SemiEchelonBasis( <V>, <vectors> )
#M  SemiEchelonBasisNC( <V>, <vectors> )
##
InstallImmediateMethod( SemiEchelonBasis,
    IsGaussianRowSpace and HasCanonicalBasis and IsAttributeStoringRep, 20,
    CanonicalBasis );

InstallMethod( SemiEchelonBasis,
    "for Gaussian row space",
    [ IsGaussianRowSpace ],
    function( V )
    local B, gens;

    B:= Objectify( NewType( FamilyObj( V ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep ),
                   rec() );

    gens:= GeneratorsOfLeftModule( V );
    if IsEmpty( gens ) or ForAll( gens, IsZero ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;

    SetUnderlyingLeftModule( B, V );
    return B;
    end );

InstallMethod( SemiEchelonBasis,
    "for Gaussian row space and matrix",
    IsIdenticalObj,
    [ IsGaussianRowSpace, IsMatrix ],
    function( V, gens )

    local heads,   # heads info for the basis
          B,       # the basis, result
          gensi,   # immutable copy
          v;       # loop over vector space generators

    # Check that the vectors form a semi-echelonized basis.
    heads:= HeadsInfoOfSemiEchelonizedMat( gens, DimensionOfVectors( V ) );
    if heads = fail then
      return fail;
    fi;

    # Construct the basis.
    B:= Objectify( NewType( FamilyObj( gens ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep ),
                   rec() );
    if IsEmpty( gens ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;
    SetUnderlyingLeftModule( B, V );
    gensi := Immutable(gens);
    ConvertToMatrixRepNC(gensi, LeftActingDomain(V));
    SetBasisVectors( B, gensi );

    B!.heads:= heads;

    # The basis vectors are linearly independent since they form
    # a semi-echelonized list of matrices.
    # Hence it is sufficient to check whether they generate the space.
    for v in GeneratorsOfLeftModule( V ) do
      if Coefficients( B, v ) = fail then
        return fail;
      fi;
    od;

    return B;
    end );

InstallMethod( SemiEchelonBasisNC,
    "for Gaussian row space and matrix",
    IsIdenticalObj,
    [ IsGaussianRowSpace, IsMatrix ],
    function( V, gens )
    local B,  # the basis, result
          gensi; # immutable copy
    B:= Objectify( NewType( FamilyObj( gens ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep ),
                   rec() );
    if IsEmpty( gens ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;
    SetUnderlyingLeftModule( B, V );
    gensi := Immutable(gens);
    ConvertToMatrixRepNC(gensi, LeftActingDomain(V));
    SetBasisVectors( B, gens );

    # Provide the `heads' information.
    B!.heads:= HeadsInfoOfSemiEchelonizedMat( gens, DimensionOfVectors( V ) );

    # Return the basis.
    return B;
    end );


#############################################################################
##
#M  BasisVectors( <B> ) . . . . . . for semi-ech. basis of Gaussian row space
##
InstallMethod( BasisVectors,
    "for semi-ech. basis of a Gaussian row space",
    [ IsBasis and IsSemiEchelonBasisOfGaussianRowSpaceRep ],
    function( B )
    local V, gens, vectors;

    # Check that the basis is not a canonical basis;
    # in this case we need another method.
    if HasIsCanonicalBasis( B ) and IsCanonicalBasis( B ) then
      TryNextMethod();
    fi;

    V:= UnderlyingLeftModule( B );

    # Note that we must not ask for the dimension here \ldots
    gens:= GeneratorsOfLeftModule( V );

    if IsEmpty( gens ) then

      B!.heads:= 0 * [ 1 .. DimensionOfVectors( V ) ];
      SetIsEmpty( B, true );
      vectors:= [];

    else

      gens:= SemiEchelonMat( gens );
      B!.heads:= gens.heads;
      vectors:= gens.vectors;

    fi;
    return vectors;
    end );


#############################################################################
##
#M  Zero( <V> ) . . . . . . . . . . . . . . . . . . . . . . . for a row space
##
InstallOtherMethod( Zero,
    "for a row space",
    [ IsRowSpace ],
    V -> Zero( LeftActingDomain( V ) ) * [ 1 .. DimensionOfVectors( V ) ] );


#############################################################################
##
#M  IsZero( <v> )
##
InstallMethod( IsZero,
    "for row vector",
    [ IsRowVector ],
    function( v )
    if IsEmpty( v ) then
      return true;
    else
      return Length( v ) < PositionNot( v, Zero( v[1] ) );
    fi;
    end );


#############################################################################
##
#M  AsLeftModule( <F>, <rows> ) . . . . . . . .  for division ring and matrix
##
InstallMethod( AsLeftModule,
    "for division ring and matrix",
    IsElmsColls,
    [ IsDivisionRing, IsMatrix ],
    function( F, vectors )
    local m;

    if not IsPrimePowerInt( Length( vectors ) ) then
      return fail;
    elif ForAll( vectors, v -> IsSubset( F, v ) ) then
#T other check!

      # All vector entries lie in `F'.
      # (We work destructively.)
      m:= SemiEchelonMatDestructive( List( vectors, ShallowCopy ) ).vectors;
      if IsEmpty( m ) then
        m:= LeftModuleByGenerators( F, [], vectors[1] );
      else
        m:= FreeLeftModule( F, m, "basis" );
      fi;

    else

      # We have at most a non-Gaussian row space.
      m:= LeftModuleByGenerators( F, vectors );

    fi;

    # Check that the space equals the list of vectors.
    if Size( m ) <> Length( vectors ) then
      return fail;
    fi;

    # Return the space.
    return m;
    end );


#############################################################################
##
#M  \+( <U1>, <U2> )  . . . . . . . . . . . .  sum of two Gaussian row spaces
##
InstallOtherMethod( \+,
    "for two Gaussian row spaces",
    IsIdenticalObj,
    [ IsGaussianRowSpace, IsGaussianRowSpace ],
    function( V, W )
    local S,          # sum of <V> and <W>, result
          mat;        # basis vectors of the sum

    if   DimensionOfVectors( V ) <> DimensionOfVectors( W ) then
      Error( "vectors in <V> and <W> have different dimension" );
    elif Dimension( V ) = 0 then
      S:= W;
    elif Dimension( W ) = 0 then
      S:= V;
    elif LeftActingDomain( V ) <> LeftActingDomain( W ) then
      S:= Intersection2( LeftActingDomain( V ), LeftActingDomain( W ) );
      S:= \+( AsVectorSpace( S, V ), AsVectorSpace( S, W ) );
    else
      mat:= SumIntersectionMat( GeneratorsOfLeftModule( V ),
                                GeneratorsOfLeftModule( W ) )[1];
      if IsEmpty( mat ) then
        S:= TrivialSubspace( V );
      else
        S:= LeftModuleByGenerators( LeftActingDomain( V ), mat );
        UseBasis( S, mat );
      fi;
    fi;

    return S;
    end );


#############################################################################
##
#M  Intersection2( <V>, <W> ) . . . . intersection of two Gaussian row spaces
##
InstallMethod( Intersection2,
    "for two Gaussian row spaces",
    IsIdenticalObj,
    [ IsGaussianRowSpace, IsGaussianRowSpace ],
    function( V, W )
    local S,          # intersection of `V' and `W', result
          mat;        # basis vectors of the intersection
    
    if   DimensionOfVectors( V ) <> DimensionOfVectors( W ) then
      S:= [];
    elif Dimension( V ) = 0 then
      S:= V;
    elif Dimension( W ) = 0 then
      S:= W;
    elif LeftActingDomain( V ) <> LeftActingDomain( W ) then
      S:= Intersection2( LeftActingDomain( V ), LeftActingDomain( W ) );
      S:= Intersection2( AsVectorSpace( S, V ), AsVectorSpace( S, W ) );
    else

      # Compute the intersection of two spaces over the same field.
      mat:= SumIntersectionMat( BasisVectors(SemiEchelonBasis( V )),
                                BasisVectors(SemiEchelonBasis( W )) )[2];
#T why not just the generators if no basis is known yet?
      if IsEmpty( mat ) then
        S:= TrivialSubspace( V );
      else
        S:= LeftModuleByGenerators( LeftActingDomain( V ), mat );
        UseBasis( S, mat );
        SetSemiEchelonBasis(S, SemiEchelonBasisNC(S,mat));
      fi;

    fi;

    return S;
    end );


#############################################################################
##
#M  NormedRowVectors( <V> )
##
InstallMethod( NormedRowVectors,
    "for Gaussian row space",
    [ IsGaussianRowSpace ],
    function( V )
    local base,       # basis vectors
          elms,       # element list, result
          elms2,      # intermediate element list
          F,          # `LeftActingDomain( V )'
          q,          # `Size( F )'
          fieldelms,  # elements of `F' (in other succession)
          j,          # loop over `base'
          new,        # intermediate element list
          pos,        # position in `new' to store the next element
          len,        # actual length of `elms2'
          i,          # loop over field elements
          toadd,      # vector to add to known vectors
          k,          # loop over `elms2'
          v;          # one normed row vector

    if not IsFinite( V ) then
      Error( "sorry, cannot compute normed vectors of infinite domain <V>" );
    fi;

    base:= Reversed( BasisVectors( CanonicalBasis( V ) ) );
    if Length( base ) = 0 then
      return [];
    fi;

    elms      := [ base[1] ];
    elms2     := [ base[1] ];
    F         := LeftActingDomain( V );
    q         := Size( F );
    fieldelms := List( AsSSortedList( F ), x -> x - 1 );

    for j in [ 1 .. Length( base ) - 1 ] do

      # Here `elms2' has the form
      # $b_i + M = b_i + \langle b_{i+1}, \ldots, b_n \rangle$.
      # Compute $b_{i-1} + \bigcup_{\lambda\in F} \lambda b_i + ( b_i + M )$.
      new:= [];
      pos:= 0;
      len:= Length( elms2 );
      for i in fieldelms do
        toadd:= base[j+1] + i * base[j];
        for k in [ 1 .. len ] do
          v:= elms2[k] + toadd;
          ConvertToVectorRep( v, q );
          new[ pos + k ]:= v;
        od;
        pos:= pos + len;
      od;
      elms2:= new;

      # `elms2' is a set here.
      Append( elms, elms2 );

    od;

    # The list is strictly sorted, so we store this.
    MakeImmutable( elms );
    Assert( 1, IsSSortedList( elms ) );
    SetIsSSortedList( elms, true );

    # Return the result.
    return elms;
    end );


#############################################################################
##
#M  CanonicalBasis( <V> ) . . . . . . . . . . . . . .  for Gaussian row space
##
##  The canonical basis of a Gaussian row space is defined by applying
##  a full Gauss algorithm to the generators of the space.
##
InstallMethod( CanonicalBasis,
    "for Gaussian row space with known semi-ech. basis",
    [ IsGaussianRowSpace and HasSemiEchelonBasis ],
    function( V )
    local base,    # list of base vectors
          heads,   # list of numbers of leading columns
          ech,     # echelonized basis, if known
          vectors, #
          row,     # one vector in `ech'
          B,       # basis record, result
          n,       # number of columns in generators
          zero,    # zero of the field
          i,       # loop over rows
          k;       # loop over columns

    base  := [];
    zero  := Zero( LeftActingDomain( V ) );

    # We use the semi-echelonized basis.
    # All we have to do is to sort the basis vectors such that the
    # pivot elements are in increasing order, and to zeroize all
    # elements in the pivot columns except the pivot itself.

    ech:= SemiEchelonBasis( V );
    vectors:= BasisVectors( ech );
    heads := ShallowCopy( ech!.heads );
    n:= Length( heads );

    for i in [ 1 .. n ] do
      if heads[i] <> 0 then

        # Eliminate the `ech!.heads[i]'-th row with all those rows
        # that are below this row and have a bigger pivot element.
        row:= ShallowCopy( vectors[ ech!.heads[i] ] );
        for k in [ i+1 .. n ] do
          if heads[k] <> 0 and ech!.heads[k] > ech!.heads[i] then
            AddRowVector( row, vectors[ ech!.heads[k] ], - row[k] );
          fi;
        od;
        Add( base, row );
        heads[i]:= Length( base );

      fi;
    od;

    B:= Objectify( NewType( FamilyObj( V ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep
                            and IsCanonicalBasis ),
                   rec() );
    if IsEmpty( vectors ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;
    SetUnderlyingLeftModule( B, V );
    SetBasisVectors( B, base );

    B!.heads:= heads;

    # Return the basis.
    return B;
    end );

InstallMethod( CanonicalBasis,
    "for Gaussian row space",
    [ IsGaussianRowSpace ],
    function( V )

    local base,    # list of base vectors
          heads,   # list of numbers of leading columns
          B,       # basis record, result
          m,       # number of rows in generators
          n,       # number of columns in generators
          zero,    # zero of the field
          i,       # loop over rows
          k;       # loop over columns

    base  := [];
    heads := ListWithIdenticalEntries( DimensionOfVectors( V ), 0 );
    zero  := Zero( LeftActingDomain( V ) );

    if not IsEmpty( GeneratorsOfLeftModule( V ) ) then

      # Make a copy to avoid changing the original argument.
      B:= List( GeneratorsOfLeftModule( V ), ShallowCopy );
      m:= Length( B );
      n:= Length( B[1] );

      # Triangulize the matrix
      TriangulizeMat( B );

      # and keep only the nonzero rows of the triangular matrix.
      i:= 1;
      base := [];
      for k in [ 1 .. n ] do
        if i <= m and B[i][k] <> zero then
          base[i]:= B[i];
          heads[k]:= i;
          i:= i + 1;
        fi;
      od;

    fi;

    B:= Objectify( NewType( FamilyObj( V ),
                                IsFiniteBasisDefault
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep
                            and IsCanonicalBasis ),
                   rec() );
    if IsEmpty( base ) then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;
    SetUnderlyingLeftModule( B, V );
    SetBasisVectors( B, base );

    B!.heads:= heads;

    # Return the basis.
    return B;
    end );


#############################################################################
##
##  5. Methods for full row spaces
##

#############################################################################
##
#M  IsFullRowModule( V )
##
InstallMethod( IsFullRowModule,
    "for Gaussian row space",
    [ IsGaussianRowSpace ],
    V -> Dimension( V ) = DimensionOfVectors( V ) );

InstallMethod( IsFullRowModule,
    "for non-Gaussian row space",
    [ IsVectorSpace and IsNonGaussianRowSpace ],
    ReturnFalse );

InstallOtherMethod( IsFullRowModule,
    "for arbitrary free left module",
    [ IsLeftModule ],
    function( V )
    local gens, R;

    # A full row module is a free left module.
    if not IsFreeLeftModule( V ) then
      return false;
    fi;

    # The elements of a full row module are row vectors over the
    # left acting domain,
    # and the dimension equals the length of the row vectors.
    gens:= GeneratorsOfLeftModule( V );
    if IsEmpty( gens ) then
      gens:= [ Zero( V ) ];
    fi;
    R:= LeftActingDomain( V );
    return     ForAll( gens,
                       row -> IsRowVector( row ) and IsSubset( R, row ) )
           and Dimension( V ) = Length( gens[1] );
    end );


#############################################################################
##
#M  CanonicalBasis( <V> )
##
InstallMethod( CanonicalBasis,
    "for a full row space",
    [ IsFullRowModule and IsVectorSpace ],
    function( V )
    local B;
    B:= Objectify( NewType( FamilyObj( V ),
                                IsFiniteBasisDefault
                            and IsCanonicalBasis
                            and IsSemiEchelonized
                            and IsSemiEchelonBasisOfGaussianRowSpaceRep
                            and IsCanonicalBasisFullRowModule ),
                   rec() );
    SetUnderlyingLeftModule( B, V );
    B!.heads:= [ 1 .. DimensionOfVectors( V ) ];
    if DimensionOfVectors( V ) = 0 then
      SetIsEmpty( B, true );
    else
      SetIsRectangularTable( B, true );
    fi;
    return B;
    end );


#############################################################################
##
##  6. Methods for collections of subspaces of full row spaces
##

#############################################################################
##
#R  IsSubspacesFullRowSpaceDefaultRep
##
DeclareRepresentation( "IsSubspacesFullRowSpaceDefaultRep",
    IsSubspacesVectorSpaceDefaultRep,
    [] );


#############################################################################
##
#M  Iterator( <subspaces> ) . . . . . for subspaces of finite full row module
##
BindGlobal( "IsDoneIterator_SubspacesDim",
    iter ->     IsDoneIterator( iter!.choiceiter )
            and IsDoneIterator( iter!.spaceiter ) );

BindGlobal( "NextIterator_SubspacesDim", function( iter )
    local dim,
          vector,
          pos,
          base,
          i,
          j,
          k,
          n,
          diff;

    k:= iter!.k;
    n:= iter!.n;

    if IsDoneIterator( iter!.spaceiter ) then

      # Get the next choice of pivot positions,
      # and install an iterator for spaces with this choice.
      iter!.actchoice:= NextIterator( iter!.choiceiter );
      dim:= n * k - k * (k - 1) / 2 - Sum( iter!.actchoice );
      Add( iter!.actchoice, n + 1 );
      iter!.spaceiter:= IteratorByBasis(
          CanonicalBasis( FullRowSpace( iter!.field, dim ) ) );

    fi;

    # Construct the canonical basis of the space.
    vector:= NextIterator( iter!.spaceiter );
    pos:= 0;
    base:= NullMat( k, n, iter!.field );
    for i in [ 1 .. k ] do
      base[i][ iter!.actchoice[i] ]:= One( iter!.field );
      for j in [ i .. k ] do
        diff:= iter!.actchoice[ j+1 ] - iter!.actchoice[j] - 1;
        if diff > 0 then
          base[i]{ [ iter!.actchoice[j]+1 .. iter!.actchoice[j+1]-1 ] }:=
                   vector{ [ pos + 1 .. pos + diff ] };
          pos:= pos + diff;
        fi;
      od;
    od;

    return Subspace( iter!.V, base, "basis" );
    end );

BindGlobal( "ShallowCopy_SubspacesDim",
    iter -> rec( V          := iter!.V,
                 field      := iter!.field,
                 n          := iter!.n,
                 k          := iter!.k,
                 choiceiter := ShallowCopy( iter!.choiceiter ),
                 actchoice  := iter!.actchoice,
                 spaceiter  := ShallowCopy( iter!.spaceiter ) ) );

BindGlobal( "IsDoneIterator_SubspacesAll",
    iter ->     iter!.actdim = iter!.dim
            and IsDoneIterator( iter!.actdimiter ) );

BindGlobal( "NextIterator_SubspacesAll", function( iter )
    if IsDoneIterator( iter!.actdimiter ) then
      iter!.actdim:= iter!.actdim + 1;
      iter!.actdimiter:= Iterator(Subspaces( iter!.V, iter!.actdim));
    fi;
    return NextIterator( iter!.actdimiter );
    end );

BindGlobal( "ShallowCopy_SubspacesAll",
    iter -> rec( V          := iter!.V,
                 dim        := iter!.dim,
                 actdim     := iter!.actdim,
                 actdimiter := ShallowCopy( iter!.actdimiter ) ) );

InstallMethod( Iterator,
    "for subspaces collection of a (finite) full row module",
    [ IsSubspacesVectorSpace and IsSubspacesFullRowSpaceDefaultRep ],
    function( D )
    local V,      # the vector space
          n,      # dimension of `V'
          k,
          iter;   # iterator, result

    V:= D!.structure;

    if not IsFinite( V ) then
      TryNextMethod();
    fi;

    k:= D!.dimension;
    n:= Dimension( V );

    if IsInt( D!.dimension ) then

      # Loop over subspaces of fixed dimension `k'.
      # For that, loop over all possible choices of `k' ordered positions
      # in `[ 1 .. n ]', and for every such choice, loop over all
      # possibilities to fill the positions in the canonical basis
      # that has these positions as pivot columns.

      # If the choice is $[ a_1, a_2, \ldots, a_k ]$ then there are
      # \[ (a_2-a_1-1)+2(a_3-a_2-1)+\cdots + (k-1)(a_k-a_{k-1}-1)+k(n-a_k)
      #    = \sum_{i=1}^{k-1} i(a_{i+1}-a_i-1) + k(n-a_k)
      #    = k n - \frac{1}{2}k(k-1) - \sum_{i=1}^k a_i \]
      # positions that can be chosen arbitrarily, so we may loop over
      # the elements of a space of this dimension.

      iter:= IteratorByFunctions( rec(
                 IsDoneIterator := IsDoneIterator_SubspacesDim,
                 NextIterator   := NextIterator_SubspacesDim,
                 ShallowCopy    := ShallowCopy_SubspacesDim,

                 V              := V,
                 field          := LeftActingDomain( V ),
                 n              := n,
                 k              := k,
                 choiceiter     := Iterator( Combinations( [ 1..n ],
                                                 D!.dimension ) ) ) );
#T better make this *really* clever!
      # Initialize.
      iter!.actchoice:= NextIterator( iter!.choiceiter );
      iter!.spaceiter:= IteratorByBasis( CanonicalBasis( FullRowSpace(
           iter!.field, n * k - k * (k - 1) / 2
                               - Sum( iter!.actchoice ) ) ) );
      Add( iter!.actchoice, n+1 );

    else

      # Loop over all subspaces of `V'.
      # For that, use iterators for subspaces of fixed dimension,
      # and loop over all dimensions.
      iter:= IteratorByFunctions( rec(
                 IsDoneIterator := IsDoneIterator_SubspacesAll,
                 NextIterator   := NextIterator_SubspacesAll,
                 ShallowCopy    := ShallowCopy_SubspacesAll,

                 V              := V,
                 dim            := n,
                 actdim         := 0,
                 actdimiter     := Iterator( Subspaces( V, 0 ) ) ) );

    fi;

    # Return the iterator.
    return iter;
    end );


#############################################################################
##
#M  Subspaces( <V>, <dim> )
##
InstallMethod( Subspaces,
    "for (Gaussian) full row space",
    [ IsFullRowModule and IsVectorSpace, IsInt ],
    function( V, dim )
    return Objectify( NewType( CollectionsFamily( FamilyObj( V ) ),
                                   IsSubspacesVectorSpace
                               and IsSubspacesFullRowSpaceDefaultRep ),
                      rec(
                           structure  := V,
                           dimension  := dim
                          )
                     );
    end );

InstallOtherMethod( Subspaces,
    "for (Gaussian) full row space",
    [ IsFullRowModule and IsVectorSpace, IsString ],
    function( V, all )
    return Subspaces( V );
    end );


#############################################################################
##
#M  Subspaces( <V> )
##
InstallMethod( Subspaces,
    [ IsFullRowModule and IsVectorSpace ],
    V -> Objectify( NewType( CollectionsFamily( FamilyObj( V ) ),
                                 IsSubspacesVectorSpace
                             and IsSubspacesFullRowSpaceDefaultRep ),
                    rec(
                         structure  := V,
                         dimension  := "all"
                        )
                   ) );


#############################################################################
##
##  7. Methods for mutable bases of Gaussian row spaces
##

#############################################################################
##
#R  IsMutableBasisOfGaussianRowSpaceRep( <B> )
##
##  The default mutable bases of Gaussian row spaces are semi-echelonized.
##  Note that we switch to a mutable basis of representation
##  `IsMutableBasisByImmutableBasisRep' if the mutable basis is closed by a
##  vector that makes the space non-Gaussian.
##
DeclareRepresentation( "IsMutableBasisOfGaussianRowSpaceRep",
    IsComponentObjectRep,
    [ "heads", "basisVectors", "leftActingDomain", "zero" ] );


#############################################################################
##
#M  MutableBasis( <R>, <vectors> )  . . . . . . . . . . . for matrix over <R>
#M  MutableBasis( <R>, <vectors>, <zero> )  . . . . . . . for matrix over <R>
##
InstallMethod( MutableBasis,
    "method to construct mutable bases of row spaces",
    IsElmsColls,
    [ IsRing, IsMatrix ],
    function( R, vectors )
    local B, newvectors;

    if ForAny( vectors, v -> not IsSubset( R, v ) ) then

      # If Gaussian elimination is not allowed,
      # we construct a mutable basis that stores an immutable basis.
      TryNextMethod();

    else

      # Note that `vectors' is not empty.
      newvectors:= SemiEchelonMat( vectors );

      B:= Objectify( NewType( FamilyObj( vectors ),
                                  IsMutableBasis
                              and IsMutable
                              and IsMutableBasisOfGaussianRowSpaceRep ),
                     rec(
                          basisVectors:= ShallowCopy( newvectors.vectors ),
                          heads:= ShallowCopy( newvectors.heads ),
                          zero:= Zero( vectors[1] ),
                          leftActingDomain := R
                          ) );

    fi;

    return B;
    end );

InstallOtherMethod( MutableBasis,
    "method to construct mutable bases of row spaces",
    IsIdenticalObjObjXObj,
    [ IsRing, IsList, IsRowVector ],
    function( R, vectors, zero )
    local B;

    if ForAny( vectors, v -> not IsSubset( R, v ) ) then

      # If Gaussian elimination is not allowed,
      # we construct a mutable basis that stores an immutable basis.
      TryNextMethod();

    else

      B:= Objectify( NewType( CollectionsFamily( FamilyObj( zero ) ),
                                  IsMutableBasis
                              and IsMutable
                              and IsMutableBasisOfGaussianRowSpaceRep ),
                     rec(
                          zero:= zero,
                          leftActingDomain := R
                          ) );

      if IsEmpty( vectors ) then

        B!.basisVectors:= [];
        B!.heads:= ListWithIdenticalEntries( Length( zero ), 0 );

      else

        vectors:= SemiEchelonMat( vectors );
        B!.basisVectors:= ShallowCopy( vectors.vectors );
        B!.heads:= ShallowCopy( vectors.heads );

      fi;

    fi;

    return B;
    end );


#############################################################################
##
#M  ViewObj( <MB> ) . . . . . . .  view mutable basis of a Gaussian row space
##
InstallMethod( ViewObj,
    "for a mutable basis of a Gaussian row space",
    [ IsMutableBasis and IsMutableBasisOfGaussianRowSpaceRep ],
    function( MB )
    Print( "<mutable basis over ", MB!.leftActingDomain, ", ",
           Length( MB!.basisVectors ), " vectors>" );
    end );


#############################################################################
##
#M  PrintObj( <MB> )  . . . . . . print mutable basis of a Gaussian row space
##
InstallMethod( PrintObj,
    "for a mutable basis of a Gaussian row space",
    [ IsMutableBasis and IsMutableBasisOfGaussianRowSpaceRep ],
    function( MB )
    Print( "MutableBasis( ", MB!.leftActingDomain, ", " );
    if NrBasisVectors( MB ) = 0 then
      Print( "[], ", Zero( MB!.leftActingDomain ), " )" );
    else
      Print( MB!.basisVectors, " )" );
    fi;
    end );


#############################################################################
##
#M  BasisVectors( <MB> )  . . . . . for mutable basis of a Gaussian row space
##
InstallOtherMethod( BasisVectors,
    "for a mutable basis of a Gaussian row space",
    [ IsMutableBasis and IsMutableBasisOfGaussianRowSpaceRep ],
    MB -> Immutable( MB!.basisVectors ) );


#############################################################################
##
#M  CloseMutableBasis( <MB>, <v> )  . .  for mut. basis of Gaussian row space
##
InstallMethod( CloseMutableBasis,
    "for a mut. basis of a Gaussian row space, and a row vector",
    IsCollsElms,
    [ IsMutableBasis and IsMutable and IsMutableBasisOfGaussianRowSpaceRep,
      IsRowVector ],
    function( MB, v )
    local V,              # corresponding free left module
          ncols,          # dimension of the row vectors
          zero,           # zero scalar
          heads,          # heads info of the basis
          basisvectors,   # list of basis vectors of `MB'
          j;              # loop over `heads'

    # Check whether the mutable basis belongs to a Gaussian row space
    # after the closure.
    if not IsSubset( MB!.leftActingDomain, v ) then

      # Change the representation to a mutable basis by immutable basis.
#T better mechanism?
      basisvectors:= Concatenation( MB!.basisVectors, [ v ] );
      V:= LeftModuleByGenerators( MB!.leftActingDomain, basisvectors );
      UseBasis( V, basisvectors );

      SetFilterObj( MB, IsMutableBasisByImmutableBasisRep );
      ResetFilterObj( MB, IsMutableBasisOfGaussianRowSpaceRep );

      MB!.immutableBasis:= Basis( V );

    else

      # Reduce `v' with the known basis vectors.
      v:= ShallowCopy( v );
      ncols:= Length( v );
      heads:= MB!.heads;

      if ncols <> Length( MB!.heads ) then
        Error( "<v> must have same length as `MB!.heads'" );
      fi;

      zero:= Zero( v[1] );
      basisvectors:= MB!.basisVectors;

      for j in [ 1 .. ncols ] do
        if zero <> v[j] and heads[j] <> 0 then
#T better loop with `PositionNot'?
          AddRowVector( v, basisvectors[ heads[j] ], - v[j] );
        fi;
      od;

      # If necessary add the sifted vector, and update the basis info.
      j := PositionNot( v, zero );
      if j <= ncols then
        MultRowVector( v, Inverse( v[j] ) );
        Add( basisvectors, v );
        heads[j]:= Length( basisvectors );
      fi;

    fi;
    end );


#############################################################################
##
#M  IsContainedInSpan( <MB>, <v> )  . .  for mut. basis of Gaussian row space
##
InstallMethod( IsContainedInSpan,
    "for a mut. basis of a Gaussian row space, and a row vector",
    IsCollsElms,
    [ IsMutableBasis and IsMutableBasisOfGaussianRowSpaceRep,
      IsRowVector ],
    function( MB, v )
    local
          ncols,          # dimension of the row vectors
          zero,           # zero scalar
          heads,          # heads info of the basis
          basisvectors,   # list of basis vectors of `MB'
          j;              # loop over `heads'

    if not IsSubset( MB!.leftActingDomain, v ) then

      return false;

    else

      # Reduce `v' with the known basis vectors.
      v:= ShallowCopy( v );
      ncols:= Length( v );
      heads:= MB!.heads;

      if ncols <> Length( MB!.heads ) then
        return false;
      fi;

      zero:= Zero( v[1] );
      basisvectors:= MB!.basisVectors;

      for j in [ 1 .. ncols ] do
        if heads[j] <> 0 then
          AddRowVector( v, basisvectors[ heads[j] ], - v[j] );
        fi;
      od;

      # Check whether the sifted vector is zero.
      return IsZero( v );

    fi;
    end );


#############################################################################
##
#M  ImmutableBasis( <MB> )  . . . . for mutable basis of a Gaussian row space
##
InstallMethod( ImmutableBasis,
    "for a mutable basis of a Gaussian row space",
    [ IsMutableBasis and IsMutableBasisOfGaussianRowSpaceRep ],
    function( MB )
    local V;
    V:= FreeLeftModule( MB!.leftActingDomain,
                        BasisVectors( MB ),
                        MB!.zero );
    MB:= SemiEchelonBasisNC( V, BasisVectors( MB ) );
#T use known `heads' info !!
    UseBasis( V, MB );
    return MB;
    end );


#############################################################################
##
#M  SiftedVector( <MB>, <v> ) . . . for mutable basis of a Gaussian row space
##
##  If `<MB>!.heads[<i>]' is nonzero this means that the <i>-th column is
##  leading column of the row `<MB>!.heads[<i>]'.
##
InstallOtherMethod( SiftedVector,
    "for mutable basis of Gaussian row space, and row vector",
    IsCollsElms,
    [ IsMutableBasis and IsMutableBasisOfGaussianRowSpaceRep, IsRowVector ],
    function( MB, v )
    return SiftedVectorForGaussianRowSpace(
               MB!.leftActingDomain, MB!.basisVectors, MB!.heads, v );
    end );


#############################################################################
##
#F  OnLines( <vec>, <g> ) . . . . . . . .  for operation on projective points
##
InstallGlobalFunction( OnLines, function( vec, g )
    local c;
    vec:= OnPoints( vec, g );
    c:= PositionNonZero( vec ); # better than PositionNot, as no `Zero'
                                # element needs to be created
    if c <= Length( vec ) then

      # Normalize from the *left* if the matrices act from the right!
      vec:= Inverse( vec[c] ) * vec;

    fi;
    return vec;
end );


#############################################################################
##
#M  NormedRowVector( <v> )
##
InstallMethod( NormedRowVector,
    "for a row vector of scalars",
    [ IsRowVector and IsScalarCollection ],
function( v )
    local   depth;

    if 0 < Length(v)  then
	depth:=PositionNonZero( v ); # better than PositionNot, as no `Zero'
				     # element needs to be created
        if depth <= Length(v) then
            return Inverse(v[depth]) * v;
        else
            return ShallowCopy(v);
        fi;
    else
        return ShallowCopy(v);
    fi;
end );


#T mutable bases for Gaussian row and matrix spaces are always semi-ech.
#T (note that we construct a mutable basis only if we want to do successive
#T closures)


#############################################################################
##
##  8. Methods installed by somebody else without documenting this ...
##


#############################################################################
##
#F  ExtendedVectors( <V> )  . . . . . . . . . . . . . . . . . for a row space
##
BindGlobal( "ElementNumber_ExtendedVectors", function( enum, n )
    if Length( enum ) < n then
      Error( "<enum>[", n, "] must have an assigned value" );
    fi;
    n:= Concatenation( enum!.spaceEnumerator[n], [ enum!.one ] );
    ConvertToVectorRepNC( n, enum!.q );
    return Immutable( n );
end );

BindGlobal( "NumberElement_ExtendedVectors", function( enum, elm )
    if not IsList( elm ) or Length( elm ) <> enum!.len
                         or elm[ enum!.len ] <> enum!.one then
      return fail;
    fi;
    return Position( enum!.spaceEnumerator,
		     elm{ [ 1 .. Length( elm ) - 1 ] } );
end );

BindGlobal( "NumberElement_ExtendedVectorsFF", function( enum, elm )
    # test whether the vector is indeed compact over the right finite field
    if not IsDataObjectRep( elm ) then
      if ConvertToVectorRepNC( elm, enum!.q ) = fail then
        return NumberElement_ExtendedVectors( enum, elm );
      fi;
    fi;
    # Problem with GF(4) vectors over GF(2)
    if ( IsGF2VectorRep( elm ) and enum!.q <> 2 )
       or ( Is8BitVectorRep( elm ) and enum!.q = 2 ) then
      return NumberElement_ExtendedVectors( enum, elm );
    fi;

    # compute index via number
    if not IsList( elm ) or Length( elm ) <> enum!.len
                         or elm[ enum!.len ] <> enum!.one then
      return fail;
    fi;
    return QuoInt( NumberFFVector( elm, enum!.q ), enum!.q ) + 1;
end );

BindGlobal( "Length_ExtendedVectors", T -> Length( T!.spaceEnumerator ) );

BindGlobal( "PrintObj_ExtendedVectors", function( T )
    Print( "A( ", UnderlyingCollection( T!.spaceEnumerator ), " )" );
end );

BindGlobal( "ExtendedVectors", function( V )
    local enum;

    enum:= EnumeratorByFunctions( FamilyObj( V ), rec(
               ElementNumber   := ElementNumber_ExtendedVectors,
               NumberElement   := NumberElement_ExtendedVectors,
               Length          := Length_ExtendedVectors,
               PrintObj        := PrintObj_ExtendedVectors,

               spaceEnumerator := Enumerator( V ),
               one             := One( LeftActingDomain( V ) ),
               len             := Length( Zero( V ) ) + 1 ) );

    if     IsFinite( LeftActingDomain( V ) )
       and IsPrimeInt( Size( LeftActingDomain( V ) ) )
       and Size( LeftActingDomain( V ) ) < 256
       and IsInternalRep( One( LeftActingDomain( V ) ) ) then
      SetFilterObj( enum, IsQuickPositionList );
      enum!.q:= enum!.spaceEnumerator!.q;
      enum!.NumberElement:= NumberElement_ExtendedVectorsFF;
    else
      enum!.q:= Size( LeftActingDomain( V ) );
    fi;

    return enum;
end );


#############################################################################
##
#F  EnumeratorOfNormedRowVectors( <V> )  . . . . . . for a Gaussian row space
##
##  This had been called `OneDimSubspacesTransversal' in {\GAP}~4.3,
##  and special code in `ActionHomomorphismConstructor' relied on the fact
##  that one of its arguments was *not* an object returned by
##  `OneDimSubspacesTransversal'.
##  Now the result is just the ``sparse equivalent'' of `NormedRowVectors',
##  it does not carry any nasty `PositionCanonical' magic.
##
BindGlobal( "ElementNumber_NormedRowVectors", function( T, num )
    local   f,  v,  q,  n,  nnum, i,  l,  L;

    f := T!.enumeratorField;
    q := Length( f );
    n := T!.dimension;
    v := ListWithIdenticalEntries( n, Zero( T!.one ) );
    nnum:= num;
    num := num - 1;

    # Find the number of entries after the leading 1.
    l := 0;
    L := 1;
    while num >= L  do
        l := l + 1;
        L := L * q + 1;
    od;
    num := num - ( L - 1 ) / q;
    if n <= l then
      Error( "<T>[", nnum, "] must have an assigned value" );
    fi;
    v[ n - l ] := T!.one;
    for i  in [ n - l + 1 .. n ]  do
        v[ i ] := f[ num mod q + 1 ];
        num := QuoInt( num, q );
    od;
    ConvertToVectorRepNC(v,q);
    return Immutable( v );
end );

BindGlobal( "NumberElement_NormedRowVectors", function( T, elm )
    local   f,  zero,  q,  n,  l,  num,  val,  i;

    f := T!.enumeratorField;
    zero := Zero( T!.one );
    q := Length( f );
    n := T!.dimension;
    l := 1;

    if    not IsRowVector( elm )
       or not IsCollsElms( FamilyObj( T ), FamilyObj( elm ) )
       or Length( elm ) <> T!.dimension then
      return fail;
    fi;

    # Find the first entry different from zero.
    while elm[ l ] = zero  do
        l := l + 1;
    od;
    elm := elm / elm[ l ];

    num := 1;
    for i  in [ 0 .. n - l - 1 ]  do
        num := num + q ^ i;
    od;
    val := 1;
    for i  in [ l + 1 .. n ]  do
        num := num + val * ( Position( f, elm[ i ] ) - 1 );
        val := val * q;
    od;
    return num;
end );

BindGlobal( "Length_NormedRowVectors", function( T )
    local  q,  d;

    q := Length( T!.enumeratorField );
    d := T!.dimension;
    return ( q ^ d - 1 ) / ( q - 1 );
end );

BindGlobal( "PrintObj_NormedRowVectors", function( T )
    Print( "EnumeratorOfNormedRowVectors( ", T!.domain, " )" );
end );

BindGlobal( "EnumeratorOfNormedRowVectors", function( V )
    if not ( IsFullRowModule( V ) and IsFinite( V ) ) then
      Error( "<V> must be a finite full row space" );
    fi;

    return EnumeratorByFunctions( FamilyObj( V ), rec(
               ElementNumber   := ElementNumber_NormedRowVectors,
               NumberElement   := NumberElement_NormedRowVectors,
               Length          := Length_NormedRowVectors,
               PrintObj        := PrintObj_NormedRowVectors,

               enumeratorField := Enumerator( LeftActingDomain( V ) ),
               domain          := V,
               dimension       := Dimension( V ),
               one             := One( LeftActingDomain( V ) ) ) );
end );


#############################################################################
##
#F  OrthogonalSpaceInFullRowSpace( U ) . . . . . . . . .compute the dual to U
##
InstallMethod( OrthogonalSpaceInFullRowSpace,
    "dual space for Gaussian row space",
    [ IsGaussianRowSpace ],
function( U )
    local base, n, i, null;
    base := ShallowCopy( Basis( U ) );
    n := Length( Zero( U ) );
    for i in [Length(base)+1..n] do
        Add( base, Zero(U) );
    od;
    null := NullspaceMat( TransposedMat( base ) );
    return VectorSpace( LeftActingDomain(U), null, Zero(U), "basis" );
end );


#############################################################################
##
#E